Update to LLVM 19
The LLVM 19.1.0 final release is planned for Sep 3rd. The rustc 1.82 stable release will be on Oct 17th.
The unstable MC/DC coverage support is temporarily broken by this update. It will be restored by https://github.com/rust-lang/rust/pull/126733. The implementation changed substantially in LLVM 19, and there are no plans to support both the LLVM 18 and LLVM 19 implementation at the same time.
Compatibility note for wasm:
> WebAssembly target support for the `multivalue` target feature has changed when upgrading to LLVM 19. Support for generating functions with multiple returns no longer works and `-Ctarget-feature=+multivalue` has a different meaning than it did in LLVM 18 and prior. The WebAssembly target features `multivalue` and `reference-types` are now both enabled by default, but generated code is not affected by default. These features being enabled are encoded in the `target_features` custom section and may affect downstream tooling such as `wasm-opt` consuming the module, but the actual generated WebAssembly will continue to not use either `multivalue` or `reference-types` by default. There is no longer any supported means to generate a module that has a function with multiple returns.
Related changes:
* https://github.com/rust-lang/rust/pull/127605
* https://github.com/rust-lang/rust/pull/127613
* https://github.com/rust-lang/rust/pull/127654
* https://github.com/rust-lang/rust/pull/128141
* https://github.com/llvm/llvm-project/pull/98933
Fixes https://github.com/rust-lang/rust/issues/121444.
Fixes https://github.com/rust-lang/rust/issues/128212.
Mark `Parser::eat`/`check` methods as `#[must_use]`
These methods return a `bool`, but we probably should either use these values or explicitly throw them away (e.g. when we just want to unconditionally eat a token if it exists).
I changed a few places from `eat` to `expect`, but otherwise I tried to leave a comment explaining why the `eat` was okay.
This also adds a test for the `pattern_type!` macro, which used to silently accept a missing `is` token.
Detect non-lifetime binder params shadowing item params
We should check that `for<T>` shadows `T` from an item in the same way that `for<'a>` shadows `'a` from an item.
r? ``@petrochenkov`` since you're familiar w the nuances of rib kinds
Don't record trait aliases as marker traits
Don't record `#[marker]` on trait aliases, since we use that to check for the (non-presence of) associated types and other things which don't make sense of trait aliases. We already enforce this attr is only applied to a trait.
Also do the same for `#[const_trait]`, which we also enforce is only applied to a trait. This is a drive-by change, but also worthwhile just in case.
Fixes#127222
Remove crashes for misuses of intrinsics
All of these do not crash if the feature gate is removed. An ICE due *opting into* the intrinsics feature gate is not a bug that needs to be fixed, but instead a misuse of an internal-only API.
See https://github.com/rust-lang/compiler-team/issues/620
The last two issues are already closed anyways, but:
Fixes#97501Fixes#111699Fixes#101962
Don't ICE if HIR and middle types disagree in borrowck error reporting
We try to match up the `middle::ty::Ty` and `hir::Ty` types in borrowck error reporting, but due to things like `Self` self type alias, or regular type aliases, these might not match up. Don't ICE.
This PR also tries to recover the error by looking up the self type of the impl in case we see `Self`. The diagnostic is frankly quite confusing, but I also didn't really want to look at it because I don't understand the conflict error reporting logic. 🤷Fixes#121816
Make sure that args are compatible in `resolve_associated_item`
Implements a similar check to the one that we have in projection for GATs (#102488, #123240), where we check that the args of an impl item are compatible before returning it. This is done in `resolve_assoc_item`, which is backing `Instance::resolve`, so this is conceptually generalizing the check from GATs to methods/assoc consts. This is important to make sure that the inliner will only visit and substitute MIR bodies that are compatible w/ their trait definitions.
This shouldn't happen in codegen, but there are a few ways to get the inliner to be invoked (via calls to `optimized_mir`) before codegen, namely polymorphization and CTFE.
Fixes#121957Fixes#120792Fixes#120793Fixes#121063
Just totally fully deny late-bound consts
Kinda don't care about supporting this until we have where clauses on binders. They're super busted and should be reworked in due time, and they are approximately 100% useless until then 😸Fixes#127970Fixes#127009
r? ``@BoxyUwU``
Forbid borrows and unsized types from being used as the type of a const generic under `adt_const_params`
Fixes#112219Fixes#112124Fixes#112125
### Motivation
Currently the `adt_const_params` feature allows writing `Foo<const N: [u8]>` this is entirely useless as it is not possible to write an expression which evaluates to a type that is not `Sized`. In order to actually use unsized types in const generics they are typically written as `const N: &[u8]` which *is* possible to provide a value of.
Unfortunately allowing the types of const parameters to contain references is non trivial (#120961) as it introduces a number of difficult questions about how equality of references in the type system should behave. References in the types of const generics is largely only useful for using unsized types in const generics.
This PR introduces a new feature gate `unsized_const_parameters` and moves support for `const N: [u8]` and `const N: &...` from `adt_const_params` into it. The goal here hopefully is to experiment with allowing `const N: [u8]` to work without references and then eventually completely forbid references in const generics.
Splitting this out into a new feature gate means that stabilization of `adt_const_params` does not have to resolve#120961 which is the only remaining "big" blocker for the feature. Remaining issues after this are a few ICEs and naming bikeshed for `ConstParamTy`.
### Implementation
The implementation is slightly subtle here as we would like to ensure that a stabilization of `adt_const_params` is forwards compatible with any outcome of `unsized_const_parameters`. This is inherently tricky as we do not support unstable trait implementations and we determine whether a type is valid as the type of a const parameter via a trait bound.
There are a few constraints here:
- We would like to *allow for the possibility* of adding a `Sized` supertrait to `ConstParamTy` in the event that we wind up opting to not support unsized types and instead requiring people to write the 'sized version', e.g. `const N: [u8; M]` instead of `const N: [u8]`.
- Crates should be able to enable `unsized_const_parameters` and write trait implementations of `ConstParamTy` for `!Sized` types without downstream crates that only enable `adt_const_params` being able to observe this (required for std to be able to `impl<T> ConstParamTy for [T]`
Ultimately the way this is accomplished is via having two traits (sad), `ConstParamTy` and `UnsizedConstParamTy`. Depending on whether `unsized_const_parameters` is enabled or not we change which trait is used to check whether a type is allowed to be a const parameter.
Long term (when stabilizing `UnsizedConstParamTy`) it should be possible to completely merge these traits (and derive macros), only having a single `trait ConstParamTy` and `macro ConstParamTy`.
Under `adt_const_params` it is now illegal to directly refer to `ConstParamTy` it is only used as an internal impl detail by `derive(ConstParamTy)` and checking const parameters are well formed. This is necessary in order to ensure forwards compatibility with all possible future directions for `feature(unsized_const_parameters)`.
Generally the intuition here should be that `ConstParamTy` is the stable trait that everything uses, and `UnsizedConstParamTy` is that plus unstable implementations (well, I suppose `ConstParamTy` isn't stable yet :P).
Represent type-level consts with new-and-improved `hir::ConstArg`
### Summary
This is a step toward `min_generic_const_exprs`. We now represent all const
generic arguments using an enum that differentiates between const *paths*
(temporarily just bare const params) and arbitrary anon consts that may perform
computations. This will enable us to cleanly implement the `min_generic_const_args`
plan of allowing the use of generics in paths used as const args, while
disallowing their use in arbitrary anon consts. Here is a summary of the salient
aspects of this change:
- Add `current_def_id_parent` to `LoweringContext`
This is needed to track anon const parents properly once we implement
`ConstArgKind::Path` (which requires moving anon const def-creation
outside of `DefCollector`).
- Create `hir::ConstArgKind` enum with `Path` and `Anon` variants. Use it in the
existing `hir::ConstArg` struct, replacing the previous `hir::AnonConst` field.
- Use `ConstArg` for all instances of const args. Specifically, use it instead
of `AnonConst` for assoc item constraints, array lengths, and const param
defaults.
- Some `ast::AnonConst`s now have their `DefId`s created in
rustc_ast_lowering rather than `DefCollector`. This is because in some
cases they will end up becoming a `ConstArgKind::Path` instead, which
has no `DefId`. We have to solve this in a hacky way where we guess
whether the `AnonConst` could end up as a path const since we can't
know for sure until after name resolution (`N` could refer to a free
const or a nullary struct). If it has no chance as being a const
param, then we create a `DefId` in `DefCollector` -- otherwise we
decide during ast_lowering. This will have to be updated once all path
consts use `ConstArgKind::Path`.
- We explicitly use `ConstArgHasType` for array lengths, rather than
implicitly relying on anon const type feeding -- this is due to the
addition of `ConstArgKind::Path`.
- Some tests have their outputs changed, but the changes are for the
most part minor (including removing duplicate or almost-duplicate
errors). One test now ICEs, but it is for an incomplete, unstable
feature and is now tracked at https://github.com/rust-lang/rust/issues/127009.
### Followup items post-merge
- Use `ConstArgKind::Path` for all const paths, not just const params.
- Fix (no github dont close this issue) #127009
- If a path in generic args doesn't resolve as a type, try to resolve as a const
instead (do this in rustc_resolve). Then remove the special-casing from
`rustc_ast_lowering`, so that all params will automatically be lowered as
`ConstArgKind::Path`.
- (?) Consider making `const_evaluatable_unchecked` a hard error, or at least
trying it in crater
r? `@BoxyUwU`
Fix ambiguous cases of multiple & in elided self lifetimes
This change proposes simpler rules to identify the lifetime on `self` parameters which may be used to elide a return type lifetime.
## The old rules
(copied from [this comment](https://github.com/rust-lang/rust/pull/117967#discussion_r1420554242))
Most of the code can be found in [late.rs](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html) and acts on AST types. The function [resolve_fn_params](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html#2006), in the success case, returns a single lifetime which can be used to elide the lifetime of return types.
Here's how:
* If the first parameter is called self then we search that parameter using "`self` search rules", below
* If no unique applicable lifetime was found, search all other parameters using "regular parameter search rules", below
(In practice the code does extra work to assemble good diagnostic information, so it's not quite laid out like the above.)
### `self` search rules
This is primarily handled in [find_lifetime_for_self](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html#2118) , and is described slightly [here](https://github.com/rust-lang/rust/issues/117715#issuecomment-1813115477) already. The code:
1. Recursively walks the type of the `self` parameter (there's some complexity about resolving various special cases, but it's essentially just walking the type as far as I can see)
2. Each time we find a reference anywhere in the type, if the **direct** referent is `Self` (either spelled `Self` or by some alias resolution which I don't fully understand), then we'll add that to a set of candidate lifetimes
3. If there's exactly one such unique lifetime candidate found, we return this lifetime.
### Regular parameter search rules
1. Find all the lifetimes in each parameter, including implicit, explicit etc.
2. If there's exactly one parameter containing lifetimes, and if that parameter contains exactly one (unique) lifetime, *and if we didn't find a `self` lifetime parameter already*, we'll return this lifetime.
## The new rules
There are no changes to the "regular parameter search rules" or to the overall flow, only to the `self` search rules which are now:
1. Recursively walks the type of the `self` parameter, searching for lifetimes of reference types whose referent **contains** `Self`.[^1]
2. Keep a record of:
* Whether 0, 1 or n unique lifetimes are found on references encountered during the walk
4. If no lifetime was found, we don't return a lifetime. (This means other parameters' lifetimes may be used for return type lifetime elision).
5. If there's one lifetime found, we return the lifetime.
6. If multiple lifetimes were found, we abort elision entirely (other parameters' lifetimes won't be used).
[^1]: this prevents us from considering lifetimes from inside of the self-type
## Examples that were accepted before and will now be rejected
```rust
fn a(self: &Box<&Self>) -> &u32
fn b(self: &Pin<&mut Self>) -> &String
fn c(self: &mut &Self) -> Option<&Self>
fn d(self: &mut &Box<Self>, arg: &usize) -> &usize // previously used the lt from arg
```
### Examples that change the elided lifetime
```rust
fn e(self: &mut Box<Self>, arg: &usize) -> &usize
// ^ new ^ previous
```
## Examples that were rejected before and will now be accepted
```rust
fn f(self: &Box<Self>) -> &u32
```
---
*edit: old PR description:*
```rust
struct Concrete(u32);
impl Concrete {
fn m(self: &Box<Self>) -> &u32 {
&self.0
}
}
```
resulted in a confusing error.
```rust
impl Concrete {
fn n(self: &Box<&Self>) -> &u32 {
&self.0
}
}
```
resulted in no error or warning, despite apparent ambiguity over the elided lifetime.
Fixes https://github.com/rust-lang/rust/issues/117715
This is a very large commit since a lot needs to be changed in order to
make the tests pass. The salient changes are:
- `ConstArgKind` gets a new `Path` variant, and all const params are now
represented using it. Non-param paths still use `ConstArgKind::Anon`
to prevent this change from getting too large, but they will soon use
the `Path` variant too.
- `ConstArg` gets a distinct `hir_id` field and its own variant in
`hir::Node`. This affected many parts of the compiler that expected
the parent of an `AnonConst` to be the containing context (e.g., an
array repeat expression). They have been changed to check the
"grandparent" where necessary.
- Some `ast::AnonConst`s now have their `DefId`s created in
rustc_ast_lowering rather than `DefCollector`. This is because in some
cases they will end up becoming a `ConstArgKind::Path` instead, which
has no `DefId`. We have to solve this in a hacky way where we guess
whether the `AnonConst` could end up as a path const since we can't
know for sure until after name resolution (`N` could refer to a free
const or a nullary struct). If it has no chance as being a const
param, then we create a `DefId` in `DefCollector` -- otherwise we
decide during ast_lowering. This will have to be updated once all path
consts use `ConstArgKind::Path`.
- We explicitly use `ConstArgHasType` for array lengths, rather than
implicitly relying on anon const type feeding -- this is due to the
addition of `ConstArgKind::Path`.
- Some tests have their outputs changed, but the changes are for the
most part minor (including removing duplicate or almost-duplicate
errors). One test now ICEs, but it is for an incomplete, unstable
feature and is now tracked at #127009.
Emit a wrap expr span_bug only if context is not tainted
Fixes#127332
The ICE occurs because of this `span_bug`: 51917e2e69/compiler/rustc_hir_typeck/src/expr_use_visitor.rs (L732-L738)
which is triggered by the fact that we're trying to use an `enum` in a `with` expression instead of a `struct`.
The issue originates in commit 814bfe9335 from PR #127202. As per the title of that commit the ICEing code should not be reachable any more, but looks like it still is.
This PR changes the code so that the `span_bug` will be emitted only if the context is not tainted by a previous error.
Avoid cloning jump threading state when possible
The current implementation of jump threading passes most of its time cloning its state. This PR attempts to avoid such clones by special-casing the last predecessor when recursing through a terminator.
This is not optimal, but a first step while I refactor the state data structure to be sparse.
The two other commits are drive-by.
Fixes https://github.com/rust-lang/rust/issues/116721
r? `@oli-obk`
Account for things that optimize out in inlining costs
This updates the MIR inlining `CostChecker` to have both bonuses and penalties, rather than just penalties.
That lets us add bonuses for some things where we want to encourage inlining without risking wrapping into a gigantic cost. For example, `switchInt(const …)` we give an inlining bonus because codegen will actually eliminate the branch (and associated dead blocks) once it's monomorphized, so measuring both sides of the branch gives an unrealistically-high cost to it. Similarly, an `unreachable` terminator gets a small bonus, because whatever branch leads there doesn't actually exist post-codegen.
Fix assertion failure for some `Expect` diagnostics.
In #120699 I moved some code dealing with `has_future_breakage` earlier in `emit_diagnostic`. Issue #126521 identified a case where that reordering was invalid (leading to an assertion failure) for some `Expect` diagnostics.
This commit partially undoes the change, by moving the handling of unstable `Expect` diagnostics earlier again. This makes `emit_diagnostic` a bit uglier, but is necessary to fix the problem.
Fixes#126521.
r? ``@oli-obk``
In #120699 I moved some code dealing with `has_future_breakage` earlier
in `emit_diagnostic`. Issue #126521 identified a case where that
reordering was invalid (leading to an assertion failure) for some `Expect`
diagnostics.
This commit partially undoes the change, by moving the handling of
unstable `Expect` diagnostics earlier again. This makes
`emit_diagnostic` a bit uglier, but is necessary to fix the problem.
Fixes#126521.
Rollup of 3 pull requests
Successful merges:
- #126568 (mark undetermined if target binding in current ns is not got)
- #126577 (const_refs_to_static test and cleanup)
- #126584 (Do not ICE in privacy when type inference fails.)
r? `@ghost`
`@rustbot` modify labels: rollup
Consistently use subtyping in method resolution
fixes#126062
An earlier version of this PR modified how we compute variance, but the root cause was an inconsistency between the usage of `eq` and `sub`, where we assumed that the latter passing implies the former will pass.
r? `@compiler-errors`
PR #121208 converted this from a `span_delayed_bug` to a `span_bug`
because nothing in the test suite caused execution to hit this path. But
now fuzzing has found a test case that does hit it. So this commit
converts it back to `span_delayed_bug` and adds the relevant test.
Fixes#126385.
Add `f16` and `f128` const eval for binary and unary operationations
Add const evaluation and Miri support for f16 and f128, including unary and binary operations. Casts are not yet included.
Fixes https://github.com/rust-lang/rust/issues/124583
r? ``@RalfJung``
Previously, the implementation of `Tree::from_enum` incorrectly
treated enums with `Variants::Single` and `Variants::Multiple`
identically. This is incorrect for `Variants::Single` enums,
which delegate their layout to that of a variant with a particular
index (or no variant at all if the enum is empty).
This flaw manifested first as an ICE. `Tree::from_enum` attempted
to compute the tag of variants other than the one at
`Variants::Single`'s `index`, and fell afoul of a sanity-checking
assertion in `compiler/rustc_const_eval/src/interpret/discriminant.rs`.
This assertion is non-load-bearing, and can be removed; the routine
its in is well-behaved even without it.
With the assertion removed, the proximate issue becomes apparent:
calling `Tree::from_variant` on a variant that does not exist is
ill-defined. A sanity check the given variant has
`FieldShapes::Arbitrary` fails, and the analysis is (correctly)
aborted with `Err::NotYetSupported`.
This commit corrects this chain of failures by ensuring that
`Tree::from_variant` is not called on variants that are, as far as
layout is concerned, nonexistent. Specifically, the implementation
of `Tree::from_enum` is now partitioned into three cases:
1. enums that are uninhabited
2. enums for which all but one variant is uninhabited
3. enums with multiple inhabited variants
`Tree::from_variant` is now only invoked in the third case. In the
first case, `Tree::uninhabited()` is produced. In the second case,
the layout is delegated to `Variants::Single`'s index.
Fixes#125811
Remove the `ty` field from type system `Const`s
Fixes#125556Fixes#122908
Part of the work on `adt_const_params`/`generic_const_param_types`/`min_generic_const_exprs`/generally making the compiler nicer. cc rust-lang/project-const-generics#44
Please review commit-by-commit otherwise I wasted a lot of time not just squashing this into a giant mess (and also it'll be SO much nicer because theres a lot of fluff changes mixed in with other more careful changes if looking via File Changes
---
Why do this?
- The `ty` field keeps causing ICEs and weird behaviour due to it either being treated as "part of the const" or it being forgotten about leading to ICEs.
- As we move forward with `adt_const_params` and a potential `min_generic_const_exprs` it's going to become more complex to actually lower the correct `Ty<'tcx>`
- It muddles the idea behind how we check `Const` arguments have the correct type. By having the `ty` field it may seem like we ought to be relating it when we relate two types, or that its generally important information about the `Const`.
- Brings the compiler more in line with `a-mir-formality` as that also tracks the type of type system `Const`s via `ConstArgHasType` bounds in the env instead of on the `Const` itself.
- A lot of stuff is a lot nicer when you dont have to pass around the type of a const lol. Everywhere we construct `Const` is now significantly nicer 😅
See #125671's description for some more information about the `ty` field
---
General summary of changes in this PR:
- Add `Ty` to `ConstKind::Value` as otherwise there is no way to implement `ConstArgHasType` to ensure that const arguments are correctly typed for the parameter when we stop creating anon consts for all const args. It's also just incredibly difficult/annoying to thread the correct `Ty` around to a bunch of ctfe functions otherwise.
- Fully implement `ConstArgHasType` in both the old and new solver. Since it now has no reliance on the `ty` field it serves its originally intended purpose of being able to act as a double check that trait vs impls have correctly typed const parameters. It also will now be able to be responsible for checking types of const arguments to parameters under `min_generic_const_exprs`.
- Add `Ty` to `mir::Const::Ty`. I dont have a great understanding of why mir constants are setup like this to be honest. Regardless they need to be able to determine the type of the const and the easiest way to make this happen was to simply store the `Ty` along side the `ty::Const`. Maybe we can do better here in the future but I'd have to spend way more time looking at everywhere we use `mir::Const`.
- rustdoc has its own `Const` which also has a `ty` field. It was relatively easy to remove this.
---
r? `@lcnr` `@compiler-errors`
resolve: mark it undetermined if single import is not has any bindings
- Fixes#124490
- Fixes#125013
This issue arises from incorrect resolution updates, for example:
```rust
mod a {
pub mod b {
pub mod c {}
}
}
use a::*;
use b::c;
use c as b;
fn main() {}
```
1. In the first loop, binding `(root, b)` is refer to `root:🅰️:b` due to `use a::*`.
1. However, binding `(root, c)` isn't defined by `use b::c` during this stage because `use c as b` falls under the `single_imports` of `(root, b)`, where the `imported_module` hasn't been computed yet. This results in marking the `path_res` for `b` as `Indeterminate`.
2. Then, the `imported_module` for `use c as b` will be recorded.
2. In the second loop, `use b::c` will be processed again:
1. Firstly, it attempts to find the `path_res` for `(root, b)`.
2. It will iterate through the `single_imports` of `use b::c`, encounter `use c as b`, attempt to resolve `c` in `root`, and ultimately return `Err(Undetermined)`, thus passing the iterator.
3. Use the binding `(root, b)` -> `root:🅰️:b` introduced by `use a::*` and ultimately return `root:🅰️:b` as the `path_res` of `b`.
4. Then define the binding `(root, c)` -> `root:🅰️🅱️:c`.
3. Then process `use c as b`, update the resolution for `(root, b)` to refer to `root:🅰️🅱️:c`, ultimately causing inconsistency.
In my view, step `2.2` has an issue where it should exit early, similar to the behavior when there's no `imported_module`. Therefore, I've added an attribute called `indeterminate` to `ImportData`. This will help us handle only those single imports that have at least one determined binding.
r? ``@petrochenkov``
This test reproduces a rustc ICE. Unfortunately, the changes to lifetime
elision mask the original ICE bug by making this function signature
illegal. However, by simplifying the signature we can regain the
original ICE.
Fail relating constants of different types
fixes#121585fixes#121858fixes#124151
I gave this several attempts before, but we lost too many important diagnostics until I managed to make compilation never bail out early. We have reached this point, so now we can finally fix all those ICEs by bubbling up an error instead of continueing when we encounter a bug.
Resolve anon const's parent predicates to direct parent instead of opaque's parent
When an anon const is inside of an opaque, #99801 added a hack to resolve the anon const's parent predicates *not* to the opaque's predicates, but to the opaque's *parent's* predicates. This is insufficient when considering nested opaques.
This means that the `predicates_of` an anon const might reference duplicated lifetimes (installed by `compute_bidirectional_outlives_predicates`) when computing known outlives in MIR borrowck, leading to these ICEs:
Fixes#121574Fixes#118403
~~Instead, we should be using the `OpaqueTypeOrigin` to acquire the owner item (fn/type alias/etc) of the opaque, whose predicates we're fine to mention.~~
~~I think it's a bit sketchy that we're doing this at all, tbh; I think it *should* be fine for the anon const to inherit the predicates of the opaque it's located inside. However, that would also mean that we need to make sure the `generics_of` that anon const line up in the same way.~~
~~None of this is important to solve right now; I just want to fix these ICEs so we can land #125468, which accidentally fixes these issues in a different and unrelated way.~~
edit: We don't need this special case anyways because we install the right parent item in `generics_of` anyways:
213ad10c8f/compiler/rustc_hir_analysis/src/collect/generics_of.rs (L150)
r? `@BoxyUwU`