Skip to content

Enable Enum.HasFlag box elision in Tier0 - #130590

Merged
tannergooding merged 1 commit into
dotnet:mainfrom
tannergooding:tannergooding-jit-t0-box-elision
Jul 14, 2026
Merged

tannergooding merged 1 commit into
dotnet:mainfrom
tannergooding:tannergooding-jit-t0-box-elision

Conversation

@tannergooding

@tannergooding tannergooding commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

The JIT can already elide the boxes generated for Enum.HasFlag in optimized (Tier1) code, but not in Tier0/minopts. This is the motivating case here: Enum.HasFlag at Tier0 allocates and boxes both the this value and the flag argument, then makes a real call, which is a lot of work for something that should fold to a couple of and/cmp instructions.

Root cause

To keep the local count (and prolog zeroing) down, Tier0 shares a single "Reusable Box Helper" temp across boxes. Shared temps carry no exact type, so gtOptimizeEnumHasFlag cannot recover the underlying value and bails, leaving the box in place.

impImportAndPushBox has a carve-out that instead hands integral box values their own single-def exact temp precisely so this elision can fire (added in #89348). However, its condition included isEnum(hClass) != TypeCompareState::Must, which excludes actual enums, the exact case it was meant to enable. So enum boxes kept sharing a temp and never got their exact type.

Fix

Correct the inverted guard from != TypeCompareState::Must to == TypeCompareState::Must so the carve-out targets enum boxes, the case it was written for. This has two effects at Tier0:

  1. Enum boxes get a unique exact temp, so gtOptimizeEnumHasFlag recovers the value and elides the box entirely. This is the allocation win and the motivating fix.
  2. Non-enum integral boxes go back to sharing a reusable temp (their pre-Avoid boxing in Enum.HasFlag in Tier0 #89348 behavior). This does not change which allocations happen; it only reuses a single ref-temp slot across boxes with non-overlapping lifetimes, which shrinks the Tier0 frame and prolog zeroing.

Measured impact

SuperPMI, x64, checked JIT, vs clean main.

Allocations. The only heap allocations removed are the enum HasFlag boxes themselves (CORINFO_HELP_NEWSFAST 2 -> 0 on the HasFlag methods). Non-enum box allocation counts are invariant. A cross-collection NEWSFAST-delta scan confirmed this change never emits more allocations than base (it never reintroduces a box the base was eliding) — the receiver/flag temps are only shared across non-overlapping lifetimes, so a live boxed value is never clobbered.

Code size (asmdiffs). Net -175,983 bytes across 6,641 contexts:

Collection contexts net bytes
aspnet2 53 -2,174
benchmarks.run_pgo 141 -3,850
coreclr_tests 1,363 -37,656
libraries_tests 5,062 -132,292
libraries_tests_no_tiered 22 -11

That is -218,115 bytes of improvements over 4,583 methods against +42,132 bytes of regressions over 1,789 methods. The regressions are small (worst single method +47 bytes, clustered +6..+47) and are Tier0 prolog/mov zero-init churn from the different temp layout when a non-enum box reverts to the shared slot — no added allocations. The bulk of the win is the frame/prolog shrink from re-sharing non-enum integral box temps; the enum box elision itself is the smaller, allocation-reducing slice.

JIT throughput (tpdiff). MinOpts -0.06% (aspnet2) to ~-0.00/-0.01% overall; FullOpts unchanged (shareBoxedTemps is already false there). This is one import-time condition, so per-method JIT work is unchanged — effectively free on throughput.

Tier0 repro. HasFlagConst 103 -> 49 bytes, HasFlagVar 105 -> 59 bytes, with the NEWSFAST/HasFlag calls gone and correct runtime results.

Net: correcting the guard enables the enum box elision at Tier0 (the allocation win) and, as a side effect, restores shared non-enum integral box temps for a substantial additional code-size and PerfScore win, at effectively zero JIT throughput cost.

Note

This PR description was generated with the assistance of GitHub Copilot.

Copilot AI review requested due to automatic review settings July 12, 2026 22:04
@github-actions github-actions Bot added the area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI label Jul 12, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR adjusts Tier0/minopts boxing import behavior so that boxing integral values (including enums) uses per-box single-def, exact-typed temps, enabling existing box-elision optimizations (notably Enum.HasFlag) to trigger in Tier0.

Changes:

  • Stops sharing the “Reusable Box Helper” temp for integral box operations in minopts/debug when the method doesn’t already have many locals.
  • Updates the importer rationale/comments to reflect the Tier0 motivation and intended downstream optimization enablement.
Show a summary per file
File Description
src/coreclr/jit/importer.cpp Refines Tier0/minopts box-temp sharing logic to preserve exact types for integral (incl. enum) boxes, enabling Enum.HasFlag box elision.

Copilot's findings

  • Files reviewed: 1/1 changed files
  • Comments generated: 1

Comment thread src/coreclr/jit/importer.cpp Resolved
@EgorBo

EgorBo commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

The JIT can already elide the boxes generated for Enum.HasFlag in optimized (Tier1) code, but not in Tier0/minopt

It definitely did supposed to be optimized in tier0 as well via #89348

the isEnum check was probably put there to avoid size regressions when we don't reuse the shared box temp

@tannergooding

Copy link
Copy Markdown
Member Author

@EgorBo Maybe, but it’s doing both the opposite of what the comment said it was supposed to do (ie it’s skipping enum and allowing everything else through) and it’s a throughput hit on top to boot.

We’re seeing essentially pure improvement here by actually allowing enums to use the opt in T0: https://dev.azure.com/dnceng-public/public/_build/results?buildId=1505225&view=ms.vss-build-web.run-extensions-tab

@EgorBo

EgorBo commented Jul 13, 2026

Copy link
Copy Markdown
Member

@EgorBo Maybe, but it’s doing both the opposite of what the comment said it was supposed to do (ie it’s skipping enum and allowing everything else through) and it’s a throughput hit on top to boot.

We’re seeing essentially pure improvement here by actually allowing enums to use the opt in T0: https://dev.azure.com/dnceng-public/public/_build/results?buildId=1505225&view=ms.vss-build-web.run-extensions-tab

It's probably because something has been improved since then and it no longer leads to regressions

Comment thread src/coreclr/jit/importer.cpp Resolved
impImportAndPushBox has a Tier0 carve-out that skips box-temp sharing for
integral values so each box gets its own single-def exact temp. gtOptimizeEnumHasFlag
needs that exact temp to recover the value and drop the box. The isEnum guard on
the carve-out was inverted (!= Must), so it applied to everything except enums --
the one case it was added for -- and Enum.HasFlag kept allocating and boxing at Tier0.

Fix the guard to == Must so the carve-out targets enum boxes, restoring the
Enum.HasFlag box elision at Tier0.

Co-authored-by: Copilot App <[email protected]>
Copilot AI review requested due to automatic review settings July 13, 2026 13:38
@tannergooding
tannergooding force-pushed the tannergooding-jit-t0-box-elision branch from f23d0eb to 3f008ad Compare July 13, 2026 13:38
@tannergooding

Copy link
Copy Markdown
Member Author

Force-pushed a rebase onto latest main and switched the fix from dropping the isEnum clause to simply correcting the inverted guard to == TypeCompareState::Must.

Both designs deliver the identical enum HasFlag box elision at the same ~zero throughput cost -- a cross-collection NEWSFAST-delta scan confirmed the two are allocation-equivalent (same boxes removed, neither reintroduces a box). The difference is that == Must also reverts non-enum integral boxes to a shared reusable temp (their pre-#89348 behavior), which shrinks Tier0 frames/prolog zeroing when box lifetimes don't overlap. That takes the net code-size win from ~-31k to -175,983 bytes across the SPMI collections, at effectively zero TP cost. It's also the smaller, original-intent diff (one operator), so it's the better fix.

Updated the description with the full breakdown.

Note

This comment was generated with the assistance of GitHub Copilot.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot's findings

  • Files reviewed: 1/1 changed files
  • Comments generated: 2

Comment thread src/coreclr/jit/importer.cpp Resolved
Comment thread src/coreclr/jit/importer.cpp Resolved
@tannergooding

Copy link
Copy Markdown
Member Author

-175.9k bytes on Windows x64, -88.7k bytes on Windows Arm64. Similar numbers for Linux, and similar TP improvement to the other at [-0.05%, -0.00%]

So altogether better and inline with the original intent, most look to be removing CORINFO_HELP_NEWSFAST calls

@tannergooding
tannergooding merged commit 1286e56 into dotnet:main Jul 14, 2026
136 of 139 checks passed
@tannergooding
tannergooding deleted the tannergooding-jit-t0-box-elision branch July 14, 2026 00:18
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview7 milestone Jul 14, 2026
eiriktsarpalis pushed a commit that referenced this pull request Jul 15, 2026
The JIT can already elide the boxes generated for `Enum.HasFlag` in
optimized (Tier1) code, but not in Tier0/minopts. This is the motivating
case here: `Enum.HasFlag` at Tier0 allocates and boxes both the `this`
value and the flag argument, then makes a real call, which is a lot of
work for something that should fold to a couple of `and`/`cmp`
instructions.

## Root cause

To keep the local count (and prolog zeroing) down, Tier0 shares a single
"Reusable Box Helper" temp across boxes. Shared temps carry no exact
type, so `gtOptimizeEnumHasFlag` cannot recover the underlying value and
bails, leaving the box in place.

`impImportAndPushBox` has a carve-out that instead hands integral box
values their own single-def *exact* temp precisely so this elision can
fire (added in #89348). However, its condition included `isEnum(hClass)
!= TypeCompareState::Must`, which *excludes* actual enums, the exact
case it was meant to enable. So enum boxes kept sharing a temp and never
got their exact type.

## Fix

Correct the inverted guard from `!= TypeCompareState::Must` to `==
TypeCompareState::Must` so the carve-out targets enum boxes, the case it
was written for. This has two effects at Tier0:

1. **Enum boxes get a unique exact temp**, so `gtOptimizeEnumHasFlag`
recovers the value and elides the box entirely. This is the allocation
win and the motivating fix.
2. **Non-enum integral boxes go back to sharing a reusable temp** (their
pre-#89348 behavior). This does not change which allocations happen; it
only reuses a single ref-temp slot across boxes with non-overlapping
lifetimes, which shrinks the Tier0 frame and prolog zeroing.

## Measured impact

SuperPMI, x64, checked JIT, vs clean `main`.

**Allocations.** The only heap allocations removed are the enum
`HasFlag` boxes themselves (`CORINFO_HELP_NEWSFAST` 2 -> 0 on the
`HasFlag` methods). Non-enum box allocation counts are invariant. A
cross-collection `NEWSFAST`-delta scan confirmed this change never emits
*more* allocations than base (it never reintroduces a box the base was
eliding) — the receiver/flag temps are only shared across
non-overlapping lifetimes, so a live boxed value is never clobbered.

**Code size (asmdiffs).** Net **-175,983 bytes** across 6,641 contexts:

| Collection | contexts | net bytes |
|---|--:|--:|
| aspnet2 | 53 | -2,174 |
| benchmarks.run_pgo | 141 | -3,850 |
| coreclr_tests | 1,363 | -37,656 |
| libraries_tests | 5,062 | -132,292 |
| libraries_tests_no_tiered | 22 | -11 |

That is -218,115 bytes of improvements over 4,583 methods against
+42,132 bytes of regressions over 1,789 methods. The regressions are
small (worst single method +47 bytes, clustered +6..+47) and are Tier0
prolog/`mov` zero-init churn from the different temp layout when a
non-enum box reverts to the shared slot — no added allocations. The bulk
of the win is the frame/prolog shrink from re-sharing non-enum integral
box temps; the enum box elision itself is the smaller,
allocation-reducing slice.

**JIT throughput (tpdiff).** MinOpts -0.06% (aspnet2) to ~-0.00/-0.01%
overall; FullOpts unchanged (`shareBoxedTemps` is already false there).
This is one import-time condition, so per-method JIT work is unchanged —
effectively free on throughput.

**Tier0 repro.** `HasFlagConst` 103 -> 49 bytes, `HasFlagVar` 105 -> 59
bytes, with the `NEWSFAST`/`HasFlag` calls gone and correct runtime
results.

Net: correcting the guard enables the enum box elision at Tier0 (the
allocation win) and, as a side effect, restores shared non-enum integral
box temps for a substantial additional code-size and PerfScore win, at
effectively zero JIT throughput cost.

> [!NOTE]
> This PR description was generated with the assistance of GitHub
Copilot.

Co-authored-by: Copilot App <[email protected]>
@github-actions github-actions Bot locked and limited conversation to collaborators Aug 13, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants