Skip to content

Add a fast path to match exhaustiveness checking. - #166637

Open
kpreid wants to merge 3 commits into
rust-lang:mainfrom
kpreid:fast-match
Open

kpreid wants to merge 3 commits into
rust-lang:mainfrom
kpreid:fast-match

Conversation

@kpreid

@kpreid kpreid commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

View all comments

The new function is_obviously_one_to_one() checks matches in O(n) time, provided that they are matching fieldless enums, with exactly one arm per variant and no guards, in exactly the declaration order of the variants. My hope is that this is a pattern common enough, particularly in derive macros, to make this extra mode worthwhile.

Inspired by @panstromek’s blog post https://yoyo-code.com/derive-debug-compile-time-improvements/, linked from This Week in Rust issue 679, which said:

Of course, we should also adress the match checking cost. We can maybe do something wacky in the derive, but I think the proper way to fix it is just optimizing the algorithm, because it really doesn't have to be quadratic in this case. That's easier said than done because the algorithm is quite complex, but it should be doable.

This change is an attempt to get the “doesn’t have to be quadratic” benefits without needing to think hard about optimization. And if the general algorithm ever does get optimized in that way, this will be easy to rip out.

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Nov 27, 2026
@jhpratt

jhpratt commented Nov 27, 2026

Copy link
Copy Markdown
Member

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Nov 27, 2026
@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Nov 27, 2026
Add a fast path to match exhaustiveness checking.
@rust-bors

rust-bors Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 7fb128a (7fb128a59c97ba774db4425481ecbf97257ac602)
Base parent: 16bf51a (16bf51a54a6e9065fe045f7cb99c49079a17dcba)

@rust-timer

This comment has been minimized.

@rust-timer

Copy link
Copy Markdown

Finished benchmarking commit (7fb128a): comparison URL.

Overall result: ❌✅ regressions and improvements - please read:

Benchmarking means the PR may be perf-sensitive. Consider adding rollup=never if this change is not fit for rolling up.

Next, please: If you can, justify the regressions found in this try perf run in writing along with @rustbot label: +perf-regression-triaged. If not, fix the regressions and do another perf run. Neutral or positive results will clear the label automatically.

@bors rollup=iffy rustc-perf
@rustbot label: -S-waiting-on-perf +perf-regression

Instruction count

Our most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.

mean range count
Regressions ❌
(primary)
0.3% [0.3%, 0.4%] 2
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-18.4% [-35.2%, -0.3%] 11
All ❌✅ (primary) 0.3% [0.3%, 0.4%] 2

Max RSS (memory usage)

