Skip to content

JIT: head/tail merge can collapse distinct cast helper calls, losing PGO type profile #128659

Open

Description

@AndyAyersMS

GenTreeCall::Equals does not compare gtCastHelperILOffset for helper calls. As a result, fgHeadTailMerge can merge two structurally-identical CORINFO_HELP_CHKCASTCLASS (or CORINFO_HELP_ISINSTANCEOF*) calls in different return blocks, even when they originate from distinct IL offsets with distinct dynamic class profiles. The merged call retains only one IL offset, so cast helper expansion (pickGDV in helperexpansion.cpp) consults only one site's class profile. Calls whose runtime class matches the other site's profile take the slow helper path instead of the inlined GDV fast path.

This is the same family of bug as #128631 (which was for VSD gtStubCallStubAddr), but for cast helpers.

Repro

 using System;
 using System.Diagnostics;
 using System.Runtime.CompilerServices;
 
 public class Foo { public virtual int Tag => 0; }
 public class Bar : Foo { public override int Tag => 1; }
 public class Baz : Foo { public override int Tag => 2; }
 
 public class Bench
 {
     [MethodImpl(MethodImplOptions.NoInlining)]
     public static Foo Dispatch(int tag, object o)
     {
         // Side effect prevents Roslyn from deduping the two casts at IL level.
         if (tag == 0) { GC.KeepAlive(o); return (Foo)o; }
         return (Foo)o;
     }
 
     public static int Main()
     {
         var bar = new Bar();
         var baz = new Baz();
 
         long sum = 0;
         for (int i = 0; i < 200_000; i++)
         {
             sum += Dispatch(0, bar).Tag;
             sum += Dispatch(1, baz).Tag;
         }
         System.Threading.Thread.Sleep(500);
 
         const int N = 200_000_000;
         var sw = Stopwatch.StartNew();
         for (int i = 0; i < N; i++)
         {
             Foo f1 = Dispatch(0, bar);
             Foo f2 = Dispatch(1, baz);
             sum += f1.Tag + f2.Tag;
         }
         sw.Stop();
         Console.WriteLine($"sum={sum} elapsed={sw.Elapsed.TotalMilliseconds:F1}ms per-iter={sw.Elapsed.TotalNanoseconds / (double)N:F2}ns");
         return 100;
     }
 }

The IL contains two castclass instructions (offsets 0x00A and 0x011). JitDump=Dispatch shows the merge firing:

 *************** Starting PHASE Head and tail merge
 A set of 2 return blocks end with the same tree
    ... CALL help ref CORINFO_HELP_CHKCASTCLASS (100% likely 'Bar')
 Will cross-jump to BB03
 unlinking ... from BB02

After merge, only BB03's IL offset survives; the GDV expansion fast-paths only Bar. The tag=1 path (which only ever sees Baz) loses its fast path.

Measurement (Windows x64, Checked clrjit)

┌────────────────────────────────────────────┬─────────────────────────┐
│ JIT │ Median ns/iter (5 runs) │
├────────────────────────────────────────────┼─────────────────────────┤
│ Current (merges casts) │ 12.3 │
├────────────────────────────────────────────┼─────────────────────────┤
│ Local fix gating on gtCastHelperILOffset │ 9.9 │
└────────────────────────────────────────────┴─────────────────────────┘

≈20% regression caused by the merge in this workload.

Suggested fix

In GenTreeCall::Equals, after the existing helper checks, add:

 if (c1->IsHelperCall() && (c1->gtCastHelperILOffset != c2->gtCastHelperILOffset))
 {
     return false;
 }

(Or scope more narrowly to the actual cast helpers.) Equivalent to the fix in #128654, but for the cast-helper case.

Notes

  • Reachability is gated by Roslyn's IL-level dedup: most natural source patterns produce only one castclass IL instruction over a given local, so head/tail merge can't trigger. A side effect (or other control-flow shape) between the two casts is enough to defeat the dedup.
  • Related fields in the same union (gtStubCallStubAddr already covered by JIT: Fix bug in GenTree::Equals #128654; gtInitClsHnd is also carried as an argument so it's caught by the existing args-equality loop).

Activity

  1. added
    untriaged
    on May 27, 2026
  2. added
    area-CodeGen-coreclr
    on May 27, 2026
  3. dotnet-policy-service commented on May 27, 2026

    @dotnet-policy-service
    Contributor

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

  4. AndyAyersMS commented on May 27, 2026

    @AndyAyersMS
    MemberAuthor

    fyi @EgorBo

    Fix seems simple enough, if it doesn't cause false negatives.

  5. AndyAyersMS commented on May 27, 2026

    @AndyAyersMS
    MemberAuthor

    We run into the same issue as the broader change for #128654 -- we need access to the compiler (say to call impIsCastHelperMayHaveProfileData) but this method and a host of callers are static or have no compiler instance handy.

  6. EgorBo commented on May 27, 2026

    @EgorBo
    Member

    @AndyAyersMS I think we should not return true in GenTree::Compare (or was it Equals) for different IL offsets indeed. Although, if both casts have the same most popular candidate in the PGO data then why not? (even if offsets are different)

  7. added this to the 11.0.0 milestone on May 29, 2026
  8. removed
    untriaged
    on May 29, 2026
  9. AndyAyersMS commented on Jul 2, 2026

    @AndyAyersMS
    MemberAuthor

    Seems like we don't see this all that often, at least in SPMI (though probably not a great place to look for problems). About 100 examples.

    Going to defer this out of 11 -- you ok with that @EgorBo?

  10. EgorBo commented on Jul 2, 2026

    @EgorBo
    Member

    Seems like we don't see this all that often, at least in SPMI (though probably not a great place to look for problems). About 100 examples.

    Going to defer this out of 11 -- you ok with that @EgorBo?

    sounds fine to me

  11. modified the milestones: 11.0.0, Future on Jul 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclr

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions