Trim `GoalStalledOn::Certainty`
It's always `Certainty::Maybe`, so we can trim it down to just the `MaybeInfo` that is within `Certainty::Maybe`.
r? @lcnr
trait solver: Track canonical response universe assumptions
Fixesrust-lang/rust#159889
Canonical responses recreate universes for placeholders created while evaluating a query. Region constraints are handled inside the query, but opaque type constraints can still carry those placeholders back to the caller. Without an assumptions entry, eager placeholder handling hits the `unwrap()` in `get_placeholder_assumptions`.
Record empty assumptions when recreating response universes under `-Zassumptions-on-binders`. idk if empty assumptions is the final shape irl, but imo keeping this next to `create_next_universe` is the right local fix. It restores the invariant where the universe enters the caller and matches bookkeeping from other binder entry paths. fyi the issue repro now reports E0277 instead of ICEing.
It's always `Certainty::Maybe`, so we can trim it down to just the
`MaybeInfo` that is within `Certainty::Maybe`. And then the same change
can be made to the field of `RerunStalled::WontMakeProgress`, and
`goal_remains_stalled` can return a bool, and a hot `matches!` in
`try_evaluate_obligations` that never failed can be removed.
It's expensive and is called unconditionally in
`NormalizesTo::consider_impl_candidate`, which is always called within a
loop. The result is invariant across the loop, so this commit hoists the
call outside of `consider_impl_candidate` and passes the return value in.
Notes:
- At the hoist sites, the expression is `goal.predicate.trait_ref(cx)`;
for `NormalizesTo` this dispatches to
`goal.predicate.alias.trait_ref(cx)`.
- Two other `GoalKind` methods are affected, but this doesn't
change perf because they can get the `goal_trait_ref` cheaply.
`impl_is_default` is moderately expensive. This commit moves the cheaper
`consider_impl_candidate` check (which does `args_may_unify`) ahead, for
a small perf win. (Note: this change makes the new solver match what the
old solver does in `assemble_candidates_from_impls`.)
Rollup of 7 pull requests
Successful merges:
- rust-lang/rust#160629 ([Priroda] Add bootstrap test and check steps)
- rust-lang/rust#160811 (Fix `visible_parent_map` fallback map merging perf regression)
- rust-lang/rust#154329 (Diagnostics ICE when replaying proof trees with next-solver)
- rust-lang/rust#157841 (Ensure inferred let pattern types are well-formed)
- rust-lang/rust#159300 (Implement `to_string()` on `ByteStr` and `ByteString`)
- rust-lang/rust#160858 (Add regression test for assoc const panic ICE in match)
- rust-lang/rust#160864 (Rename `HostEffectPredicate` to `HostEffectClause`)
Optimize new solver unification table ops
The current code uses the `ena` crate in sub-optimal ways. Improving this gives big speed wins for the new trait solver on some benchmarks. Details in individual commits.
r? @lcnr
Diagnostics ICE when replaying proof trees with next-solver
When diagnostics replay proof tree state, rebuilding a canonical state can fail to match the current inference state. With -Znext-solver=globally, this could panic while reporting an error, avoiding the panic.
Make proof tree replay fallible in diagnostics and fall back to the current obligation when replay fails. Add a regression test for the higher-ranked PartialEq and PartialOrd case. Fixesrust-lang/rust#151304.
Keep the original compile-fail reproducer as the ICE guard and add
check-pass coverage for a valid `Trait` implementation while clarifying
the assumptions workaround.
trait_solver: normalize next-gen region constraints
fixesrust-lang/rust#157729
-zassumptions-on-binders can produce next-gen region constraints that mean the same thing but don't have the same shape. in this case object candidate merging stayed ambiguous and instance resolution later hit the ice. imo normalizing the constraint at the response boundary is the least weird place for this, because candidate selection shouldn't need to know which vtable looks nicer.
canonicalize and evaluate the next-gen region constraint before response canonicalization, then cover the dyn derived<p> supertrait case from the issue. lgtm locally with the focused test, tests/ui/traits/next-solver, and tests/ui/assumptions_on_binders. idk if there's a better home for the helper call, but ltm this keeps the fix pretty narrow.
In this case we currently have something approximating this:
```
find(vid) != vid
```
which means "is this not a root var?"
This commit changes it to basically this:
```
!try_probe_value(vid).is_some()
```
which is equivalent but doesn't require any parent chasing.
[perf] Reuse existing trait reference instead of recreating it.
Effectively, do one step of common subexpression elimination, manually. We can reuse the existing interned reference made a few lines prior, without needing to recreate it.
r? @lcnr
**AI disclosure:** The optimization opportunity here was discovered as part of a systematic probe for missed optimizations using a combination of both traditional and AI tools. The code here was initially prototyped and vetted by AI tools, followed by additional manual work. I stand behind the quality of the code I'm submitting, and I vouch it's as good or better than if no AI tools were in the loop.
There are two canonicalization steps done by `canonicalize_input` and
`canonicalize_param_env`: `env` (possible cached) and `rest`.
`canonicalize_param_env` does the `env` step. It returns several pieces
of a canonicalizer (either from the cache or by constructing a
canonicalizer) and then `canonicalize_input` uses those parts to
construct a second canonicalizer, which it uses for `rest`.
This commit changes things so that `canonicalize_param_env` does the
`env` part (if necessary) and then returns a canonicalizer that can do
the `rest` part. I find this easier to read. In particular, we no longer
construct an `env` canonicalizer when it's not necessary, we immediately
construct the `rest` canonicalizer.
This function is very sub-optimal, perf-wise: it takes
`self.obligations.pending` (with `mem::take`) and iterates over the
elements, checking each one. But most of the time no progress is made
and all the obligations get pushed back onto `self.obligations.pending`.
This drain + reconstruct approach is very expensive, mostly because the
new `pending` vec is built by pushing one element at a time, which
requires repeated reallocations. And this vec can have thousands of
elements in it, in extreme cases.
Also, `obligation` and `stalled_on` get passed by value to
`evaluate_root_goal` (`obligation` as `goal`), which then usually passes
the values back in the `GoalEvaluation` which is immediately
deconstructed. This is a lot of wasted value moves.
This commit optimizes things in two ways.
- It prioritizes the hot path. This involves checking in advance if
there is an inspector (usually not) and adding `goal_remains_stalled`
which takes `stalled_on` by reference. This hot path avoids all the
value moves and `GoalEvaluation` construction/deconstruction and gets
to the very common "nothing needed to be done" outcome as quickly as
possible.
- It uses `retain_mut` to update `self.obligations.pending`. This
requires some adjustments (e.g. handling recursion via the
`overflowed` flag with some cleanup code after the `retain_mut` call,
and cloning obligations in the error cases).
Currently it is modified with the very clunky
`canonical_param_env_cache_get_or_insert` method, which takes two
closures.
This commit replaces that with `with_canonical_param_env_cache` a
simpler accessor that is very similar to the nearby `with_global_cache`.
This lets `canonicalize_param_env` use normal hash map operations.
The commit also:
- Introduces a dedicated `CanonicalParamEnvCache` newtype.
- Adds a helpful comment to `CanonicalizeParamEnvCacheEntry::param_env`.
When diagnostics replay proof tree state, rebuilding a canonical
state can fail to match the current inference state. With
-Znext-solver=globally, this could panic because inference
variables created to replay a canonical state were placed in the
wrong universe relative to placeholders bound by the same state.
Fix this by threading a `prev_universe` through proof tree replay:
`InspectGoal` now stores the caller-side universe at the time the
goal was created, and `instantiate_canonical_state` reuses that same
base universe (instead of recomputing it) when creating any
replay-only fresh variables and when reconstructing placeholders
from the canonical state, ensuring all canonical states for a single
goal share a consistent universe mapping.
Add a regression test for the higher-ranked PartialEq and PartialOrd
case.
Signed-off-by: Vicente Gusmão <vicente.gusmao@tecnico.ulisboa.pt>
Rerun the goal with doubled recursion limit even if the goal has ty vars
Fix the `bevy_render` regression and more in the next solver crater run.
The problem is that we don't rerun the root goal with doubled recursion limit if it contains ty vars.
But we actually need the evaluation response to resolve the ty vars. So the type inference fails.
Make `#[fundamental]` only apply to the first argument of `Box`
Per a [discussion with lang](https://rust-lang.zulipchat.com/#narrow/channel/213817-t-lang/topic/.60.23.5Bfundamental.5D.60.20and.20.60Box.3CT.2C.20A.3E.60/with/613236766), it was decided that we want `Box<T, A>` to only be fundamental in `T`. ~~Given that `Box` is the only fundamental type with two generic params, simply make it so only the first param is considered for fundamentalness.~~ ~~`Tuple` is also fundamental, but has its own path in coherence checking and so isn't impacted by this; `Box` is the only thing that is.~~
Since this is just an internal detail and `#[fundamental]` is not in a rush to get stabilised, lang's opinion was that t-compiler has free rein on how to implement this so I figured I'd go with the most straightforward implementation for now. The main alternative I see would be supporting param-position `#[fundamental]` & have the semantics that:
```rust
#[fundamental]
struct Foo<T, U>(T, U);
```
is equivalent to
```rust
struct Foo<#[fundamental] T, #[fundamental] U>(T, U);
```
though given that there's no usecase for this right now, it seemed somewhat unnecessary.
r? compiler
* fundamental only on first arg
* woo this made error messages nicer
* oh the test was misnamed lol
* special case only box
* rename tests
Co-authored-by: Nia Deckers <nia-e@haecceity.cc>
Many "predicate"-to-"clause" renamings
Lots of names weren't changed to account for the introduction of the `Clause` type as a specialized form of `Predicate`, presumably because it was tedious. This commit converts as many of them as I could find. It's mostly very tedious renamings of types, functions, variables, and queries. The more interesting ones are a couple of files (`predicates_of.rs`, `impossible_predicates.rs`) and a MIR pass (`ImpossiblePredicates`).
r? @oli-obk
Lots of names weren't changed to account for the introduction of the
`Clause` type as a specialized form of `Predicate`, presumably because
it was tedious. This commit converts as many of them as I could find.
It's mostly very tedious renamings of types, functions, variables, and
queries. The more interesting ones are a couple of files
(`predicates_of.rs`, `impossible_predicates.rs`) and a MIR pass
(`ImpossiblePredicates`).
`PendingObligations` is a `ThinVec` containing a pair
`(PredicateObligation<'tcx>, Option<GoalStalledOn<TyCtxt<'tcx>>>)`. This
pair is currently 136 bytes. This is more than 128 bytes, which means
that LLVM uses (slow) `memcpy` to move the elements.
This commit shrinks `GoalStalledOn` by changing its two `Vec` fields to
`ThinVec`. This shrinks the pair from 136 bytes to 104 bytes, under the
`memcpy` threshold.
The use of `ThinVec` in `GoalStalledOn` forces us to use `ThinVec` in a
number of other places. Some of these required the thin-vec `unstable`
feature for `may_dangle` support.
The commit also adds some size assertions, to prevent backsliding.
Normalize region obligations before regionck
We now normalize `TypeOutlives` predicates when evaluating them in the next solver.
So we don't need to normalize in regionck anymore.
r? @ShoyuVanilla
cc @lcnr
Canonical responses can return query-created placeholders through opaque type constraints. Record empty assumptions when recreating those universes in the caller so eager placeholder handling does not ICE.
when bailing on ambiguity, don't force other results to ambig
A smaller version of rust-lang/rust#149904 which doesn't cause the perf issue in bevy, or at least in the minimization
While not necessarily necessary for https://github.com/rust-lang/trait-system-refactor-initiative/issues/257 due to rust-lang/rust#158643. This does fix the underlying issues there.
This change does affect `binius_field`, the remaining issues are tracked in https://github.com/rust-lang/trait-system-refactor-initiative/issues/274.
The core idea is that for
- A
- B
- A (cycle with initial result)
- B <---
We normally run A until we reach a fixpoint. We don't do so in case trying to do so encounters overflow or the result of `A` ends up ambiguous to avoid performance issues.
We want to generally keep the provisional cache entries which depend on A around. Evaluating these goals depends on the current provisional result of A. This means it is fine to keep them around if A reached a fixpoint. If we bail without reaching a fixpoint, the provisional result used while computing B differs from the final result of A. This means the entry for B is not valid and we'd need to discard it.
Discarding all nested provisional cache entries when not reaching a fixpoint causes perf issues. In case the final result of A is ambiguous, then this PR keeps nested cache entries which are ambiguous and don't have any inference constraints around. That is sound, as having more goals be ambiguous is never an issue, the trait solver can always say "🤷 idk". It also shouldn't cause any incorrect ambiguity errors issues, as changing the provisional result of A to be ambiguity should not change B to go from being ambiguous to something else.
The current implementation mutated the result of all nested provisional cache entries to be ambiguous, which resulted in incorrect ambiguity errors in https://github.com/rust-lang/trait-system-refactor-initiative/issues/257. This PR differs from that by dropping goals whose result isn't already ambiguous. That's means we don't keep quite as many cache entries around, which is potentially worse for perf, but from what I can tell this doens't cause issues in practice.
r? BoxyUwU
stepping into where-clauses during normalization may be productive
fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/273, see that issue for more info.
Whether stepping into a where-clause is productive depends not on whether we're proving a `NormalizesTo` or `Trait` goal, but instead on how both the impl and the cycle rely on it.
In the example in tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive-2.rs this is just a productive use given the way @Nadrieril and I are thinking about it right now.
We're changing such cycles to be ambiguous for now, so this does not commit us to anything.
This previously caused a lot of breakage when normalizing where-clauses, e.g. https://github.com/rust-lang/trait-system-refactor-initiative/issues/176, however with rust-lang/rust#158643 that is no longer an issue. We will need to figure out what to do here if we want to properly fix `ParamEnv` normalization in the future
r? @BoxyUwU or @nikomatsakis
trait solver: account for universes from replace_bound_vars
Fixesrust-lang/rust#157840.
The ICE was not really because eager placeholder handling looked at too many universes. Boxy was right: with `-Zassumptions-on-binders`, if the new solver creates a placeholder universe, that universe needs an assumptions entry.
The bad path is `FindParamInClause` entering a binder through `replace_bound_vars`. `BoundVarReplacer` materializes a placeholder universe for the escaping bound vars, but nothing records placeholder assumptions for it. Later eager placeholder handling walks all non-input universes, which imo is the right behavior, and `get_placeholder_assumptions` hits the missing entry.
This moves the empty-assumptions bookkeeping into `EvalCtxt::replace_bound_vars` instead of keeping it local to `FindParamInClause`. The helper snapshots the universe slots before replacement and inserts `Assumptions::empty()` for any slot that got filled.
There is still a FIXME there because idk that empty assumptions is the final shape irl. `replace_bound_vars` does not have the param-env context to compute proper assumptions. But for this PR, imo this is the least weird local fix: it keeps the eager pass looking at all non-input universes and fixes the missing bookkeeping where the universe is created.
The repro is covered by a UI test. It reports the overflow diagnostic instead of ICEing.