Skip to content

NativeAOT retains an unused lambda but eliminates an unused interface implementation #137809

Description

@eiriktsarpalis

Native AOT retains the target method of a delegate that is never invoked. An instance of a single-method interface implementation that is kept alive in the same way has its method trimmed.

Related to dotnet/runtime#137566.

Reproduction

Publish each of the following Program.cs files separately, using the same Repro.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <PublishAot>true</PublishAot>
    <IlcGenerateMapFile>true</IlcGenerateMapFile>
  </PropertyGroup>
</Project>

Lambda:

System.GC.KeepAlive(() => 42);

Interface:

System.GC.KeepAlive(new Factory());

interface IFactory { int Get(); }
class Factory : IFactory { public int Get() => 42; }
dotnet publish -c Release -r win-x64 -o published

GC.KeepAlive is there only so that the delegate and the Factory instance are both constructed. Without it, the unused Factory allocation is eliminated altogether and the comparison no longer holds. The lambda is retained either way; var unused = () => 42; also reproduces.

Observed behavior

Both programs run successfully. In obj\Release\net11.0\win-x64\native\Repro.map.xml:

Version Object constructed Target method retained
Lambda Yes (Func<int>, cached in <>c) Yes: Repro_Program___c____Main___b__0_0
Interface Yes: ConstructedEEType ??_7Repro_Factory@@6B@ No: there is no Factory.Get body

Expected behavior

I would expect a delegate that is never invoked to be handled like an interface implementation whose method is never called, so that its target can be trimmed. Is retaining the target an inherent requirement of how delegates are represented, or could Native AOT recognize this case?

Environment

  • Windows x64; RID win-x64.
  • .NET SDK 11.0.100, targeting net11.0.
  • Native AOT compiler package runtime.win-x64.Microsoft.DotNet.ILCompiler/11.0.0.

