Add a new `rustc_show_spans` internal attribute
This new internal attribute is a first step for solving rust-lang/rust#126763.
Given the code:
```rust
#![feature(rustc_attrs)]
mod x { pub const Y: u8 = 1; }
macro_rules! path { ($a:tt, $b:tt) => { let _ = $a::$b; }; }
#[rustc_show_spans(path)]
fn no_macro() { let _ = x::Y; }
#[rustc_show_spans(path)]
fn path_bug() { path!(x, Y); }
```
We can now report the spans and thus show the bug of the span not falling inside the macro context:
```
note: showing the spans of the path
--> test.rs:8:25
|
8 | fn no_macro() { let _ = x::Y; }
| ^^^^
note: showing the spans of the path
--> test.rs:11:23
|
11 | fn path_bug() { path!(x, Y); }
| ^^^^
```
r? @petrochenkov
This new attribute is a first step for solving issue 126763.
Now, we can easily test out where spans end up, particularly useful for
ensuring that spans end up in the best suitable macro context.
aarch64: Use neon registers for ABI on targets that require `neon"
This PR is the aarch64 version of https://github.com/rust-lang/rust/pull/161583.
When a target requires the neon feature (which all `aarch64[_be]` hardfloat targets do), pass any vectors that fit (all sized vectors on aarch64 should do) in those registers.
We also make disable the `neon` target feature a hard error since doing so is much more likely to result in miscompilations as a result of this change, as the previous patch did for SSE.
I've also check the stdarch CI for aarch64-unknown-linux-gnu and aarch64_be-linux-gnu locally with no issues.
Pass the unremapped path to the `rustc` invocation for doctests
Turns out that `--remap-path-scope` is only half working with doctests, this is because `rustdoc` use a secret environment variable to pass the real filename of the doctest.
However we were only passing a remapped path. That means that doctests source path were getting remapped, but only for one scope: `documentation`. It didn't respect `macro` for `file!` for example.
To fix this, we have to:
1. pass the local path to the `rustc` invocation
2. have `rustc` treat that path as a real filename and apply remapping per scope to it
- I had to add a new `Input` variant, otherwise I can't differentiate normal input `-` from doctests `-` source
4. we have to pass `--remap-path-{prefix,scope}` to `rustc` so the path actually gets remap properly
`VecCache` stores a second set of buckets, `present`, that track the
keys used. This supports simpler iteration over the buckets, when doing
incremental builds, `-Zincremental-verify-ich`, self-profiling, or rustc
debug assertions.
However, when doing a full non-incremental build and *not* doing
verify-ich, self-profiling, or rustc debug assertions, the second set of
buckets are never used, and maintaining them wastes space and
instructions.
Disable that code for that case, and add assertions ensuring `present`
never gets used.
Verifying this requires running a local copy of the perf collector that
does not pass `-Zincremental-verify-ich` on full builds. I ran the
`cargo`, `image`, and `ripgrep` builds locally under both bench and DHAT
profiling, and also ran `aws-sdk-ec2` (1.175.1) as a bench.
aws-sdk-ec2 full check max-rss improved by 62.6 MiB (1.13%).
cargo DHAT peak saved 4.7 MiB (0.74%), max-rss saved 2.6 MiB (0.30%).
image DHAT peak saved 2.3 MiB (1.73%), max-rss saved 1.50 MiB (0.53%).
ripgrep DHAT peak saved 2.02 MiB (3.22%), max-rss saved 1.10 MiB (0.55%).
(Differences in DHAT peak vs max-rss are likely due to allocations vs
actually accessed pages within those allocations. Differences in amount
saved between benchmarks are due to number of queries and number of
buckets needed to hold those queries.)
All of these also improved marginally in instructions executed.
Annotate MIR with dataflow results for testing purposes
When requested through an internal rustc attribute, include dataflow
results in MIR output, i.e., `-Zunpretty=mir` or `--emit mir`.
For now, supported dataflows are:
* `#[rustc_mir(rustc_pretty_live_locals)]`
* `#[rustc_mir(rustc_pretty_transitive_live_locals)]`
The mechanism is intended to supersede existing `rustc_peek` intrinsic.
For demonstration also migrates one of tests based on `rustc_peek`:
tests/ui/mir-dataflow/liveness-projection.rs.
When requested through an internal rustc attribute, include dataflow
results in MIR output, i.e., `-Zunpretty=mir` or `--emit mir`.
For now, supported dataflows are:
* `#[rustc_mir(rustc_pretty_live_locals)]`
* `#[rustc_mir(rustc_pretty_transitive_live_locals)]`
The mechanism is intended to supersede existing `rustc_peek` intrinsic.
For demonstration also migrates one of tests based on `rustc_peek`:
tests/ui/mir-dataflow/liveness-projection.rs.
MIR move elimination [2/6]: TailCopyToMove
Depends on rust-lang/rust#163335
This PR implements a pre-pass for the `MoveElimination` pass from https://github.com/rust-lang/rfcs/pull/3943.
`TailCopyToMove` turns `Copy` into `Move` just before a `Return` terminator. This is valid even for places that have been borrowed because the `Return` will invalidate borrows anyway. This is necessary to allow the source of the copy to be unified with the return place.
r? tmiasko
Deterministic encoding of `DefPathHashMap`
This PR splits DefPathHashMap into two parts: deterministic (`det_part`) and non-deterministic (`non_det_part`). `det_part` is used while we sure that allocation and insertion order of def ids is deterministic, at the moment of writing it happens before we start parallel checks after prefetch of `hir_crate_items` in `run_required_analysis`. Up until this point of compilation the allocation of def ids and their insertion order into `det_part` should be the same between different compilations.
Next, when non-determinism starts due to parallel compilation we put all mapping between local hash and def ids into a `SortedMap` which gives us ready-to-use sorted by local hash slice of pairs to encode while encoding metadata.
Note, that this PR does not solve the problem of allocation of different def indices to same code entities (meaning same local hash), this problem is solved in rust-lang/rust#162809 by remapping needed local def indices.
Also note that we serialize `det_part` as a raw bytes sequence, so during remapping if we do not place all def indices that are needed to be remapped into separate container we will end up with copying `det_part`, changing some entries in it and then serialize it as a bytes sequence. With the approach in this PR we do not copy and modify `det_part`, instead we do all modifications in `non_det_part`.
r? @petrochenkov
Remove `PartialOrd`/`Ord` impls for `Span`/`SpanData`
Because they are inconsistent with the `PartialEq`/`Eq` impls, and span ordering is inherently dubious. Details in individual commits.
r? @oli-obk
Ensure llvm worker threads have sufficient stack space
The rustc driver sets the default stack size to 16MB, however worker threads spawned by the backend will use std's default stack size (usually 2MB).
Pass through the stack size chosen by the driver to the backend, and explicitly request the stack size.
This probably isn't the preferred way to do this, but maybe a starting point to educate me.
This doesn't catch every spawned thread (jobserver and ctrlc also create them through std). Are there other threads which might be sensitive to small stack sizes?
Fixesrust-lang/rust#163272
`Span` and `SpanData` encode four fields: `lo`/`hi`, `ctxt`, and
`parent`. `ctxt` and `parent` have unorderable types.
Both types ignore `ctxt` and `parent` for `PartialOrd`/`Ord`. But their
`PartialEq`/`Eq` impls do *not* ignore those fields. This eq/ord
inconsistency is a bug. It was introduced in #123165.
The idea of ordering spans in general is dubious, because of `ctxt` and
`parent`. But the idea of ordering spans just with `lo`/`hi` is fine.
Therefore, this commit does the following.
- Removes the `PartialOrd`/`Ord` impls for `Span`/`SpanData`
- Adds a `Span::lo_hi` method which can be used in lots of places where
span locations are involved in sorting. E.g.
`xs.sort_by_key(|span| span.lo_hi())`
- Adds `OrdSpan`, a newtype around `Span` that impls
`PartialEq`/`Eq`/`PartialOrd`/`Ord` using `lo_hi`. This is for storing
spans in ordered types like `BTreeMap<OrdSpan, T>`.
Note also that some `sort`+`dedup` combinations might not remove all
duplicates with the old eq/ord inconsistency. These now all do the right
thing, which could affect some error messages, though in practice
nothing in the test suite is affected.
The rustc driver sets the default stack size to 16MB, however
worker threads spawned by the backend will use std's default
stack size (usually 2MB).
Pass through the stack size chosen by the driver to the backend,
and explicitly request the stack size.
Build a new incr comp session dir from scratch every time
Rather than copying the old incr comp dir and then modifying it. This saves a copy/hardlink for files that are modified. And it removes the need for accurate work product tracking to avoid accumulating cruft, which is non-trivial. We don't accurately track the pre-LTO bitcode files for ThinLTO for example.
Part of https://github.com/rust-lang/compiler-team/issues/908
Rather than copying the old incr comp dir and then modifying it. This
saves a copy/hardlink for files that are modified. And it removes the
need for accurate work product tracking to avoid accumulating cruft,
which is non-trivial. We don't accurately track the pre-LTO bitcode
files for ThinLTO for example.
`core::num::f16b` Rust's 16bit Brain Float
Implements the [RFC: f16b type](https://github.com/rust-lang/rfcs/pull/3983). Best reviewed commit by commit, happy to split into separate PRs if that is deemed easier to review. However the line count and surface area is, in my opinion, reasonably small.
Adds;
- ABI plumbing for the `f16b` along with `bfloat` lang item to work with LLVM, GCC is explicitly `unimplemented!(...)`
- `f16b` feature gate, page for `f16b` on libruscdoc and a `struct bf16` in `core::num`
- Tests
- Treat `f16b` as a scalar primitive for scalable vectors
Issues;
- [Tracking Issue](https://github.com/rust-lang/rust/issues/160630)
- [RFC](https://github.com/rust-lang/rfcs/pull/3983)
It encodes the `emit` behaviour, one of:
- `BugAbort`: Abort as a bug.
- `FatalAbort`: Abort as a fatal error.
- `ErrorGuaranteed`: Return an `ErrorGuaranteed` (the default).
- `()`: return `()`.
This is useful but `Diag` is very widely used and it's arguably not
useful enough to be worth the generic parameter. This commit removes it.
Benefits:
- Many fewer generic parameters, including many functions where the
genericity is entirely uninteresting. This includes every
`Diagnostic::into_diag` and `Subdiagnostic::add_to_diag`. Removes the
need for the comment about `<G>` on `trait Diagnostic`.
- No `PhantomData` in `Diag`.
- Makes bootstrapping a bit faster.
The downside is there is no longer a single `emit` method.
- Getting a `!` return type requires calling `emit_bug` or `emit_fatal`.
This only affects a few call sites.
- Getting an `ErrorGuaranteed` return type requires calling `emit_err`.
This affects a lot of call sites. (It arguably makes call sites more
self-documenting.)
- Using the wrong `emit_*` on a diagnostic causes a runtime abort, which
previously couldn't occur. Seems unlikely, but it's not impossible.
- Note: If no particular return type is needed, `emit` can be used for
any diagnostic. (Bug/fatal diagnostics will still trigger abort.)
Adjust `bug!`/`span_bug!` emission
PR rust-lang/rust#161873 moved these macros from `rustc_middle` to `rustc_span`. In doing so it made some undesirable changes.
- The internal `emit_producing_nothing` became public.
- The macros now have different behaviour to function-based ICEs like `dcx.bug(..)` or `dcx.struct_bug(..).emit()`.
This commit reverts those changes. This brings back `Box<dyn Any>` output in a few tests because the panic payload is `ExplicitBug` (which std doesn't know about) rather than `String`. That might be worth fixing again in the future, but if so, it should be done in a way that works with all aborts, not just those done via the macros.
r? @mejrs
Currently it uses `eprintln!` for the "query stack during panic" header
and "end of query stack" footer and
`struct_failure_note(..).with_span(..).emit()` for the stack frames. The
difference is curious.
Looking more closely:
- failure notes lack a leading label (e.g. no "note: ");
- although the failure note is given a span, the span never renders
because the `AnnotateSnippetEmitter` used for the query stack has an
empty source map field;
- the JSON emitter is never involved here.
Therefore, the only difference between using `struct_failure_note` and
`eprintln!` is that the former prints in bold. But boldness for frames
isn't important; indeed, normal backtrace frames don't use bold.
So the commit changes query stack frame printing to use `eprintln!`,
removes some now unnecessary `dcx` arguments, and also removes
`struct_failure_note`. That leaves "For more information about an error,
try `rustc --explain {}`" as the only use of `FailureNote`.
PR #161873 moved these macros from `rustc_middle` to `rustc_span`. In
doing so it made some undesirable changes.
- The internal `emit_producing_nothing` became public.
- It gave the macros different behaviour to function-based ICEs like
`dcx.bug(..)` or `dcx.struct_bug(..).emit()`.
- `ExplicitBug` is not used, so `report_ice` prints an extraneous,
unintended "the compiler unexpectedly panicked" message.
- It broke the interaction between `span_bug!` and
`-Ztrack-diagnostics`.
This commit adjusts things to avoid the undesirable changes. It required
moving `ExplicitBug` to `rustc_span`. Setting `diag.emitted_at` fixed
the `-Ztrack-diagnostics` problem, seen in the change from `callback.rs`
to `validate.rs` in `track7.stderr`.
`Box<dyn Any>` output now occurs again in a few tests because the panic
payload is `ExplicitBug` (which std doesn't know about) rather than
`String`. That might be worth addressing in the future but it would
require a different/additional mechanism and is beyond the scope of this
PR.
Replace hard linked `metadata.rmeta` with a copy when finalizing the incremental compilation session dir fails
Fixesrust-lang/rust#151181.
Since 1.90.0, on ReFS (Windows Dev Drive) volumes finalizing the incremental compilation session directory would fail with `Access is denied. (os error 5)`. The issue was caused by rust-lang/rust#114669, which meant that `metadata.rmeta` inside the session dir was a hard link to a file that was potentially being used by several other processes and ReFS seemingly refuses to rename such directories. As a fallback, we try to replace the hard linked metadata file with a copy instead, so that the rename can succeed.
I don't think adding a test for this is possible due to the lack of a ReFS runner but I added a unit test for the `replace_hard_link_with_copy` helper.
r? @bjorn3
It currently takes `&self`, which is a bit strange for an `init` method.
As a result, the Cranelift and GCC backends have to use types with
interior mutability.
This commit changes it to `&mut self`. Benefits:
- The Cranelift backend can use `Option` instead of `OnceCell` to
indicate uninit vs. init.
- The GCC backend can avoid `Mutex`, and use `bool` instead of
`AtomicBool`, which makes things much simpler. The commit also
restructures `GccCodegenBackend` to mirror `CraneliftCodegenBackend`:
just contain an `Option<BackendConfig>`, which makes the uninit vs.
init distinction foolproof. (E.g. no need to set `lto_supported` to
false and then later overwrite it with the real value.) As part of
this the `LockedTargetInfo` type is renamed `SharedTargetInfo` because
that better matches its new internals. (All this compiles both with
and without the "master" feature set.)
Session creation is currently awkward: we build a mostly-initialized
session, then use it to initialize a codegen backend, and then use the
codegen backend to finish initializing the session.
And it's not just awkward: within the Cranelift backend's `init` method
`sess.lto()` is called, which consults `sess.thin_lto_supported`,
*before* that field has been properly set! In practice it had no effect
but it's worth fixing.
This commit cleans up this mess. It introduces `EarlySession`, which
contains just four `Session` fields, the ones that are needed for
codegen backend initialization. It is now a field within `Session`, and
`Session` derefs to `EarlySession` to avoid changing a zillion
`sess.target`/`sess.opts`/etc. occurrences. `EarlySession` is passed to
`init`, which returns a `CodegenBackendInit` that contains the
backend-specific information needed to build a `Session`. (It replaces
the `replaced_intrinsics`, `fallback_intrinsics`, and
`thin_lto_supported` methods.) The `Session` can then be built in a
single step. No more `Session`/`CodegenBackend` initialization
intermingling.
A few functions that previously took a `Session` now take something
else, e.g. a `Target`. Some `Session` methods are now `EarlySession`
methods. And a new `early_lto` method is used for Cranelift's LTO check.
move bug and span_bug macros to rustc_span
This allows them to be used without depending on rustc_middle.
This is done by using a rustc_interface callback so that, if the callback is set, a internal compiler error diagnostic is printed through that. After that the panic is initiated.
r? @jdonszelmann @bjorn3
diagnostics: reject sanitizer compiles of proc-macro
We discussed this at the project all hands way back in May, and I'm only just now getting to it. Since proc-macros get loaded into rustc, it's not helpful to try and compile them in a sanitizer mode because you'll most likely end up with incompatible uses of things like the sanitizer runtimes.
Avoid the `arena_cache` modifier for several queries
The `arena_cache` query modifier is convenient, but we can potentially avoid some overhead by allocating values into the central `tcx.arena` when possible.
There should be no change to compiler output.
Introduce `rustc_middle::middel::resolve`
There are various types used to carry name resolution results across crate boundaries. They are scattered across places like `rustc_middle::ty`, `rustc_middle::metadata`, and `rustc_hir::def`.
This commit moves them into the new module, a more logical place for them to live. As part of this it eliminates the small `rustc_middle::metadata` module.
One nice consequence of this change: it removes the single use of a `LocalDefId` in `rustc_ast`. (This is what got my attention in the first place.)
r? @petrochenkov
There are various types used to carry name resolution results across
crate boundaries. They are scattered across places like
`rustc_middle::ty`, `rustc_middle::metadata`, and `rustc_hir::def`.
This commit moves them into the new module, a more logical place for
them to live. As part of this it eliminates the small
`rustc_middle::metadata` module.
One nice consequence of this change: it removes the single use of a
`LocalDefId` in `rustc_ast`. (This is what got my attention in the first
place.)
make target feature ABI check a hard error on ARM
With LLVM 24, we now (finally) get hard errors from the backend for "you want ABI X but the target features required for that ABI are missing", at least on the ARM backend:
```
error: <unknown>:0:0: in function _RNvXsc_Cs4Af2OiBEA1T_8minicoreiNtB5_3Add3add i32 (i32, i32): calling convention is hard-float, but floating-point registers are unavailable
```
That's not a pretty error, so let's make rust emit a hard error before we even get there -- just on ARM for now, matching LLVM. We have emitted a future-compat error for this since Rust 1.86 (https://github.com/rust-lang/rust/pull/136147, https://github.com/rust-lang/rust/pull/134794). I'm not making it a hard error everywhere since for other targets we are still figuring out the exact things we have to check, and it's better to do that without risking new hard errors.
For ARM, the exact check we are doing is:
- every target must set `llvm_floatabi` to either "soft" or "hard"
- on softfloat targets, no check is needed
- on hardfloat targets, the "fpregs" target feature is *required* and the the "soft-float" target feature is *forbidden*
Since this is a new hard error, this probably requires FCP. I am not sure for which team -- @rust-lang/lang is often involved for target feature things, but this is mostly about rejecting invalid `-C` flags which are handled by t-compiler (@davidtwco @BoxyUwU).
Fixes https://github.com/rust-lang/rust/issues/161276
Tracking issue rust-lang/rust#116344
Cc @TimNN
Remove -Zsaturating-float-casts flag
I added this flag back in 2017 (rust-lang/rust#45205) to enable benchmarking of the saturating semantics when it was newly implemented and still experimental. But saturation has been the official semantics for float<->int `as` casts for years now. A flag for turning it off no longer serves any purpose, it's just `-Zplease-miscompile-casts` now.