Previously some invalid let expressions would result in both a feature
error and a parsing error. Avoid this and ensure that we only emit the
parsing error when this happens.
There was an incomplete version of the check in parsing and a second
version in AST validation. This meant that some, but not all, invalid
uses were allowed inside macros/disabled cfgs. It also means that later
passes have a hard time knowing when the let expression is in a valid
location, sometimes causing ICEs.
- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a
valid location.
- Suppress later errors and MIR construction for invalid let
expressions.
Improve diagnostic for generic params from outer items (E0401)
Generalize the wording of E0401 to talk about *outer items* instead of *outer functions* since the current phrasing is outdated. The outer item can be a function, constant, trait, ADT or impl block (see the new UI test for the more exotic examples).
Further, don't suggest introducing generic parameters to constant items unless the feature `generic_const_items` is enabled.
Lastly, make E0401 translatable while we're at it.
Fixes#115720.
Call `LateLintPass::check_attribute` from `with_lint_attrs`
Fixes#115571
For regular `register_late_pass` lints also means that `last_node_with_lint_attrs` is correct when in `check_attribute`, I've added a test that previously failed for `clippy::allow_attributes`
As far as I can see the only late lint in rustc that uses `check_attribute` is `unstable_features` which is allow by default and deprecated so this is mostly for clippy (or future rustc lints)
Fix incorrect mutable suggestion information for binding in ref pattern like: `let &b = a;`
fixes#114896
I find we have to get pat_span but not local_decl.source_info.span for suggestion. In `let &b = a;` pat_span is &b. I think check `let &b = a` in hir to make sure it is hir::Node::Local(hir::Local {pat: hir::Pat{kind: hir::PatKind::Ref(....... can distinguish it from other situation, but I'm not sure.
If my processing method is not accurate, please guide me to modify it, thank you.
r? `@davidtwco`
also handle 2 panics when dumping proof trees for the whole test suite
- need to actually tell the proof tree builder about overflow
- need to handle a recursion_limit of 0 :<
Enable incremental-relative-spans by default.
This was enabled on nightly in https://github.com/rust-lang/rust/pull/84762.
It has been a while, without obvious bugs. It's time to enable it by default for incremental runs.
Disentangle `Debug` and `Display` for `Ty`.
The `Debug` impl for `Ty` just calls the `Display` impl for `Ty`. This is surprising and annoying. In particular, it means `Debug` doesn't show as much information as `Debug` for `TyKind` does. And `Debug` is used in some user-facing error messages, which seems bad.
This commit changes the `Debug` impl for `Ty` to call the `Debug` impl for `TyKind`. It also does a number of follow-up changes to preserve existing output, many of which involve inserting
`with_no_trimmed_paths!` calls. It also adds `Display` impls for `UserType` and `Canonical`.
Some tests have changes to expected output:
- Those that use the `rustc_abi(debug)` attribute.
- Those that use the `rustc_layout(debug)` attribute.
- Those that use the `EMIT_MIR` annotation.
In each case the output is slightly uglier than before. This isn't ideal, but it's pretty weird (particularly for the attributes) that the output is using `Debug` in the first place. They're fairly obscure attributes (I hadn't heard of them) so I'm not worried by this.
For `async-is-unwindsafe.stderr`, there is one line that now lacks a full path. This is a consistency improvement, because all the other mentions of `Context` in this test lack a path.
Instead of writing coverage mappings into a supplied `&RustString`, this
function can just create the buffer itself and return the resulting vector of
bytes.
If two or more mappings cover exactly the same region, their relative order
will now be preserved from `get_expressions_and_counter_regions`, rather than
being disturbed by implementation details of an unstable sort.
The current order is: counter mappings, expression mappings, zero mappings.
(LLVM will also perform its own stable sort on these mappings, but that sort
only compares file ID, start location, and `RegionKind`.)
This struct was only being used to hold the global file table, and one of its
methods didn't even use the table. Changing its methods to ordinary functions
makes it easier to see where the table is mutated.
The `Debug` impl for `Ty` just calls the `Display` impl for `Ty`. This
is surprising and annoying. In particular, it means `Debug` doesn't show
as much information as `Debug` for `TyKind` does. And `Debug` is used in
some user-facing error messages, which seems bad.
This commit changes the `Debug` impl for `Ty` to call the `Debug` impl
for `TyKind`. It also does a number of follow-up changes to preserve
existing output, many of which involve inserting
`with_no_trimmed_paths!` calls. It also adds `Display` impls for
`UserType` and `Canonical`.
Some tests have changes to expected output:
- Those that use the `rustc_abi(debug)` attribute.
- Those that use the `EMIT_MIR` annotation.
In each case the output is slightly uglier than before. This isn't
ideal, but it's pretty weird (particularly for the attribute) that the
output is using `Debug` in the first place. They're fairly obscure
attributes (I hadn't heard of them) so I'm not worried by this.
For `async-is-unwindsafe.stderr`, there is one line that now lacks a
full path. This is a consistency improvement, because all the other
mentions of `Context` in this test lack a path.
Add optimized lock methods for `Sharded` and refactor `Lock`
This adds methods to `Sharded` which pick a shard and also locks it. These branch on parallelism just once instead of twice, improving performance.
Benchmark for `cfg(parallel_compiler)` and 1 thread:
<table><tr><td rowspan="2">Benchmark</td><td colspan="1"><b>Before</b></th><td colspan="2"><b>After</b></th></tr><tr><td align="right">Time</td><td align="right">Time</td><td align="right">%</th></tr><tr><td>🟣 <b>clap</b>:check</td><td align="right">1.6461s</td><td align="right">1.6345s</td><td align="right"> -0.70%</td></tr><tr><td>🟣 <b>hyper</b>:check</td><td align="right">0.2414s</td><td align="right">0.2394s</td><td align="right"> -0.83%</td></tr><tr><td>🟣 <b>regex</b>:check</td><td align="right">0.9205s</td><td align="right">0.9143s</td><td align="right"> -0.67%</td></tr><tr><td>🟣 <b>syn</b>:check</td><td align="right">1.4981s</td><td align="right">1.4869s</td><td align="right"> -0.75%</td></tr><tr><td>🟣 <b>syntex_syntax</b>:check</td><td align="right">5.7629s</td><td align="right">5.7256s</td><td align="right"> -0.65%</td></tr><tr><td>Total</td><td align="right">10.0690s</td><td align="right">10.0008s</td><td align="right"> -0.68%</td></tr><tr><td>Summary</td><td align="right">1.0000s</td><td align="right">0.9928s</td><td align="right"> -0.72%</td></tr></table>
cc `@SparrowLii`
Encode only MIR reachable from other crates
Only reachable items might participate in the code generation in the
downstream crates. Omit redundant optimized MIR of unreachable items
from a crate metadata.
Additionally, include reachable closures in reachable set, so that
unreachable closures can be omitted on the same basis.
Only reachable items might participate in the code generation in the
downstream crates. Omit redundant optimized MIR of unreachable items
from a crate metadata.
Additionally, include reachable closures in reachable set, so that
unreachable closures can be omitted on the same basis.
Use `FreezeLock` for `CStore`
This uses `FreezeLock` to protect the `CStore`. `FreezeReadGuard` and `FreezeWriteGuard` are changed to support a `map` operation.
r? `@oli-obk`
Abort if check nightly options failed on stable
Fixes#115680
Also, if there are multiple unstable options passing on stable compiler, printing multiple same `note` and `help` seems noisy.
Add function that returns span of an item in smir
Addressees https://github.com/rust-lang/project-stable-mir/issues/31
Maybe we should change `Span = Opaque` into something else, and then return `String` with newly added function, I don't think it matters that much though, since we are not storing `Span` anywhere.
r? `@oli-obk`
Avoid a `source_span` query when encoding Spans into query results
This avoids a `source_span` query when encoding `Span`s into query results. It's not sound to execute queries here as the query caches can be locked and the dep graph is no longer writable.
r? `@cjgillot`
The lint panicked for an input like 'extern "C" fn(Option<&<T as FooTrait>::FooType>)' because the type T therein cannot be normalized. The normalization failure caused SizeSkeleton::compute() to return an error and trigger a panic in the unwrap().
Improve "associated type not found" diagnostics
```rs
use core::ops::Deref;
fn foo<T>() where T: Deref<Output = u32> {}
```
Before:
```
error[E0220]: associated type `Output` not found for `Deref`
--> E0220.rs:5:28
|
5 | fn foo<T>() where T: Deref<Output = u32> {}
| ^^^^^^ associated type `Output` not found
```
After:
```
error[E0220]: associated type `Output` not found for `Deref`
--> E0220.rs:5:28
|
5 | fn foo<T>() where T: Deref<Output = u32> {}
| ^^^^^^ help: `Deref` has the following associated type: `Target`
```
---
`@rustbot` label +A-diagnostics +D-papercut
debuginfo: add compiler option to allow compressed debuginfo sections
LLVM already supports emitting compressed debuginfo. In debuginfo=full builds, the debug section is often a large amount of data, and it typically compresses very well (3x is not unreasonable.) We add a new knob to allow debuginfo to be compressed when the matching LLVM functionality is present. Like clang, if a known-but-disabled compression mechanism is requested, we disable compression and emit uncompressed debuginfo sections.
The API is different enough on older LLVMs we just pretend the support
is missing on LLVM older than 16.
Use the same DISubprogram for each instance of the same inlined function within a caller
# Issue Details:
The call to `panic` within a function like `Option::unwrap` is translated to LLVM as a `tail call` (as it will never return), when multiple calls to the same function like this are inlined LLVM will notice the common `tail call` block (i.e., loading the same panic string + location info and then calling `panic`) and merge them together.
When merging these instructions together, LLVM will also attempt to merge the debug locations as well, but this fails (i.e., debug info is dropped) as Rust emits a new `DISubprogram` at each inline site thus LLVM doesn't recognize that these are actually the same function and so thinks that there isn't a common debug location.
As an example of this, consider the following program:
```rust
#[no_mangle]
fn add_numbers(x: &Option<i32>, y: &Option<i32>) -> i32 {
let x1 = x.unwrap();
let y1 = y.unwrap();
x1 + y1
}
```
When building for x86_64 Windows using 1.72 it generates (note the lack of `.cv_loc` before the call to `panic`, thus it will be attributed to the same line at the `addq` instruction):
```llvm
.cv_loc 0 1 3 0 # src\lib.rs:3:0
addq $40, %rsp
retq
leaq .Lalloc_f570dea0a53168780ce9a91e67646421(%rip), %rcx
leaq .Lalloc_629ace53b7e5b76aaa810d549cc84ea3(%rip), %r8
movl $43, %edx
callq _ZN4core9panicking5panic17h12e60b9063f6dee8E
int3
```
# Fix Details:
Cache the `DISubprogram` emitted for each inlined function instance within a caller so that this can be reused if that instance is encountered again.
Ideally, we would also deduplicate child scopes and variables, however my attempt to do that with #114643 resulted in asserts when building for Linux (#115156) which would require some deep changes to Rust to fix (#115455).
Instead, when using an inlined function as a debug scope, we will also create a new child scope such that subsequent child scopes and variables do not collide (from LLVM's perspective).
After this change the above assembly now (with <https://reviews.llvm.org/D159226> as well) shows the `panic!` was inlined from `unwrap` in `option.rs` at line 935 into the current function in `lib.rs` at line 0 (line 0 is emitted since it is ambiguous which line to use as there were two inline sites that lead to this same code):
```llvm
.cv_loc 0 1 3 0 # src\lib.rs:3:0
addq $40, %rsp
retq
.cv_inline_site_id 6 within 0 inlined_at 1 0 0
.cv_loc 6 2 935 0 # library\core\src\option.rs:935:0
leaq .Lalloc_5f55955de67e57c79064b537689facea(%rip), %rcx
leaq .Lalloc_e741d4de8cb5801e1fd7a6c6795c1559(%rip), %r8
movl $43, %edx
callq _ZN4core9panicking5panic17hde1558f32d5b1c04E
int3
```
lto: load bitcode sections by name
Upstream change
llvm/llvm-project@6b539f5eb8 changed `isSectionBitcode` works and it now only respects `.llvm.lto` sections instead of also `.llvmbc`, which it says was never intended to be used for LTO. We instead load sections by name, and sniff for raw bitcode by hand.
This is an alternative approach to #115136, where we tried the same thing using the `object` crate, but it got too fraught to continue.
r? `@nikic`
`@rustbot` label: +llvm-main
Use `Freeze` for `SourceFile`
This uses the `Freeze` type in `SourceFile` to let accessing `external_src` and `lines` be lock-free.
Behavior of `add_external_src` is changed to set `ExternalSourceKind::AbsentErr` on a hash mismatch which matches the documentation. `ExternalSourceKind::Unneeded` was removed as it's unused.
Based on https://github.com/rust-lang/rust/pull/115401.
LLVM already supports emitting compressed debuginfo. In debuginfo=full
builds, the debug section is often a large amount of data, and it
typically compresses very well (3x is not unreasonable.) We add a new
knob to allow debuginfo to be compressed when the matching LLVM
functionality is present. Like clang, if a known-but-disabled
compression mechanism is requested, we disable compression and emit
uncompressed debuginfo sections.
The API is different enough on older LLVMs we just pretend the support
is missing on LLVM older than 16.
Upstream change
llvm/llvm-project@6b539f5eb8 changed
`isSectionBitcode` works and it now only respects `.llvm.lto` sections
instead of also `.llvmbc`, which it says was never intended to be used
for LTO. We instead load sections by name, and sniff for raw bitcode by
hand.
r? @nikic
@rustbot label: +llvm-main
Rollup of 6 pull requests
Successful merges:
- #104299 (Clarify stability guarantee for lifetimes in enum discriminants)
- #115088 (Fix Step Skipping Caused by Using the `--exclude` Option)
- #115201 (rustdoc: list matching impls on type aliases)
- #115633 (Lint node for `PRIVATE_BOUNDS`/`PRIVATE_INTERFACES` is the item which names the private type)
- #115638 (`-Cllvm-args` usability improvement)
- #115643 (fix: return early when has tainted in mir-lint)
r? `@ghost`
`@rustbot` modify labels: rollup
fix: return early when has tainted in mir-lint
Fixes#115203
`a[..]` is of indeterminate size, it had been reported error during borrow check, therefore we skip the mir lint process.
`-Cllvm-args` usability improvement
fixes: #26338fixes: #115564
Two problems were found during playing with `-Cllvm-args`
1. When `llvm.link-shared` is set to `false` in `config.toml`, output of `rustc -C llvm-args='--help-list-hidden'` doesn't contain `--emit-dwarf-unwind` and `--emulated-tls`. When it is set to `true`, `rustc -C llvm-args='--help-list-hidden'` emits `--emit-dwarf-unwind`, but `--emulated-tls` is still missing.
2. Setting `-Cllvm-args=--emit-dwarf-unwind=always` doesn't take any effect, but `-Cllvm-args=-machine-outliner-reruns=3` does work.
### 1
Adding `RegisterCodeGenFlags` to register codegen flags fixed the first problem. `rustc -C llvm-args='--help-list-hidden'` emits full codegen flags including `--emit-dwarf-unwind` and `--emulated-tls`.
### 2
Constructing `TargetOptions` from `InitTargetOptionsFromCodeGenFlags` in `LLVMRustCreateTargetMachine` fixed the second problem. The `LLVMRustSetLLVMOptions` calls `ParseCommandLineOptions` which parses given `llvm-args`. For options like `machine-outliner-reruns`, it just works, since the codegen logic directly consumes the parsing result:
[machine-outliner-reruns register](0537f6354c/llvm/lib/CodeGen/MachineOutliner.cpp (L114))
[machine-outliner-reruns consumption](0537f6354c/llvm/lib/CodeGen/MachineOutliner.cpp (L1138))
But for flags defined in `TargetOptions` and `MCTargetOptions` to take effect, constructing them with `InitTargetOptionsFromCodeGenFlags` is essential, or the parsing result is just not consumed. Similar patterns can be observed in [lli](0537f6354c/llvm/tools/llc/llc.cpp (L494)), [llc](0537f6354c/llvm/tools/lli/lli.cpp (L517)), etc.
Lint node for `PRIVATE_BOUNDS`/`PRIVATE_INTERFACES` is the item which names the private type
The HIR that the `PRIVATE_BOUNDS` lint should be attached to is the item that has the *bounds*, not the private type. This PR also aligns this behavior with the `EXPORTED_PRIVATE_DEPENDENCIES` lint, which also requires putting the `allow` on the item that names the private type.
Fixes#115475
r? petrochenkov
Add CL and CMD into to pdb debug info
Partial fix for https://github.com/rust-lang/rust/issues/96475
The Arg0 and CommandLineArgs of the MCTargetOptions cpp class are not set within bb548f9645/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp (L378)
This causes LLVM to not neither output any compiler path (cl) nor the arguments that were used when invoking it (cmd) in the PDB file.
This fix adds the missing information to the target machine so LLVM can use it.
`Span` has undergone some changes over the years (addition of an optional
parent, and possible inlining of the context in interned spans) but the
comments and identifiers used haven't kept up. As a result, I find it
harder to understand than I should.
This commit reworks the comments, renames some identifiers, and
restructures the code slightly, all to make things clearer. I now feel
like I understand this code again.
Don't suggest dereferencing to unsized type
Rudimentary check that the self type is Sized. I don't really like any of this diagnostics code -- it's really messy and also really prone to false positives and negatives, but oh well.
Fixes#115569
Print the path of a return-position impl trait in trait when `return_type_notation` is enabled
When we're printing a return-position impl trait in trait, we usually just print it like an opaque. This is *usually* fine, but can be confusing when using `return_type_notation`. Print the path of the method from where the RPITIT originates when this feature gate is enabled.
miri: catch function calls where the argument is caller-invalid / the return value callee-invalid
When doing a type-changing copy, we must validate the data both at the old and new type.
Fixes https://github.com/rust-lang/miri/issues/3017
coverage: Simplify the `coverageinfo` query
The `coverageinfo` query walks through a `mir::Body`'s statements to find the total number of coverage counter IDs and coverage expression IDs that have been used, as this information is needed by coverage codegen.
This PR makes 3 nice simplifications to that query:
- Extract a common iterator over coverage statements, shared by both coverage-related queries
- Simplify the query's visitor from two passes to just one pass
- Explicitly track the highest seen IDs in the visitor, and only convert to a count right at the end
I also updated some related comments. Some had been invalidated by these changes, while others had already been invalidated by previous coverage changes.
Don't require `Drop` for `[PhantomData<T>; N]` where `N` and `T` are generic, if `T` requires `Drop`
fixes https://github.com/rust-lang/rust/issues/115403
fixes https://github.com/rust-lang/rust/issues/115410
This was accidentally regressed in https://github.com/rust-lang/rust/pull/114134, because it was accidentally stabilized in #102204 (cc `@rust-lang/lang,` seems like an innocent stabilization, considering this PR is more of a bugfix than a feature).
While we have a whole month to beta backport this change before the regression hits stable, I'd still prefer not to go through an FCP on this PR (which fixes a regression), if T-lang wants an FCP, I can can open an issue about the change itself.
Stabilize `PATH` option for `--print KIND=PATH`
This PR propose stabilizing the `PATH` option for `--print KIND=PATH`. This option was previously added in https://github.com/rust-lang/rust/pull/113780 (as insta-stable before being un-stablized in https://github.com/rust-lang/rust/pull/114139).
Description of the `PATH` option:
> A filepath may optionally be specified for each requested information kind, in the format `--print KIND=PATH`, just like for `--emit`. When a path is specified, information will be written there instead of to stdout.
------
Description of the original PR [\[link\]](https://github.com/rust-lang/rust/pull/113780#issue-1807080607):
> **Support --print KIND=PATH command line syntax**
>
> As is already done for `--emit KIND=PATH` and `-L KIND=PATH`.
>
> In the discussion of https://github.com/rust-lang/rust/pull/110785, it was pointed out that `--print KIND=PATH` is nicer than trying to apply the single global `-o path` to `--print`'s output, because in general there can be multiple print requests within a single rustc invocation, and anyway `-o` would already be used for a different meaning in the case of `link-args` and `native-static-libs`.
>
> I am interested in using `--print cfg=PATH` in Buck2. Currently Buck2 works around the lack of support for `--print KIND=PATH` by [indirecting through a Python wrapper script](d43cf3a51a/prelude/rust/tools/get_rustc_cfg.py) to redirect rustc's stdout into the location dictated by the build system.
>
> From skimming Cargo's usages of `--print`, it definitely seems like it would benefit from `--print KIND=PATH` too. Currently it is working around the lack of this by inserting `--crate-name=___ --print=crate-name` so that it can look for a line containing `___` as a delimiter between the 2 other `--print` informations it actually cares about. This is commented as a "HACK" and "abuse". 31eda6f7c3/src/cargo/core/compiler/build_context/target_info.rs (L242)
-----
cc `@dtolnay`
r? `@jackh726`
Upstream change
llvm/llvm-project@6b539f5eb8 changed
`isSectionBitcode` works and it now only respects `.llvm.lto` sections
instead of also `.llvmbc`, which it says was never intended to be used
for LTO. We instead load sections by name, and sniff for raw bitcode by
hand.
r? @nikic
@rustbot label: +llvm-main
Description of the `PATH` option:
> A filepath may optionally be specified for each requested information
> kind, in the format `--print KIND=PATH`, just like for `--emit`. When
> a path is specified, information will be written there instead of to
> stdout.
Don't report any errors in `lower_intrinsics`.
Intrinsics should have been type checked earlier.
This is part of moving all mir-opt diagnostics early enough so that they are reliably emitted even in check builds: https://github.com/rust-lang/rust/issues/49292#issuecomment-1692212095
Both of the coverage queries can now use this one helper function to iterate
over all of the `mir::Coverage` payloads in the statements of a `mir::Body`.
Implement refinement lint for RPITIT
Implements a lint that warns against accidentally refining an RPITIT in an implementation. This is not a hard error, and can be suppressed with `#[allow(refining_impl_trait)]`, since this behavior may be desirable -- the lint just serves as an acknowledgement from the impl author that they understand that the types they write in the implementation are an API guarantee.
This compares bounds syntactically, not semantically -- semantic implication is more difficult and essentially relies on adding the ability to keep the RPITIT hidden in the trait system so that things can be proven about the type that shows up in the impl without its own bounds leaking through, either via a new reveal mode or something else. This was experimentally implemented in #111931.
Somewhat opinionated choices:
1. Putting the lint behind `refining_impl_trait` rather than a blanket `refine` lint. This could be changed, but I like keeping the lint specialized to RPITITs so the explanation can be tailored to it.
2. This PR does not include the `#[refine]` attribute or the feature gate, since it's kind of orthogonal and can be added in a separate PR.
r? `@oli-obk`
Sync rustc_codegen_cranelift
Not much changed this time. Mostly doing this sync to make it easier to run the entire test suite on the in-tree version.
r? `@ghost`
`@rustbot` label +A-codegen +A-cranelift +T-compiler
Use a specialized varint + bitpacking scheme for DepGraph encoding
The previous scheme here uses leb128 to encode the edge tables that represent the incr comp dependency graph. The problem with that scheme is that leb128 has overhead for larger values, and generally relies on the distribution of encoded values being heavily skewed towards smaller values. That is definitely not the case for a dep node index, since they are handed out sequentially and the whole range is covered, the distribution is actually biased in the opposite direction: Most dep nodes are large.
This PR implements a different varint encoding scheme. Instead of applying varint encoding to individual dep node indices (which is extremely branchy) we now apply it per node.
While being built, each node now stores its edges in a `SmallVec` with a bit of extra logic to track the max value of each edge. Then we varint encode the whole batch. This is a gamble: We save on space by only claiming 2 bits per node instead of ~3 bits per edge which is a nice savings but needs to balance out with the space overhead that a single large index in a node with a lot of edges will encode unnecessary bytes in each of that node's edge indices.
Then, to keep the runtime overhead of this encoding scheme down we deserialize our indices by loading 4 bytes for each then masking off the bytes that are't ours. This is much less code and branches than leb128, but relies on having some readable bytes past the end of each edge list. We explicitly add such padding to the in-memory data during decoding. And we also do this decoding lazily, turning a dense on-disk encoding into a peak memory reduction.
Then we apply a bit-packing scheme; since in https://github.com/rust-lang/rust/pull/115391 we now have unused bits on `DepKind`, we use those unused bits (currently there are 7!) to store the 2 bits that we need for the byte width of the edges in each node, then use the remaining bits to store the length of the edge list, if it fits.
r? `@nnethercote`
Lint on invalid usage of `UnsafeCell::raw_get` in reference casting
This PR proposes to take into account `UnsafeCell::raw_get` method call for non-Freeze types for the `invalid_reference_casting` lint.
The goal of this is to catch those kind of invalid reference casting:
```rust
fn as_mut<T>(x: &T) -> &mut T {
unsafe { &mut *std::cell::UnsafeCell::raw_get(x as *const _ as *const _) }
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
}
```
r? `@est31`
Update stdarch submodule and remove special handling in cranelift codegen for some AVX and SSE2 LLVM intrinsics
https://github.com/rust-lang/stdarch/pull/1463 reimplemented some x86 intrinsics to avoid using some x86-specific LLVM intrinsics:
* Store unaligned (`_mm*_storeu_*`) use `<*mut _>::write_unaligned` instead of `llvm.x86.*.storeu.*`.
* Shift by immediate (`_mm*_s{ll,rl,ra}i_epi*`) use `if` (srl, sll) or `min` (sra) to simulate the behaviour when the RHS is out of range. RHS is constant, so the `if`/`min` will be optimized away.
This PR updates the stdarch submodule to pull these changes and removes special handling for those LLVM intrinsics from cranelift codegen. I left gcc codegen untouched because there are some autogenerated lists.
fix#115348fix#115348
It looks that:
- In `rustc_mir_build::build`, the body of function will not be built, when the `tcx.check_match(def)` fails due to `non-exhaustive patterns`
- In `rustc_mir_transform::check_unsafety`, the `UnsafetyChecker` collects all `used_unsafe_blocks` in the MIR of a function, and the `UnusedUnsafeVisitor` will visit all `UnsafeBlock`s in the HIR and collect `unused_unsafes`, which are not contained in `used_unsafe_blocks`, and report `unnecessary_unsafe`s
- So the unsafe block in the issue example code will be reported as `unnecessary_unsafe`.
Replace `rustc_data_structures` dependency with `rustc_index` in `rustc_parse_format`
`rustc_data_structures` is only used for the `static_assert_size` macro, yet that is defined in `rustc_index` and merely re-exported. `rustc_index` is a lot more lightweight than `rustc_data_structures` which would make this a lot more reusable for rust-analyzer.
Add explanatory note to 'expected item' error
Fixes#113110
It changes the diagnostic from this:
```
error: expected item, found `5`
--> ../test.rs:1:1
|
1 | 5
| ^ expected item
```
to this:
```
error: expected item, found `5`
--> ../test.rs:1:1
|
1 | 5
| ^ expected item
|
= note: items are things that can appear at the root of a module
= note: for a full list see https://doc.rust-lang.org/reference/items.html
```
Represent MIR composite debuginfo as projections instead of aggregates
Composite debuginfo for MIR is currently represented as
```
debug name => Type { projection1 => place1, projection2 => place2 };
```
ie. a single `VarDebugInfo` object with that name, and its value a `VarDebugInfoContents::Composite`.
This PR proposes to reverse the representation to be
```
debug name.projection1 => place1;
debug name.projection2 => place2;
```
ie. multiple `VarDebugInfo` objects with each their projection.
This simplifies the handling of composite debuginfo by the compiler by avoiding weird nesting.
Based on https://github.com/rust-lang/rust/pull/115139
Add `FreezeLock` type and use it to store `Definitions`
This adds a `FreezeLock` type which allows mutation using a lock until the value is frozen where it can be accessed lock-free. It's used to store `Definitions` in `Untracked` instead of a `RwLock`. Unlike the current scheme of leaking read guards this doesn't deadlock if definitions is written to after no mutation are expected.
It uses `once` chained with `(0..self.num_calls).map(...)` followed by
`.take(self.num_calls`. I found this hard to read. It's simpler to just
use `repeat_with`.
replace doc occurrences of ItemLikeVisitor
Solves #114885
ItemLikeVisitor used to have comments describing visit patterns. After it was removed, it was moved to `rustc_hir::intravisit` but references in `intravisit.rs` weren't updated.
Fix error report for size overflow from transmute
Fixes#115402
The span in the error reporting always points to the `dst`, this is an old issue, I may open another PR to fix it.
Make if let guard parsing consistent with normal guards
- Add tests that struct expressions are not allowed in `if let` and `while let` (no change, consistent with `if` and `while`)
- Allow struct expressions in `if let` guards (consistent with `if` guards).
r? `@cjgillot`
Closes#93817
cc #51114
Use relative positions inside a SourceFile.
This allows to remove the normalization of start positions for hashing, and simplify allocation of global address space.
cc `@Zoxc`
Currently we stop compilation, but some users might want to keep going.
This is needed for us to test against rustc tests. Other tools, such as
Kani, also implements parts of their logic as a backend so it is
important for compilation to continue.
Invoking StableMir::run() on a crate that has any compilation error was
crashing the entire process. Instead, return a `CompilerError` so the
user knows compilation did not succeed.
I believe ICE will also be converted to `CompilerError`.
I'm also adding a return value to the callback, because I think it will
be handy for users (at least it was for my current task of implementing
a tool to validate stable-mir). However, if people disagree,
I can remove that.
Rollup of 5 pull requests
Successful merges:
- #115353 (Emit error instead of ICE when optimized MIR is missing)
- #115488 (Take `&mut Results` in `ResultsVisitor`)
- #115492 (Allow `large_assignments` for Box/Arc/Rc initialization)
- #115519 (Don't ICE on associated type projection without feature gate in new solver)
- #115534 (Expose more information with DefId in smir)
r? `@ghost`
`@rustbot` modify labels: rollup
Expose more information with DefId in smir
Currently `Debug` for `DefId` doesn't provide enough information, this changes so that we get `usize` of the `DefId` and the name of it.
r? `@oli-obk`
Don't ICE on associated type projection without feature gate in new solver
Self-explanatory, we should avoid ICEs when the feature gate is not enabled. Continue to ICE when the feature gate *is* enabled, though.
Fixes#115500
Allow `large_assignments` for Box/Arc/Rc initialization
Does the `stop linting in box/arc initialization` task of #83518.
r? `@oli-obk` who is E-mentor.
Do not require associated types with Self: Sized to uphold bounds when confirming object candidate
RPITITs and associated types that have `Self: Sized` bounds are opted out of the `dyn Trait` well-formedness check that happens during confirmation. This ensures that we can actually *use* `dyn Trait`s that have associated types that, e.g., have GATs and RPITITs and other naughty things as long as those are opted-out of object safety via a `Self: Sized` bound.
Fixes#115464
This seems like a natural part of https://github.com/rust-lang/rust/pull/112319#issuecomment-1592574451, and I don't think needs re-litigation.
r? `@oli-obk`
Encode DepKind as u16
The derived Encodable/Decodable impls serialize/deserialize as a varint, which results in a lot of code size around the encoding/decoding of these types which isn't justified: The full range of values here is rather small but doesn't quite fit in to a `u8`. Growing _all_ serialized `DepKind` to 2 bytes costs us on average 1% size in the incr comp dep graph, which I plan to recoup in https://github.com/rust-lang/rust/pull/110050 by taking advantage of the unused bits in all the serialized `DepKind`.
r? `@nnethercote`