Activity

  1. added
    untriaged
    on Nov 18, 2026
  2. dotnet-policy-service commented on Nov 18, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @agocke, @dotnet/ilc-contrib
    See info in area-owners.md if you want to be subscribed.

  3. changed the title [-]NativeAOT retains uninvoked lambda bodies but trims equivalent interface implementations[/-] [+]NativeAOT retains an unused lambda but eliminates an unused interface implementation[/+] on Nov 18, 2026
  4. MichalStrehovsky commented on Nov 18, 2026

    @MichalStrehovsky
    Member

    Trimming works on larger entities than individual instructions. Codegen removes individual instructions because it knows about things such as side effects (moving to codegen area path). Is this the whole pattern? Just an unused delegate creation that is never stored anywhere and never passed to anything?

  5. added
    area-CodeGen-coreclr
    and removed on Nov 18, 2026
  6. dotnet-policy-service commented on Nov 18, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  7. MichalStrehovsky commented on Nov 18, 2026

    @MichalStrehovsky
    Member

    Oh, wait this is the thing where the C# compiler will actually store the allocated lambda into a static and read it from there.

    .method private hidebysig static void  '<Main>$'(string[] args) cil managed
    {
      .entrypoint
      // Code size       37 (0x25)
      .maxstack  8
      IL_0000:  ldsfld     class [System.Runtime]System.Func`1<int32> Program/'<>c'::'<>9__0_0'
      IL_0005:  dup
      IL_0006:  brtrue.s   IL_001f
      IL_0008:  pop
      IL_0009:  ldsfld     class Program/'<>c' Program/'<>c'::'<>9'
      IL_000e:  ldftn      instance int32 Program/'<>c'::'<<Main>$>b__0_0'()
      IL_0014:  newobj     instance void class [System.Runtime]System.Func`1<int32>::.ctor(object,
                                                                                           native int)
      IL_0019:  dup
      IL_001a:  stsfld     class [System.Runtime]System.Func`1<int32> Program/'<>c'::'<>9__0_0'
      IL_001f:  call       void [System.Runtime]System.GC::KeepAlive(object)
      IL_0024:  ret
    } // end of method Program::'<Main>$'
    
    
    

    Yeah, no, this would require very advanced analysis that I don't expect us to have anytime soon. It requires proving that the field that is being written here is only ever read in this same spot, so this is not just an allocation+delegate creation, but also a dead store from codegen perspective.

  8. teo-tsirpanis commented on Nov 18, 2026

    @teo-tsirpanis
    Contributor

    If it would help, Roslyn could skip the caching when the lambda is surrounded by a new, matching what it does with method groups. Right now both lambda cases do cache:

    using System;
    
    // Uses cached delegate
    GC.KeepAlive(() => 42);
    GC.KeepAlive(new Func<int>(() => 42));
    GC.KeepAlive(F);
    // Does not use cached delegate
    GC.KeepAlive(new Func<int>(F));
    
    static int F() => 42;
  9. eiriktsarpalis commented on Nov 18, 2026

    @eiriktsarpalis
    MemberAuthor

    If it would help, Roslyn could skip the caching when the lambda is surrounded by a new, matching what it does with method groups.

    If that ends up helping the linker, I could also do it manually in my generated code.

  10. teo-tsirpanis commented on Nov 18, 2026

    @teo-tsirpanis
    Contributor

    Before considering more advanced analysis, it sounds easier to treat delegates as micro-interfaces with an Invoke method, and trim all methods referenced by delegates of type say D, if no instance of D gets invoked (or its Method property called). This won't be very helpful with Func and Action delegates of common types, but for #137566 we would be able to trim the reflection code if no Func<IAttributeProvider> gets invoked anywhere in the app.

  11. MichalPetryka commented on Nov 18, 2026

    @MichalPetryka
    Contributor

    Oh, wait this is the thing where the C# compiler will actually store the allocated lambda into a static and read it from there.

    .method private hidebysig static void  '<Main>$'(string[] args) cil managed
    {
      .entrypoint
      // Code size       37 (0x25)
      .maxstack  8
      IL_0000:  ldsfld     class [System.Runtime]System.Func`1<int32> Program/'<>c'::'<>9__0_0'
      IL_0005:  dup
      IL_0006:  brtrue.s   IL_001f
      IL_0008:  pop
      IL_0009:  ldsfld     class Program/'<>c' Program/'<>c'::'<>9'
      IL_000e:  ldftn      instance int32 Program/'<>c'::'<<Main>$>b__0_0'()
      IL_0014:  newobj     instance void class [System.Runtime]System.Func`1<int32>::.ctor(object,
                                                                                           native int)
      IL_0019:  dup
      IL_001a:  stsfld     class [System.Runtime]System.Func`1<int32> Program/'<>c'::'<>9__0_0'
      IL_001f:  call       void [System.Runtime]System.GC::KeepAlive(object)
      IL_0024:  ret
    } // end of method Program::'<Main>$'
    

    Yeah, no, this would require very advanced analysis that I don't expect us to have anytime soon. It requires proving that the field that is being written here is only ever read in this same spot, so this is not just an allocation+delegate creation, but also a dead store from codegen perspective.

    Wouldn't #85014 make this much easier?

  12. MichalStrehovsky commented on Nov 19, 2026

    @MichalStrehovsky
    Member

    Wouldn't #85014 make this much easier?

    It would probably get trivially removed for the use case in the top post (the delegate is not actually used for anything).

    It would still not be enough if the delegate is actually stored somewhere, returned from a method, passed as a parameter, etc. That would need yet another piece of analysis to solve global data flow (and it would need to be a pattern that is actually statically solvable, not some halting problem kind of thing). Trimming only looks at control flow, not at data flow.

  13. MichalStrehovsky commented on Nov 19, 2026

    @MichalStrehovsky
    Member

    Before considering more advanced analysis, it sounds easier to treat delegates as micro-interfaces with an Invoke method, and trim all methods referenced by delegates of type say D, if no instance of D gets invoked (or its Method property called). This won't be very helpful with Func and Action delegates of common types, but for #137566 we would be able to trim the reflection code if no Func<IAttributeProvider> gets invoked anywhere in the app.

    In theory yes, but all of this breaks down the moment someone calls Delegate.Method, or Delegate.DynamicInvoke or any of the other ways how the target of the delegate could matter. And we still cannot pretend the delegate is simply null, so we still need to allocate something.

  14. JulieLeeMSFT commented on Nov 25, 2026

    @JulieLeeMSFT
    Member

    cc @dotnet/jit-contrib.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    JIT-DeadStoreEliminationarea-CodeGen-coreclruntriaged

    Type

    No type

    Projects

    • Status
      No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions