Repository navigation
Optimize handling of exact-match types - #165795
nnethercote wants to merge 3 commits into
Conversation
|
@bors try @rust-timer queue |
This comment has been minimized.
This comment has been minimized.
Optimize handling of exact-match types
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
Finished benchmarking commit (56f1bf8): comparison URL. Overall result: ✅ improvements - no action neededBenchmarking means the PR may be perf-sensitive. It's automatically marked not fit for rolling up. Overriding is possible but disadvised: it risks changing compiler perf. @bors rollup=never rustc-perf Instruction countOur most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.
Max RSS (memory usage)Results (primary -2.4%, secondary 0.5%)A less reliable metric. May be of interest, but not used to determine the overall result above.
CyclesResults (primary -7.4%, secondary -7.1%)A less reliable metric. May be of interest, but not used to determine the overall result above.
Binary sizeThis perf run didn't have relevant results for this metric. Bootstrap: 482.775s -> 485.777s (0.62%) |
|
LLM disclosure: I use LLM analysis to help with this. I wrote the code and text myself. |
|
Perf results are very good:
Ironically I set out to improve performance of the new solver relative to the old solver, but I ended up improving both roughly equally, so the new solver vs. old solver relative comparison isn't any better. The code is in good shape but I need to write tests. Before I do that I want to get feedback from trait solver experts on whether this is a reasonable idea, given that this code adds a moderate level of complexity. |
|
Wow, this is a huge win! I'll also ping @adwinwhite, who knows the solver better than I do 😅 |
|
I moved it out of draft status because I think the compiler code is in good enough shape. |
|
The perf is really nice. I'll get to this tomorrow. |
| /// property to skip uninteresting cases. Useful for candidate assembly, but not for auto-trait | ||
| /// existence checks, for example. |
There was a problem hiding this comment.
So if we use for_each_candidate_impl in disqualify_auto_trait_candidate_due_to_possible_impl, some tests would fail? 🤔
I wonder whether we can replace for_each_relevant_impl completely. Having two similar but slightly different methods doesn't look good :3
There was a problem hiding this comment.
Given that a type is not exact-match if it contains Param, #84857 wouldn't happen again due to this change? 🤔
Besides, we can properly reject this:
struct Foo<T>(T);
unsafe impl Send for Foo<u8> {}
trait WithAssoc { type Output; }
impl<T: Send> WithAssoc for T { type Output = Self; }
impl WithAssoc for Foo<u32> { type Output = Box<i32>; }We can look into this separately though.
There was a problem hiding this comment.
So if we use for_each_candidate_impl in disqualify_auto_trait_candidate_due_to_possible_impl, some tests would fail?
It's likely that no tests would fail because, as written, the exact-match optimization doesn't kick in unless there are 16 or more impls in one simp bucket. But I think it would be possible to write a test where doing that would fail.
Having two similar but slightly different methods doesn't look good
The difference between the two functions is basically "could unify?" vs "exists for this root".
Given that a type is not exact-match if it contains Param, #84857 wouldn't happen again due to this change?
I think that's correct. Any type containing Param should be entirely unaffected by this PR.
There was a problem hiding this comment.
The difference between the two functions is basically "could unify?" vs "exists for this root".
I think the two aren't cleanly distinguishable semantically, since the optimization in for_each_candidate_impl is only triggered sometimes.
Given that completely removing the old one is risky and requires more careful consideration, we can tackle it separately and land this as is.
| /// The following types are "exact-match": | ||
| /// - Scalar types: `bool`, `char`, integers, floats, `str`, and `!`. | ||
| /// - Certain aggregate types (ADTs, tuples, arrays, slices) that satisfy the following: | ||
| /// - Any type parameters must themselves be exact-match types. | ||
| /// - Any const parameters must be trivial `usize` leaf consts. | ||
| /// - No region parameters are allowed. | ||
| /// | ||
| /// The crucial thing that follows is that we can trivially test if two exact-match `Ty`s unify via | ||
| /// equality: they unify iff they are equal. This property is used to optimize candidate selection, | ||
| /// most notably in cases where a single generic ADT is instantiated many times. E.g. `bitmaps` has | ||
| /// a type `BitsImpl<N>` that is instantiated over 1024 distinct values of `N`, all of which impl a | ||
| /// single trait `Bits`. |
There was a problem hiding this comment.
How about we start with the definition of exact_match types and then list what it currently consists of :>
My understanding is that the list follows from the principle that a Ty is exact-match if its unification with another type implies equality. (Mainly, this means an exact-match type doesn't contain types that could be further resolved or instantiated.)
| // because it's possible for consts with different types but equal values (e.g. `5usize` | ||
| // and `5u64`) to unify. `usize` is the type that shows up in various real-world crates |
There was a problem hiding this comment.
Is the unification really possible? The const type is already determined by ADT's DefId so that we can't have both struct A<const N: usize> and struct A<const N: u64> 🤔
There was a problem hiding this comment.
Hmm, I think you are right. I thought this was possible because structurally_relate_consts doesn't consider the type when comparing two leaf values, but I guess we can't ever get to that point if the types are different?
There was a problem hiding this comment.
yeah, it should be impossible so we don't check the types in structurally_relate_consts
There was a problem hiding this comment.
The comments here need to be updated?
| let exact_match_self_tys = | ||
| tcx.trait_impl_exact_match_self_tys((trait_def_id, simp)); | ||
| assert_eq!(impls_for_type.len(), exact_match_self_tys.len()); | ||
| for (&impl_def_id, &exact_match_self_ty) in | ||
| iter::zip(impls_for_type, exact_match_self_tys) |
There was a problem hiding this comment.
We can directly return impl_def_id from the query trait_impl_exact_match_self_tys instead of zip here?
There was a problem hiding this comment.
Ok. More data to store in the query table, but less zipping... probably makes little difference to perf overall.
|
@rustbot author |
|
Reminder, once the PR becomes ready for a review, use |
`simplify_type` simplifies a type (if possible) to its outermost injective layer, which lets us partition types into small sets of possibly unifiable types. This works well for performance except for one case: ADTs with generic params and many instances. For example, `bitmaps` has `impl Bits for BitsImpl<N>` for 1024 distinct const values of `N`, all of which need to be proved distinct the expensive way. This commit adds a mechanism to make these cases cheaper. It introduces the concept of an "exact-match" type, which is one where simple `Ty` equality is enough to determine if two types unify. When exact-match types are involved, we can do various checks much more quickly. This requires: - a new visitor that determines if a type is exact-match - a new query - some new methods, most notably `for_each_candidate_impl`, which is an optimized version of the existing `for_each_relevant_impl` This gives big wins on benchmarks that stress the trait solver (new and old) such as `bitmaps`, `typenum`, `hybrid-array`, `arraystring`.
When inserting into the specialization graph, we can use exact-match status to avoid some expensive overlap checks.
- Remove unnecessary `usize` const restriction - Store `DefId` for each entry in the `trait_impl_exact_match_self_tys` query. - Comment improvements
1da59c5 to
bd06a5a
Compare
|
This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed. Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers. |
|
I have added a new commit to address the comments. @rustbot ready |
| // because it's possible for consts with different types but equal values (e.g. `5usize` | ||
| // and `5u64`) to unify. `usize` is the type that shows up in various real-world crates |
There was a problem hiding this comment.
The comments here need to be updated?
| /// property to skip uninteresting cases. Useful for candidate assembly, but not for auto-trait | ||
| /// existence checks, for example. |
There was a problem hiding this comment.
The difference between the two functions is basically "could unify?" vs "exists for this root".
I think the two aren't cleanly distinguishable semantically, since the optimization in for_each_candidate_impl is only triggered sometimes.
Given that completely removing the old one is risky and requires more careful consideration, we can tackle it separately and land this as is.
There was a problem hiding this comment.
it's subtle that for_each_candidate_impl must not be used for the auto trait check
rust/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs
Lines 1396 to 1414 in 0259d5e
A few more thoughts:
"exact match" feels confusing to me. We tend to use "structural identity" here. As in "self_ty_structural_identity". "exact match" is a new terminology and got me to think of pattern matching or StructuralPartialEq.
"types with exact structural equality" feels like maybe how i would talk about it
I dislike having both for_each_candidate_impl and for_each_relevant_impl. In a way there's for_each_impl_reject_via_self_ty and for_each_impl_reject_via_self_ty_shallow/for_each_impl_reject_via_simplified_self_ty 🤔 that makes it a lot clearer what's going on
If we make this a TypeFlag we could change the DeepRejectCtxt to also have a "typeflag set for both types, if so, deep reject if not structurally identical" fast path, which would be good for non-self types. Unsure how big of an effect it would have
|
I guess I do consider the first two considerations to be blocking I think 🤔 |
|
☔ The latest upstream changes (presumably #166507) made this pull request unmergeable. Please resolve the merge conflicts by rebasing. |
Which two are the first two? The
Is this objection just a question of naming (easy to fix), or is the presence of the split (harder)?
"Structural equality" means "two types are syntactically identical", right? That allows regions, and inference variables, etc. "Semantic identity/equality" basically means "two types are equall even though they might not be syntactically identical". Both of these are relationships between two types. The "exact-match" concept applies to a single type. When comparing two exact-match types, syntactic equality is semantic equality. It's a new concept so it deserves a new name. What do you think about "structurally-unifiable"? It's longer than "exact-match", but brings in the notion of structural equality without using "equality" (to avoid confusion with
Interesting idea. Would be a good follow-up. |
View all comments
Details in individual commits. When looking at these changes,
is_exact_match_tyis a good place to start.r? @adwinwhite