Skip to content

ILC: add opt-in per type map group switch to drop runtime-creatable type map keys - #137570

Closed
Sergio0694 wants to merge 1 commit into
dotnet:mainfrom
Sergio0694:user/sergiopedri/ilc-typemap-static-keys
Closed

Sergio0694 wants to merge 1 commit into
dotnet:mainfrom
Sergio0694:user/sergiopedri/ilc-typemap-static-keys

Conversation

@Sergio0694

Copy link
Copy Markdown
Contributor

Adds an opt-in, per type map group switch that stops ILC from keeping type map entries only because their key could be created at run time by the type loader (MakeGenericType, MakeArrayType, lazily built generic dictionaries, etc.).

For the selected groups, proxy entries and external entry trim targets are kept only when the key is statically visible. Default behavior is unchanged. Keys shared with a group that did not opt in stay kept.

Usage

<ItemGroup>
  <IlcTypeMapStaticKeyGroup Include="MyNamespace.MyTypeMapGroup" />
</ItemGroup>
<!-- or, for every group in the app -->
<PropertyGroup>
  <IlcTypeMapStaticKeysForAllGroups>true</IlcTypeMapStaticKeysForAllGroups>
</PropertyGroup>

Underlying ILC option: --typemap-assume-static-keys:<group> (repeatable; * for all groups). Group names use the ECMA type name syntax (Namespace.Outer+Group, optionally ,Assembly). A selector that matches no group only logs a message, so a typo does not fail the build. A separate bool is used for "all groups" since Include="*" would be an MSBuild glob.

This is a promise from the opted-in code that none of its keys are created at run time. If that is wrong, the type is silently missing from the map at run time, so this is intended for libraries that control their own groups.

Motivation and size

CsWinRT 3.0 would expose a high-level, documented property for users to opt into this optimization, and would set the right ILC arguments for its own type map groups (the four WindowsRuntime.InteropServices.*TypeMapGroup marker types), so unrelated groups in the same binary keep the sound behavior.

WinStore.App.dll (Microsoft Store, NativeAOT, size preference), measured on a release/11.0 based build of the same ILC change:

Configuration Size (B) Deflated (B)
Default (no opt-in) 108,068,352 32,396,771
Opt-in for the 4 CsWinRT groups 79,992,320 26,450,672
Opt-in for all groups (*) 79,992,320 not measured

That is -28.1 MB (-26%), and the opt-in alone accounts for the whole difference (it does not depend on #137541). Scoping to just the 4 CsWinRT groups gives the same size as opting in globally.

Testing

On this main based branch (no other changes):

  • TrimmingBehaviors NativeAOT smoke test passes, including a new TestInteropMapStaticKeys case: default behavior unchanged, opted-in group drops runtime-only keys, a second group in the same binary keeps them, statically visible keys and keys shared across groups are kept.
  • src/tests/Interop/TypeMap NativeAOT apps pass.
  • ILCompiler.Trimming.Tests: 621 passed, 4 failed (all "ilasm not found", environmental).

Not verified on main: the Store size numbers above and a Store smoke run in a sandbox (both done on the release/11.0 based build). Not covered: array unwrap rule in GetEffectiveTrimTargetType and ILLink/crossgen2 are intentionally untouched.

Note

This PR description was AI/Copilot-generated.

…ype map keys

Add --typemap-assume-static-keys:<group> (MSBuild item IlcTypeMapStaticKeyGroup,
or IlcTypeMapStaticKeysForAllGroups=true). For the selected type map groups, ILC no
longer keeps proxy entries and external entry trim targets only because the key could
be created by the type loader at run time. Default behavior is unchanged.

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

Sergio0694 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor Author

@MichalStrehovsky @jkoritzinsky FYI this one is likely the most critical one for us. The size difference is pretty insane, and literally all of this extra code that .NET 11 keeps is dead for us anyway, we're never doing lookups with dynamically created types. The idea is this would just be an opt-in, and then CsWinRT 3.0 would expose a high-level property for users to opt-in. When that's done, we'd add the ILC switches for our CsWinRT type maps (e.g. we'd do this in the Store, in all OSClient components, etc.). Other type maps (e.g. from other libraries) are unaffected by default.

Also note, this is an actual regression in .NET 11, the size in .NET 10 was much less for the Store (it seems ILC wasn't rooting those dynamic keys for the interop type map). So this opt-in would at least allow us to get that binary size back. As of right now, we basically cannot upgrade to .NET 11, the size regression for CsWinRT 3.0 is simply too much (it's like +25MB).

The exact property names can change (also why this is a draft), but the idea is pretty much this 😄

@MichalStrehovsky

Copy link
Copy Markdown
Member

What is the overlap in size savings between this and #137541? If you apply 541, how much extra does this PR save.

I've not looked at 541 in detail yet but in principle it should work. This PR is more problematic.

@Sergio0694

Sergio0694 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor Author

This saves ~5MB more than #137541, so it'd still be extremely valuable for us. The idea was that #137541 would be a much better default for everyone, since it just removes entries that can't possibly be needed, and this further lets us be much more aggressive in cases where we know it's fine. Plus if we expose this as an opt-in switch in CsWinRT, we just restrict the blast radius to WinRT marshalling only, without affecting other libraries.

Configuration Size (B) Δ vs neither (B) Δ %
Baseline 108,068,352 n/a n/a
Gate only (#137541) 84,881,408 -23,186,944 -21.5%
Opt-in only (4 CsWinRT groups) 79,992,320 -28,076,032 -26.0%
Gate + opt-in 79,992,320 -28,076,032 -26.0%

In particular in the Store, the opt-in ends up being a strict superset of the gate only.

@MichalStrehovsky

Copy link
Copy Markdown
Member

This saves ~5MB more than #137541, so it'd still be extremely valuable for us. The idea was that #137541 would be a much better default for everyone, since it just removes entries that can't possibly be needed, and this further lets us be much more aggressive in cases where we know it's fine. Plus if we expose this as an opt-in switch in CsWinRT, we just restrict the blast radius to WinRT marshalling only, without affecting other libraries.

What this does is that today it breaks things for any code that is reachable after a generic virtual method call or after a reflection-construction.

So:

Foo f = ...;
f.A();
f.B<string>();
typeof(Foo).GetMethod("C").MakeGenericMethod(typeof(Bar)).Invoke(f, []);


class Foo
{
    void A()
    {
        new Relevant<object>(); // TypeMap sees
    }

    virtual void B<T>()
    {
        new Relevant<T>(); // TypeMap doesn't see
    }

    virtual void C<T>()
    {
        new Relevant<T>(); // TypeMap doesn't see
    }
}

Each of these construct Relevant instance that may or may not be passed to WinRT APIs later. Whether the WinRT API call will work depends on where Relevant was constructed.

Looks like Store doesn't have cases like B and C (or you just didn't exercise all the code paths). The problem with this is that really, you can't tell if this will work before you exercise all the code paths. The other problem is that the failure is very far from the spot that causes the problem. So if this fails for the customer, they're going to file an issue on a native AOT bug because this works with JIT. It will take some investigation on our end until we can say "you did this to yourself, it's your problem, kthxbye".

From that perspective I'd be much more supportive of a mode where generic virtual methods and MakeGeneric API simply don't work. We can statically issue a warning, the failure mode is right there. Then we don't have to be conservative here either. The GVM restriction will include GVMs in the framework.

@MichalStrehovsky

Copy link
Copy Markdown
Member

Also, I qualified this with today because we had a concept called "lazy generics" that uses the type loader a lot more heavily (postponing generic expansion to runtime, saving size). In lazy generics mode, this would apply to pretty much anything created from shared code, not just GVM/reflection.

@MichalStrehovsky

Copy link
Copy Markdown
Member

One more comment to this is that we already limit this to when we see the type loader templates. We'll only create type loader templates for something if it is transitively involved in what the compiler believes is GVM or generic reflection. I'd focus on that: get rid of the GVM/reflection and you'll get rid of the conservative preservation.

@Sergio0694

Copy link
Copy Markdown
Contributor Author

@MichalStrehovsky I'm prototyping it and also trying to publish the Store to get some ballpark binary size saving numbers, and also a concrete idea of the blast radius in a real world app. One question: this feels like it would also need a new RuntimeFeature property so that you can have code conditionally implement things and avoid the restriction when the flag is not set (e.g. for library code), but does that mean we should also implement this mode for CoreCLR then, for constency? So that you can still properly debug your app in AOT-emulation mode when running on CoreCLR and PublishAot set?

Also, I assume we should also add analyzer support for all this, right?
So that you don't need to actually publish to see warnings?

@MichalStrehovsky

Copy link
Copy Markdown
Member

Did you investigate why the compiler thinks the types that trigger the extra generation are targets of reflection/possibly created by GVMs?

Feature switches are always last resort because they cause compat issues. The preferred order is basically:

  1. Find a way to get most or all of the saving without the feature switch.
  2. Add a feature switch that has a predictable failure mode.
  3. Add a feature switch with an unpredictable failure mode (this PR in the current form). We pretty much never do that one (Actually, one comes to mind BuiltInComInteropSupport, I never understood why that one was introduced.)

@MichalStrehovsky

Copy link
Copy Markdown
Member

(The feature switch option is still not the preferred one because it introduces issues that the same code in a unit test work, but doesn't work in the app. Or the same NuGet works in most apps, but not in this one. We reserve feature switch uses to legacy APIs where we cannot change the shape of the API. New APIs should never come with a feature switch, that's just bad API design.)

@Sergio0694

Copy link
Copy Markdown
Contributor Author

Closing this following the conversation with Michal. I think it's useful to get an idea of the upper bound, but as mentioned above it's not great. I have a separate set of changes that should get back most of the savings. One follow-up for this that also saves size is a switch to disable dynamic generics entirely: it precompiles all instantiations and then just makes MakeGeneric* methods throw if you try to construct an instantiation that doesn't exist. That saves another 1-2 MB and doesn't break GVMs, so it seems more usable. I can put up a prototype of that after the other ones for discussion 🙂

@Sergio0694 Sergio0694 closed this Nov 17, 2026
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