Remove `token::Lit` from `ast::MetaItemLit`.
Currently `ast::MetaItemLit` represents the literal kind twice. This PR removes that redundancy. Best reviewed one commit at a time.
r? `@petrochenkov`
Fix lint perf regressions
#104863 caused small but widespread regressions in lint performance. I tried to improve things in #105291 and #105416 with minimal success, before fully understanding what caused the regression. This PR effectively reverts all of #105291 and part of #104863 to fix the perf regression.
r? `@cjgillot`
Make encode_info_for_trait_item use queries instead of accessing the HIR
This change avoids accessing the HIR on `encode_info_for_trait_item` and uses queries. We will need to execute this function for elements that have no HIR and by using queries we will be able to feed for definitions that have no HIR.
r? ``@oli-obk``
This commit partly undoes #104863, which combined the builtin lints pass
with other lints. This caused a slowdown, because often there are no
other lints, and it's faster to do a pass with a single lint directly
than it is to do a combined pass with a `passes` vector containing a
single lint.
I removed these in #105291, and subsequently learned they are necessary
for performance.
This commit reinstates them with the new and more descriptive names
`RuntimeCombined{Early,Late}LintPass`, similar to the existing passes
like `BuiltinCombinedEarlyLintPass`. It also adds some comments,
particularly emphasising how we have ways to combine passes at both
compile-time and runtime. And it moves some comments around.
When encountering an unmet obligation that affects a method chain, like
in iterator chains where one of the links has the wrong associated
type, we point at every method call and mention their evaluated
associated type at that point to give context to the user of where
expectations diverged from the code as written.
```
note: the expression is of type `Map<std::slice::Iter<'_, {integer}>, [closure@$DIR/invalid-iterator-chain.rs:12:18: 12:21]>`
--> $DIR/invalid-iterator-chain.rs:12:14
|
LL | vec![0, 1]
| ---------- this expression has type `Vec<{integer}>`
LL | .iter()
| ------ associated type `std::iter::Iterator::Item` is `&{integer}` here
LL | .map(|x| { x; })
| ^^^^^^^^^^^^^^^ associated type `std::iter::Iterator::Item` is `()` here
```
Don't internalize __llvm_profile_counter_bias
Currently, LLVM profiling runtime counter relocation cannot be used by rust during LTO because symbols are being internalized before all symbol information is known.
This mode makes LLVM emit a __llvm_profile_counter_bias symbol which is referenced by the profiling initialization, which itself is pulled in by the rust driver here [1].
It is enabled with -Cllvm-args=-runtime-counter-relocation for platforms which are opt-in to this mode like Linux. On these platforms there will be no link error, rather just surprising behavior for a user which request runtime counter relocation. The profiling runtime will not see that symbol go on as if it were never there. On Fuchsia, the profiling runtime must have this symbol which will cause a hard link error.
As an aside, I don't have enough context as to why rust's LTO model is how it is. AFAICT, the internalize pass is only safe to run at link time when all symbol information is actually known, this being an example as to why. I think special casing this symbol as a known one that LLVM can emit which should not have it's visbility de-escalated should be fine given how seldom this pattern of defining an undefined symbol to get initilization code pulled in is. From a quick grep, __llvm_profile_runtime is the only symbol that rustc does this for.
[1] 0265a3e93b/compiler/rustc_codegen_ssa/src/back/linker.rs (L598)
compiler: remove unnecessary imports and qualified paths
Some of these imports were necessary before Edition 2021, others were already in the prelude.
I hope it's fine that this PR is so spread-out across files :/
Some method confirmation code nits
1. Make some pick methods take `&self` instead of `&mut` to avoid some cloning
2. Pass some values by reference to avoid some cloning
3. Rename a few variables here and there
Fix invalid codegen during debuginfo lowering
In order for LLVM to correctly generate debuginfo for msvc, we sometimes need to spill arguments to the stack and perform some direct & indirect offsets into the value. Previously, this code always performed those actions, even when not required as LLVM would clean it up during optimization.
However, when MIR inlining is enabled, this can cause problems as the operations occur prior to the spilled value being initialized. To solve this, we first calculate the necessary offsets using just the type which is side-effect free and does not alter the LLVM IR. Then, if we are in a situation which requires us to generate the LLVM IR (and this situation only occurs for arguments, not local variables) then we perform the same calculation again, this time generating the appropriate LLVM IR as we go.
r? `@tmiasko` but feel free to reassign if you want 🙂Fixes#105386
Migrate parts of `rustc_expand` to session diagnostics
This migrates everything but the `mbe` and `proc_macro` modules. It also contains a few cleanups and drive-by/accidental diagnostic improvements which can be seen in the diff for the UI tests.
Rollup of 10 pull requests
Successful merges:
- #98391 (Reimplement std's thread parker on top of events on SGX)
- #104019 (Compute generator sizes with `-Zprint_type_sizes`)
- #104512 (Set `download-ci-llvm = "if-available"` by default when `channel = dev`)
- #104901 (Implement masking in FileType comparison on Unix)
- #105082 (Fix Async Generator ABI)
- #105109 (Add LLVM KCFI support to the Rust compiler)
- #105505 (Don't warn about unused parens when they are used by yeet expr)
- #105514 (Introduce `Span::is_visible`)
- #105516 (Update cargo)
- #105522 (Remove wrong note for short circuiting operators)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
This migrates everything but the `mbe` and `proc_macro` modules. It also
contains a few cleanups and drive-by/accidental diagnostic improvements
which can be seen in the diff for the UI tests.
Add LLVM KCFI support to the Rust compiler
This PR adds LLVM Kernel Control Flow Integrity (KCFI) support to the Rust compiler. It initially provides forward-edge control flow protection for operating systems kernels for Rust-compiled code only by aggregating function pointers in groups identified by their return and parameter types. (See llvm/llvm-project@cff5bef.)
Forward-edge control flow protection for C or C++ and Rust -compiled code "mixed binaries" (i.e., for when C or C++ and Rust -compiled code share the same virtual address space) will be provided in later work as part of this project by identifying C char and integer type uses at the time types are encoded (see Type metadata in the design document in the tracking issue #89653).
LLVM KCFI can be enabled with -Zsanitizer=kcfi.
Thank you again, `@bjorn3,` `@eddyb,` `@nagisa,` and `@ojeda,` for all the help!
Fix Async Generator ABI
This change was missed when making async generators implement `Future` directly.
It did not cause any problems in codegen so far, as `GeneratorState<(), Output>`
happens to have the same ABI as `Poll<Output>`.
Rollup of 9 pull requests
Successful merges:
- #102406 (Make `missing_copy_implementations` more cautious)
- #105265 (Add `rustc_on_unimplemented` to `Sum` and `Product` trait.)
- #105385 (Skip test on s390x as LLD does not support the platform)
- #105453 (Make `VecDeque::from_iter` O(1) from `vec(_deque)::IntoIter`)
- #105468 (Mangle "main" as "__main_void" on wasm32-wasi)
- #105480 (rustdoc: remove no-op mobile CSS `#sidebar-toggle { text-align }`)
- #105489 (Fix typo in apple_base.rs)
- #105504 (rustdoc: make stability badge CSS more consistent)
- #105506 (Tweak `rustc_must_implement_one_of` diagnostic output)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Mangle "main" as "__main_void" on wasm32-wasi
On wasm, the age-old C trick of having a main function which can either have no arguments or argc+argv doesn't work, because wasm requires caller and callee signatures to match. WASI's current strategy is to have compilers mangle main's name to indicate which signature they're using. Rust uses the no-argument form, which should be mangled as `__main_void`.
This is needed on wasm32-wasi as of #105395.
Make `missing_copy_implementations` more cautious
- Fixes https://github.com/rust-lang/rust/issues/98348
- Also makes the lint not fire on large types and types containing raw pointers. Thoughts?
Shrink `rustc_parse_format::Piece`
This makes both variants closer together in size (previously they were different by 208 bytes -- 16 vs 224). This may make things worse, but it's worth a try.
r? `@nnethercote`
In a scenario like
```
struct Type;
pub trait Trait {
fn function(&mut self)
where
Self: Sized;
}
impl Trait for Type {
fn function(&mut self) {}
}
fn main() {
(&mut Type as &mut dyn Trait).function();
}
```
the problem is Sized, not the mutability of self. Thus don't emit the
"you need &T instead of &mut T" note, or the other way around, as all
it does is just invert the mutability of whatever was supplied.
Fixes#103622.
use the correct `Reveal` during validation
supersedes #105454. Deals with https://github.com/rust-lang/rust/issues/105009#issuecomment-1342395333, not closing #105009 as the ICE may leak into beta
The issue was the following:
- we optimize the mir, using `Reveal::All`
- some optimization relies on the hidden type of an opaque type
- we then validate using `Reveal::UserFacing` again which is not able to observe the hidden type
r? `@jackh726`
Move some queries and methods
Each commit's title should be self-explanatory. Motivated to break up some large, general files and move queries into leaf crates.
In order for LLVM to correctly generate debuginfo for msvc, we sometimes
need to spill arguments to the stack and perform some direct & indirect
offsets into the value. Previously, this code always performed those
actions, even when not required as LLVM would clean it up during
optimization.
However, when MIR inlining is enabled, this can cause problems as the
operations occur prior to the spilled value being initialized. To solve
this, we first calculate the necessary offsets using just the type which
is side-effect free and does not alter the LLVM IR. Then, if we are in a
situation which requires us to generate the LLVM IR (and this situation
only occurs for arguments, not local variables) then we perform the same
calculation again, this time generating the appropriate LLVM IR as we
go.
This commit adds LLVM Kernel Control Flow Integrity (KCFI) support to
the Rust compiler. It initially provides forward-edge control flow
protection for operating systems kernels for Rust-compiled code only by
aggregating function pointers in groups identified by their return and
parameter types. (See llvm/llvm-project@cff5bef.)
Forward-edge control flow protection for C or C++ and Rust -compiled
code "mixed binaries" (i.e., for when C or C++ and Rust -compiled code
share the same virtual address space) will be provided in later work as
part of this project by identifying C char and integer type uses at the
time types are encoded (see Type metadata in the design document in the
tracking issue #89653).
LLVM KCFI can be enabled with -Zsanitizer=kcfi.
Co-authored-by: bjorn3 <17426603+bjorn3@users.noreply.github.com>
This change was missed when making async generators implement `Future` directly.
It did not cause any problems in codegen so far, as `GeneratorState<(), Output>`
happens to have the same ABI as `Poll<Output>`.
On wasm, the age-old C trick of having a main function which can either have
no arguments or argc+argv doesn't work, because wasm requires caller and
callee signatures to match. WASI's current strategy is to have compilers
mangle main's name to indicate which signature they're using. Rust uses the
no-argument form, which should be mangled as `__main_void`.
This is needed on wasm32-wasi as of #105395.
Add help for `#![feature(impl_trait_in_fn_trait_return)]`
This adds a new variant `ImplTraitContext::FeatureGated`, so we can
generalize the help for `return_position_impl_trait_in_trait` to also
work for `impl_trait_in_fn_trait_return`.
cc #99697
Stop passing -export-dynamic to wasm-ld.
-export-dynamic was a temporary hack added in the early days of the Rust wasm32 target when Rust didn't have a way to specify wasm exports in the source code. This flag causes all global symbols, and some compiler-internal symbols, to be exported, which is often more than needed.
Rust now does have a way to specify exports in the source code: `#[export_name = "..."]`.
So as the original comment suggests, -export-dynamic can now be removed, allowing users to have smaller binaries and better encapsulation in their wasm32-unknown-unknown modules.
It's possible that this change will require existing wasm32-unknown-unknown users will to add explicit `#[export_name = "..."]` directives to exporrt the symbols that their programs depend on having exported.
make retagging work even with 'unstable' places
This is based on top of https://github.com/rust-lang/rust/pull/105301. Only the last two commits are new.
While investigating https://github.com/rust-lang/unsafe-code-guidelines/issues/381 I realized that we would have caught this issue much earlier if the add_retag pass wouldn't bail out on assignments of the form `*ptr = ...`.
So this PR changes our retag strategy:
- When a new reference is created via `Rvalue::Ref` (or a raw ptr via `Rvalue::AddressOf`), we do the retagging as part of just executing that address-taking operation.
- For everything else, we still insert retags -- these retags basically serve to ensure that references stored in local variables (and their fields) are always freshly tagged, so skipping this for assignments like `*ptr = ...` is less egregious.
r? ```@oli-obk```
Detect long types in E0308 and write them to disk
On type error with long types, print an abridged type and write the full type to disk.
Print the widest possible short type while still fitting in the terminal.
Currently, LLVM profiling runtime counter relocation cannot be
used by rust during LTO because symbols are being internalized
before all symbol information is known.
This mode makes LLVM emit a __llvm_profile_counter_bias symbol
which is referenced by the profiling initialization, which itself
is pulled in by the rust driver here [1].
It is enabled with -Cllvm-args=-runtime-counter-relocation for
platforms which are opt-in to this mode like Linux. On these
platforms there will be no link error, rather just surprising
behavior for a user which request runtime counter relocation.
The profiling runtime will not see that symbol go on as if it
were never there. On Fuchsia, the profiling runtime must have
this symbol which will cause a hard link error.
As an aside, I don't have enough context as to why rust's LTO
model is how it is. AFAICT, the internalize pass is only safe
to run at link time when all symbol information is actually
known, this being an example as to why. I think special casing
this symbol as a known one that LLVM can emit which should not
have it's visbility de-escalated should be fine given how
seldom this pattern of defining an undefined symbol to get
initilization code pulled in is. From a quick grep,
__llvm_profile_runtime is the only symbol that rustc does this
for.
[1] 0265a3e93b/compiler/rustc_codegen_ssa/src/back/linker.rs (L598)
normalize before handling simple checks for evaluatability of `ty::Const`
`{{{{{{{ N }}}}}}}` is desugared into a `ConstKind::Unevaluated` for an anonymous `const` item so when calling `is_const_evaluatable` on it we skip the `ConstKind::Param(_) => Ok(())` arm which is incorrect.
Simplify attribute handling in rustc_ast_lowering
Given that attributes is stored in a separate BTreeMap, it's not necessary to pass it in when constructing `hir::Expr`. We can just construct `hir::Expr` and then call `self.lower_attrs` later if it needs attributes.
As most desugaring code don't use attributes, this allows some code cleanup.
Remove `{Early,Late}LintPassObjects`.
`EarlyContextAndPass` wraps a single early lint pass. We aggregate multiple passes into that single pass by using `EarlyLintPassObjects`.
This commit removes `EarlyLintPassObjects` by changing `EarlyContextAndPass` into `EarlyContextAndPasses`. I.e. it just removes a level of indirection. This makes the code simpler and slightly faster.
The commit does likewise for late lints.
r? `@cjgillot`
This adds a new variant `ImplTraitContext::FeatureGated`, so we can
generalize the help for `return_position_impl_trait_in_trait` to also
work for `impl_trait_in_fn_trait_return`.
-export-dynamic was a temporary hack added in the early days of the Rust
wasm32 target when Rust didn't have a way to specify wasm exports in the
source code. This flag causes all global symbols, and some compiler-internal
symbols, to be exported, which is often more than needed.
Rust now does have a way to specify exports in the source code:
`#[export_name = "..."]`.
So as the original comment suggests, -export-dynamic can now be removed,
allowing users to have smaller binaries and better encapsulation in
their wasm32-unknown-unknown modules.
It's possible that this change will require existing wasm32-unknown-unknown
users will to add explicit `#[export_name = "..."]` directives to
exporrt the symbols that their programs depend on having exported.
Rollup of 9 pull requests
Successful merges:
- #104898 (Put all cached values into a central struct instead of just the stable hash)
- #105004 (Fix `emit_unused_delims_expr` ICE)
- #105174 (Suggest removing struct field from destructive binding only in shorthand scenario)
- #105250 (Replace usage of `ResumeTy` in async lowering with `Context`)
- #105286 (Add -Z maximal-hir-to-mir-coverage flag)
- #105320 (rustdoc: simplify CSS selectors on top-doc and non-exhaustive toggles)
- #105349 (Point at args in associated const fn pointers)
- #105362 (Cleanup macro-expanded code in `rustc_type_ir`)
- #105370 (Remove outdated syntax from trait alias pretty printing)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Remove outdated syntax from trait alias pretty printing
Given the following program:
```rust
#![feature(trait_alias)]
trait A = ?Sized;
fn main() {}
```
Old output of `rustc +nightly ./t.rs -Zunpretty=normal`:
```rust
#![feature(trait_alias)]
trait A for ? Sized ;
fn main() {}
```
New output of `rustc +a ./t.rs -Zunpretty=normal`:
```rust
#![feature(trait_alias)]
trait A = ?Sized;
fn main() {}
```
cc `@durka` (you've written the `FIXME` in #45047, see https://github.com/rust-lang/rust/pull/45047#discussion_r144960751)
Cleanup macro-expanded code in `rustc_type_ir`
We could of course just leave this as-is, but every time I go-to-def to this file it's painful to see all this `(&A(ref __self_1_0),)` stuff.
Point at args in associated const fn pointers
Tiny follow-up to #105201, not so sure it's worth it but 🤷
The UI test example is a bit more compelling when it's `GlUniformScalar::FACTORY`
r? `@cjgillot`
Add -Z maximal-hir-to-mir-coverage flag
This PR adds a new unstable flag `-Z maximal-hir-to-mir-coverage` that changes the behavior of `maybe_lint_level_root_bounded`, pursuant to [a discussion on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Mapping.20MIR.20to.20HIR). When enabled, this function will not search upwards for a lint root, but rather immediately return the provided HIR node ID. This change increases the granularity of the mapping between MIR locations and HIR nodes inside the `SourceScopeLocalData` data structures. This increase in granularity is useful for rustc consumers like [Flowistry](https://github.com/willcrichton/flowistry) that rely on getting source-mapping information about the MIR CFG that is as precise as possible.
A test `maximal_mir_to_hir_coverage.rs` has been added to verify that this flag does not break anything.
r? `@cjgillot`
cc `@gavinleroy`
Replace usage of `ResumeTy` in async lowering with `Context`
Replaces using `ResumeTy` / `get_context` in favor of using `&'static mut Context<'_>`.
Usage of the `'static` lifetime here is technically "cheating", and replaces the raw pointer in `ResumeTy` and the `get_context` fn that pulls the correct lifetimes out of thin air.
fixes https://github.com/rust-lang/rust/issues/104828 and https://github.com/rust-lang/rust/pull/104321#issuecomment-1336363077
r? `@oli-obk`
Put all cached values into a central struct instead of just the stable hash
cc `@nnethercote`
this allows re-use of the type for Predicate without duplicating all the logic for the non-hash cached fields
Re-enable removal of ZST writes to unions
This was previously disabled because Miri was lazily allocating unsized locals. But we aren't doing that anymore since https://github.com/rust-lang/rust/pull/98831, so we can have this optimization back.
Make `note_obligation_cause_code` take a `impl ToPredicate` for predicate
The only usecase that wasn't `impl ToPredicate` was noting overflow errors while revealing opaque types, which passed in an `Obligation<'tcx, Ty<'tcx>>`... Since this only happens in a `RevealAll` environment, which is after typeck (and probably primarily within `normalize_erasing_regions`) we're unlikely to display anything useful while noting this code, evidenced by the lack of UI test changes.
support `ConstKind::Expr` in `is_const_evaluatable` and `WfPredicates::compute`
Fixes#105205
Currently we haven't implemented a way to evaluate `ConstKind::Expr(Expr::Binop(Add, 1, 2))` so I just left that with a `FIXME` and a `delay_span_bug` since I have no idea how to do that and it would make this a much larger (and more complicated) PR :P
Synthesize substitutions for bad auto traits in dyn types
Auto traits are stored as just `DefId`s inside a `dyn Trait`'s existential predicates list. This is usually fine, since auto traits are forbidden to have generics -- but this becomes a problem for an ill-formed auto trait.
But since this will always result in an error, just synthesize some dummy (error) substitutions which are used at least to keep trait selection code happy about the number of substs in a trait ref.
Fixes#104808
propagate the error from parsing enum variant to the parser and emit out
While parsing enum variant, the error message always disappear
Because the error message that emit out is from main error of parser
The information of enum variant disappears while parsing enum variant with error
We only check the syntax of expecting token, i.e, in case https://github.com/rust-lang/rust/issues/103869
It will error it without telling the message that this error is from pasring enum variant.
Propagate the sub-error from parsing enum variant to the main error of parser by chaining it with map_err
Check the sub-error before emitting the main error of parser and attach it.
Fix https://github.com/rust-lang/rust/issues/103869