Results (primary 3.2%, secondary 0.5%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
3.2% [1.8%, 4.5%] 4
Regressions ❌
(secondary)
1.3% [0.4%, 2.5%] 16
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-5.8% [-5.8%, -5.7%] 2
All ❌✅ (primary) 3.2% [1.8%, 4.5%] 4

Cycles

Results (primary -2.5%, secondary -2.1%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
3.0% [3.0%, 3.0%] 1
Regressions ❌
(secondary)
6.1% [0.7%, 13.0%] 18
Improvements ✅
(primary)
-3.9% [-5.5%, -2.4%] 4
Improvements ✅
(secondary)
-23.2% [-28.8%, -1.4%] 7
All ❌✅ (primary) -2.5% [-5.5%, 3.0%] 5

Binary size

This perf run didn't have relevant results for this metric.

Bootstrap: 460.722s -> 461.446s (0.16%)
Artifact size: 405.70 MiB -> 405.97 MiB (0.06%)

@rustbot rustbot added perf-regression Performance regression. and removed S-waiting-on-perf Status: Waiting on a perf run to be completed. labels Nov 27, 2026
@panstromek

panstromek commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Nice! It's not surprising that enum-stress improves, that one is the pathological case, but I'd like to know what's happening with cranelift-codegen. This is supposed to have broader positive impact than just the stress test (the original PR improved wg-grammar as well). Maybe we need to carve out the fast path a bit more specifically (e.g. only apply it for matches with more than N arms).

For context, here's a thread on zulip where this was discussed some time ago: https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/derive.28Debug.29.20expansion.20for.20enums.20is.20not.20that.20good/with/618210698

The new function `is_obviously_one_to_one()` checks `match`es in O(n)
time, provided that they are matching fieldless enums, with exactly one
arm per variant and no guards, in exactly the declaration order of the
variants. My hope is that this is a pattern common enough, particularly
in derive macros, to make this extra mode worthwhile.

Inspired by <https://yoyo-code.com/derive-debug-compile-time-improvements/>,
linked from This Week in Rust issue 679, which said:

> Of course, we should also adress the match checking cost. We can maybe
> do something wacky in the derive, but I think the proper way to fix it
> is just optimizing the algorithm, because it really doesn't have to be
> quadratic in this case. That's easier said than done because the
> algorithm is quite complex, but it should be doable.

This change is an attempt to get the “doesn’t have to be quadratic”
benefits without needing to think hard about optimization. And if the
general algorithm ever does get optimized in that way, this will be
easy to rip out.
@kpreid

kpreid commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

The perf results appear to show that this is working more or less as I expected: great improvement in the enum-stress secondary benchmark, slight regression elsewhere due to doing an additional check.

I suspect that most of the added cost is calling ctors_for_ty() an additional time. This could be reduced by arranging so the result is reused, but it isn’t immediately obvious to me how to achieve that; it could also help if PatCx had a method for cheaply asking "is this a fieldless-enum-shaped type?" to short-circuit before calling ctors_for_ty() at all. Or perhaps there’s something even better I’ve missed due to not being familiar with this part of the compiler.

But this might be worth it even as-is?

@kpreid
kpreid marked this pull request as ready for review November 27, 2026 07:52
@rustbot

rustbot commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Some changes occurred in exhaustiveness checking

cc @Nadrieril

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Nov 27, 2026
@rustbot

rustbot commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

r? @adwinwhite

rustbot has assigned @adwinwhite.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: compiler
  • compiler expanded to 79 candidates
  • Random selection from 21 candidates

@panstromek

Copy link
Copy Markdown
Contributor

I suspect that most of the added cost is calling ctors_for_ty() an additional time.

From the cachegrind diff, it looks like that's about 8% of the incrase. The biggest incrase (~40%) is directly in analyze_match (where the rest of the code gets inlined probably).

The top of the diff is here, but there's a fair bit of inlining noise

Ir_________________ 

60,608,399 (100.0%)  PROGRAM TOTALS

--------------------------------------------------------------------------------
-- File:function summary
--------------------------------------------------------------------------------
  Ir___________________________  file:function

<  59,585,985   (98.3%,  98.3%)  ???:
   90,317,429  (149.0%)            <rustc_hir_typeck::fn_ctxt::FnCtxt>::instantiate_value_path
  -67,816,955 (-111.9%)            <rustc_hir_typeck::fn_ctxt::FnCtxt>::check_expr_path
   26,823,471   (44.3%)            rustc_pattern_analysis::rustc::analyze_match
  -17,709,348  (-29.2%)            <rustc_hir_typeck::fn_ctxt::FnCtxt>::add_required_obligations_for_hir
    8,896,314   (14.7%)            <rustc_middle::ty::context::TyCtxt>::eval_stability
    8,030,012   (13.2%)            <rustc_middle::ty::inhabitedness::inhabited_predicate::InhabitedPredicate>::instantiate_opt
    5,338,324    (8.8%)            <rustc_pattern_analysis::rustc::RustcPatCtxt>::ctors_for_ty
    3,997,760    (6.6%)            <rustc_type_ir::binder::ArgFolder<rustc_middle::ty::context::TyCtxt> as rustc_type_ir::fold::TypeFolder<rustc_middle::ty::context::TyCtxt>>::fold_ty
    3,540,409    (5.8%)            <rustc_ast_lowering::LoweringContext>::lower_ty_direct_lifetime
   -3,381,916   (-5.6%)            <rustc_pattern_analysis::pat::DeconstructedPat<rustc_pattern_analysis::rustc::RustcPatCtxt>>::walk::<rustc_pattern_analysis::usefulness::compute_match_usefulness<rustc_pattern_analysis::rustc::RustcPatCtxt>::{clos
ure#0}::{closure#0}>
    3,373,284    (5.6%)            <rustc_pattern_analysis::pat::DeconstructedPat<rustc_pattern_analysis::rustc::RustcPatCtxt>>::walk::<rustc_pattern_analysis::usefulness::compute_match_usefulness<rustc_pattern_analysis::rustc::RustcPatCtxt>::{clos
ure#1}::{closure#0}>
    3,282,450    (5.4%)            <rustc_middle::ty::inhabitedness::inhabited_predicate::InhabitedPredicate>::apply_inner::<!, <rustc_middle::ty::inhabitedness::inhabited_predicate::InhabitedPredicate>::apply_revealing_opaque<<rustc_pattern_analys
is::rustc::RustcPatCtxt>::is_uninhabited::{closure#0}>::{closure#0}, <rustc_pattern_analysis::rustc::RustcPatCtxt>::is_uninhabited::{closure#0}>
   -3,097,820   (-5.1%)            <rustc_trait_selection::traits::select::SelectionContext>::assemble_candidates_from_impls
    2,812,783    (4.6%)            <rustc_trait_selection::traits::select::SelectionContext>::candidate_from_obligation_no_cache
   -2,473,095   (-4.1%)            <rustc_middle::ty::generic_args::GenericArgs as rustc_type_ir::fold::TypeFoldable<rustc_middle::ty::context::TyCtxt>>::fold_with::<rustc_infer::infer::resolve::DeepResolverIgnoringRegions>
    2,200,288    (3.6%)            <rustc_middle::ty::inhabitedness::inhabited_predicate::InhabitedPredicate>::apply_inner::<!, <rustc_middle::ty::inhabitedness::inhabited_predicate::InhabitedPredicate>::apply_revealing_opaque<<rustc_pattern_analys
is::rustc::RustcPatCtxt>::ctors_for_ty::{closure#2}>::{closure#0}, <rustc_pattern_analysis::rustc::RustcPatCtxt>::ctors_for_ty::{closure#2}>
   -2,050,133   (-3.4%)            <rustc_ast_lowering::LoweringContext>::lower_ty
    1,954,724    (3.2%)            <rustc_middle::ty::context::CtxtInterners>::intern_alias
    1,691,662    (2.8%)            <rustc_hir_typeck::fn_ctxt::FnCtxt>::coerce
    1,553,033    (2.6%)            <rustc_middle::ty::inhabitedness::inhabited_predicate::InhabitedPredicate>::reduce_or
   -1,552,712   (-2.6%)            <rustc_trait_selection::traits::engine::ObligationCtxt<rustc_trait_selection::traits::FulfillmentError>>::normalize::<rustc_middle::ty::Ty>
    1,542,336    (2.5%)            rustc_metadata::rmeta::encoder::should_encode_mir

But this might be worth it even as-is?

I'd myself like to see this neutral or green on primary benchmarks, unless that proves to be super difficult. We don't want to get into a situation where we regress many real world use cases by a little amount for a rare perf improvement on fairly artificial stress test. cranelift-codegen regression might be a bit of a canary for that scenario.

@Nadrieril

Nadrieril commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Most ADTs aren't fieldless enums, I'm unconvinced that speeding up that one case is particularly interesting. E.g. I would have wanted such an improvement to affect the syn benchmark which is full of derives on various realistic enums and structs (EDIT: looks like it's only PartialEq derives so I guess this can't apply).

}

// Fast path for matches that pair up 1:1 with a fieldless enum.
if is_obviously_one_to_one(tycx, arms, &scrut_ty)? {

@panstromek panstromek Nov 27, 2026 •

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.

I think I'd probably try gating this behind something like if arms.len() > N in here (I'd try N=16 or something in that ballpark).

View changes since the review

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.

It might even be lower, but the point is to skip the most common false positives that are the 2-3 variants cases like Option, Result, ? operator and things like that.

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.

Added arms.len() > 16 in 0caad93.

Comment on lines +1912 to +1919
let MatchArm { pat: arm_pat, has_guard: false, arm_data: _ } = arm else {
// The arm has a guard.
return false;
};
let pat_ctor @ &Constructor::Variant(pat_variant_idx) = arm_pat.ctor() else {
// The pattern is not the right kind of pattern.
return false;
};

@panstromek panstromek Nov 27, 2026 •

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.

I'd also try checking these arm paths before the ctors_for_ty lookup, maybe with some simple probe that checks just first few items and the last one. Last one is often wildcard, so that could help us skip a lot of cases. It's also common to have the last variant be the most complex one, but that's just my intuition.

View changes since the review

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.

Added this check in 6b1159e. Instead of “first and last” I just have it scan the whole sequence, but in reverse. First and last might be a better idea, but I didn’t want to complicate the code further — let's see what happens.

@panstromek

panstromek commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Most ADTs aren't fieldless enums, I'm unconvinced that speeding up that one case is particularly interesting.

To be fair, that case is motivated by real world issue. I guess more importantly, I think this fast path could also be a starting point that could be extended to simple matches on non-fieldless enums in the future. But I definitely have a feeling that we're silently regressing the common case here. Matches on fieldless enums are not that uncommon, this should have a broader positive impact.

[edit] More specifically, I'd expect improvement on ucd, wg-grammar and stm32f4, those are benchmarks involved in the original optimization.

@Nadrieril

Copy link
Copy Markdown
Member

To be fair, that case is motivated by real world issue

It is? Your post mentions @theemathas's case of an enum with 10000 variants, which also says that for 1000 variants the compile time is bad but not abysmal. Even an enum with 1000 unit variants does not seem real world to me, is it?

@theemathas

Copy link
Copy Markdown
Contributor

I've seen two or three people run into this problem on discord so far. They were doing something like listing all sprites in a game.

@theemathas

Copy link
Copy Markdown
Contributor

Relevant issues: #133945, #7462

@Nadrieril

Copy link
Copy Markdown
Member

There's an idea I've had for a while to avoid the quadratic behavior; I tested it out here #166656 , looks promising! Working on making a proper implementation now.

@kpreid

kpreid commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

I've seen two or three people run into this problem on discord so far. They were doing something like listing all sprites in a game.

This is the type of use case I am personally interested in — a large set of entities relevant to the application, each of which is identified by a single enum variant. That said, my enums aren’t yet so big that this PR will likely make a significant difference to them.

@maxdexh

maxdexh commented Nov 27, 2026

Copy link
Copy Markdown
Member

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Nov 27, 2026
@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Nov 27, 2026
Add a fast path to match exhaustiveness checking.
@rust-bors

rust-bors Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: c7e6b2b (c7e6b2b507fee76ec892f586f1e17f2860b22075)
Base parent: b61bfe5 (b61bfe5f22374c5570299aee056c23ad9acc81ff)

@rust-timer

This comment has been minimized.

@rust-timer

Copy link
Copy Markdown

Finished benchmarking commit (c7e6b2b): comparison URL.

Overall result: ❌✅ regressions and improvements - please read:

Benchmarking means the PR may be perf-sensitive. Consider adding rollup=never if this change is not fit for rolling up.

Next, please: If you can, justify the regressions found in this try perf run in writing along with @rustbot label: +perf-regression-triaged. If not, fix the regressions and do another perf run. Neutral or positive results will clear the label automatically.

@bors rollup=iffy rustc-perf
@rustbot label: -S-waiting-on-perf +perf-regression

Instruction count

Our most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
1.9% [1.9%, 1.9%] 6
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-22.4% [-35.2%, -0.2%] 9
All ❌✅ (primary) - - 0

Max RSS (memory usage)

Results (primary 3.7%, secondary -2.0%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
3.7% [3.7%, 3.7%] 1
Regressions ❌
(secondary)
0.4% [0.4%, 0.5%] 3
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-5.6% [-6.0%, -5.2%] 2
All ❌✅ (primary) 3.7% [3.7%, 3.7%] 1

Cycles

Results (secondary -7.7%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
3.6% [0.7%, 14.7%] 8
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-16.8% [-28.7%, -0.7%] 10
All ❌✅ (primary) - - 0

Binary size

This perf run didn't have relevant results for this metric.

Bootstrap: 462.15s -> 472.536s (2.25%)
Artifact size: 405.59 MiB -> 405.59 MiB (-0.00%)

@rustbot rustbot removed the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Nov 27, 2026
@Nadrieril

Nadrieril commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

I made a proper implementation of my idea here: #166678; it solves the problem at its root :) Namely, the one quadratic behavior is that for each enum constructor we've found in the match, we iterate over all the match rows to keep only the matching ones; that PR entirely removes this behavior by tracking matching rows at the same time that we determine which constructors are present in the match.

So this works for non-unit variants, for PartialEq derives, basically any big match benefits, at the cost of many small allocations.

@kpreid

kpreid commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

I imagine that #166678 will make this PR almost completely pointless if it merges, but I'll keep this one open to check anyway.

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

perf-regression Performance regression. S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants