refactor handling of target features in Session
`Session` currently contains two lists of target features: `target_features`, which is also exposed in `cfg`, and `unstable_target_features`, which is used internally to communicate between various parts of the compiler which target features are *actually* available, including some that we don't have plans to put in `cfg`, namely "forbidden" target features. The `unstable_target_features` list is *not* equivalent to what nightly code sees in `cfg(target_features)` as the latter excludes "forbidden" target features. Both lists are computed by `fn cfg_target_features` even though one of them is never used for `cfg`. It's all kind of messy.
This PR refactors that: `fn cfg_target_features` is replaced by `fn internal_target_features` which computes all enabled Rust target features (including "forbidden" ones -- which are really more like "internal-only" ones so the 2nd commit renames them). We then compute `cfg(target_features)` from that. The session only stores one list, `internal_target_features`, which corresponds to the previous `unstable_target_features`.
To simplify computing `internal_target_features` I also refactored `parse_rust_feature_list` to better distinguish actual Rust target features from unknown target features that we are just grandfathering in. I also made `implied_target_features` not rebuild the same hash map over and over again. And I got rid of a bunch of silly temporary vectors and iterations over all Rust target features.
rustc_abi: Add `LayoutData::is_variant_uninhabited` method
This is a cheaper alternative to `TyAndLayout::for_variant(_, idx).is_uninhabited()`, which avoids the extra work done by `TyAndLayout::for_variant`.
EDIT: Let me expand on the motivation from this [comment](https://github.com/rust-lang/rust/pull/160398#issuecomment-5167761369):
`TyAndLayout::for_variant` is a curious API: the resulting layout doesn't represent a Rust type in the strict sense (not even `pattern_type!(Enum is Variant { .. })`; instead, it only describes the "variant-specific" fields, and fields shared between variants (e.g. the enum tag or coroutine captures) are entirely missing.
As such, I believe alternative APIs should be used instead to clarify intent, when possible. This PR deals with the simplest cases, and a future PR will add `TyAndLayout::variant_field(self, cx, variant_idx, field_idx)` to deal with the next-most common case of only needing a variant layout for field lookups.
Split IncrCompSession out of Session
This will allow introducing a separate incr comp session dir for the post LTO artifacts in the future. In addition it statically encodes the lifetime of the incr comp session rather than requiring an enum behind a mutex stored in the Session.
Based on https://github.com/rust-lang/rust/pull/159000
Part of https://github.com/rust-lang/compiler-team/issues/908
miri: ensure validity of references and pointers we dereference and cast
Conceptually, when we evaluate the place expression `*place`, there are two steps that happen:
- perform a (typed) load from `place`, which yields a value of pointer/ref type
- construct a new place from that value
Since this is a typed load, we have to ensure that the value satisfies the validity invariant. We forgot to do that, which led to Miri missing a bunch of UB. This PR fixes that by adding the missing checks.
Triggering this UB is a bit non-trivial: you cannot just store an invalid value into `place` using regular assignment (that would already be caught as part of the assignment). However, you can take a raw pointer to `place` and then use that to mutate the contents of `place` in a way that its validity invariant no longer holds. For example:
```rust
fn main() {
let mut x = &();
// Overwrite `x` with null.
unsafe { (&raw mut x).cast::<usize>().write(0) };
let _val = *x; //~ERROR: null reference
}
```
This program clearly (IMO) should have UB, and has UB in MiniRust, but Miri accepted that program before this PR. The same applies to references that are invalid because they are unaligned (even if we end up only accessing a 1-aligned field, i.e. the rest of the place expression evaluates just fine), and to references that are invalid because they are not dereferenceable (even if we end up projecting to a zero-sized field, i.e., the rest of the place expression evaluates just fine).
Even raw pointers have this problem: a raw pointer can be invalid if its vtable pointer is wrong, and we did not check that.
And finally, this also affects `Box`, and this is where things get tricky. `Box` derefs are not even present any more in the MIR Miri sees; they have been replaced by derefs of the underlying raw pointer. But that means we have no way to know that we should check all those things. So to fix that I adjusted the ElaborateBoxDerefs to emit a new special kind of cast that's almost a transmute but also checks `Box` validity.
Fixes https://github.com/rust-lang/miri/issues/5226
Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/617
Cc @rust-lang/opsem
This is already *supposed* to be impossible in layout, but this emphasizes that better.
Ironically I was inspired to do this as part of looking at making `Simd<T, 0>` *work*, but importantly if that's going to happen I think it should be `BackendRepr::Memory` like other ZSTs, *not* a `BackendRepr::ScalarVector` that would need to carry around a useless LLVM value in `OperandValue::Immediate` (where it's not even clear what the LLVM type of that value would be).
Support using const pointers in asm `const` operand
Implements [RFC#3848](https://github.com/rust-lang/rfcs/pull/3848) with tracking issue rust-lang/rust#128464
This adds support of const pointers for asm `const` in addition to plain integers.
The inline `asm!` support is implemented using `i` constraint, and the `global_asm!` and `naked_asm!` support is implemented by inserting `symbol + offset` and make `symbol` compiler-used. For unnamed consts, it will create additional internal & hidden symbols so that they can be referenced by global_asm.
~~The feature is also implemented for GCC backend but it's untested.~~ Tested now.
This will allow introducing a separate incr comp session dir for the
post LTO artifacts in the future. In addition it statically encodes the
lifetime of the incr comp session rather than requiring an enum behind a
mutex stored in the Session.
This gives the asm-const code the basic ability to deal wiht pointer and
provenances, which lays the ground work for asm_const_ptr.
Note that `SymStatic` is not fully removed, a specialized is kept and
renamed as `SymThreadLocalStatic`, for `#[thread_local]` statics where CTFE
does not support naming. The `#[thread_local]` is unstable feature and it's
not clear if we want to support this in `sym`, but removal of it should be
a separate PR.
Convert `-Ctarget-cpu` into a target-modifier for AVR, AMDGCN and NVPTX
Crates built for AVR, AMDGCN and NVPTX that specify different values for `-Ctarget-cpu` cannot be soundly linked together.
This PR attempts to make `rustc` ensure that no crates with disagreeing values for `-Ctarget-cpu` are linked together. This is achieved by converting `-Ctarget-cpu` into a target-modifier depending on `--target`.
To do this, the consistency check for `-Ctarget-cpu` considers mismatching values as inconsistent only for targets for which the new flag `requires_consistent_cpu` is set in their target spec.
**Why should `-Ctarget-cpu` be a target-modifier for `nvptx`?**
<details><summary>PTX is a single-module contract</summary>
<p>
PTX requires a binary to start with .version (`ptx$$`) then .target (`sm_$$`). If the ptx contains instructions that are not supported by either .version or .target, the binary is ill-formed and will be rejected by ptxas. The concept of features that can be mixed and matched in a binary does not exist for nvptx and is therefore not supported by LLVM.
</p>
</details>
<details><summary>It prevents the production of bitcode that cannot be codegen'd after linking</summary>
<p>
A target modifier should prevent configurations that are not composable across crates when those crates are linked together. The most prominent example is when enabling a target feature changes the ABI, making cross-crate calls inherently unsound.
In the case of nvptx, ABI mismatch is (at least for now) not the core problem motivating target modifiers. NVIDIA’s documented PTX calling convention has [remained stable since ptx20](https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/index.html#function-calling-sequence).
However, in the current state it is possible to produce bitcode that cannot be codegen'd after linking, because some operations are only lowerable for sufficiently new SM/PTX levels. In the best case this results in an LLVM error during the final llc step, but this is not something we should rely on for correctness.
nvptx has a special compilation pipeline where instead of linking the final PTX object, instead LLVM bitcode is linked. The resulting artifact is then compiled in one invocation.
Now consider crate A which is independently compiled into bitcode with the following rustc arguments:
```Rust
//@ compile-flags: --target nvptx64-nvidia-cuda -C target-cpu=sm_70 --crate-type=rlib
#[cfg(target_feature = "sm_70")]
fn foo() {
// cannot be lowered to ptx before "sm_70: so currently produces an LLVM error
}
#[cfg(not(target_feature = "sm_70"))]
fn foo() {
// can be lowered to ptx before "sm_70"
}
pub fn bar() {
foo()
}
```
Crate A is a dependency of crate B. In the *rustc* invocation of crate B
1. crate B is compiled into bitcode, too
2. both bitcode artifacts are bitcode-linked by *llvm-link*
3. the resulting bitcode artifact is compiled by *llc -mcpu=sm_60*
This should now ideally create an LLVM error, because the linked bitcode contains code paths that were selected under `sm_70` assumptions but the final NVPTX codegen is targeting `sm_60`, where those operations are not lowerable. An LLVM error here is better than silent miscompilation, but it’s not a promise we should rely on.
A real example where this could happen is the lowering of atomic loads and stores with non-relaxed orderings, which is known to depend on the selected SM level.
</p>
</details>
**Why should `-Ctarget-cpu` be a target-modifier for `amdgcn` and `avr`?**
- In case of AVR the target-cpu defines the ISA, which is encoded in the ELF header flags, amdgcn also encodes the cpu directly into those flags
- To not rely on *lld* which currently prevents it for both by looking at those flags [AVR](597ffbe09d/lld/test/ELF/avr-flags.s) and [amdgcn](597ffbe09d/lld/test/ELF/amdgpu-elf-flags-err.s)
Previous discussions about the topic can be found [here](https://github.com/rust-lang/rust/issues/131799#issuecomment-3390563329) and [here](https://github.com/rust-lang/rust/issues/141468).
I also created a [Zulip discussion](https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/Making.20-Ctarget-cpu.20a.20target-modifier.20on.20NVPTX/with/566622679).
I am unsure if a MCP is needed before proceeding. If you think so please let me know.
Creating *target-modifiers* for NVPTX *target-features* is to be done in a follow-up.
cc @kjetilkjeka as target maintainer for NVPTX
cc @flakebi as target maintainer for amdgcn
cc @Patryk27 as target maintainer for AVR
cc @RalfJung you were very involved in the discussions so far
Target modifier tracking issue: https://github.com/rust-lang/rust/issues/136966
For AVR, AMDGCN, and NVPTX, crates built with different target CPU values are
not generally link-compatible.
Add a `requires_consistent_cpu` flag to the target spec and enable it for these
targets. When the flag is set, treat `-Ctarget-cpu` as a target modifier and
require all linked crates to agree on its value.
Reject `-Ctarget-cpu=native` before codegen for targets that set
`requires_consistent_cpu` to true. Also do not include `native` in the printed
`target-cpus` list for such targets.
Add tests covering:
- which built-in targets set `requires-consistent-cpu`
- cross-crate behavior with and without `requires-consistent-cpu`
- that an omitted `-Ctarget-cpu` compares equal to an explicitly specified
default CPU
- rejection and printing behavior for `native`
- precedence of repeated `-Ctarget-cpu` flags in metadata comparison and LLVM IR
Introduce InstanceKind::LlvmIntrinsic
This way codegen backends don't have to check for a magic symbol name prefix to detect LLVM intrinsic calls and thus can more easily handle them separately as necessary.
This way codegen backends don't have to check for a magic symbol name
prefix to detect LLVM intrinsic calls and thus can more easily handle
them separately as necessary.
Introduce a dedicated panic for null reference production to distinguish
producing a reference from a null pointer from an actual null pointer
dereference.
This emits a dedicated panic message for null reference production while
preserving the existing panic for actual dereferences.
Rename `align` to `default_align` on `Scalar` and `Primitive`
To emphasize that just because you see a `Scalar(I32)` that doesn't really tell you anything about the alignment it has -- one should be looking at the type (well, the place) for that.
(The `size` method doesn't really have that problem -- i32 is always 4 bytes, no matter the context -- so is left untouched.)
No actual layout or behaviour changes in *this* PR. Just the rename and some comments.
r? @workingjubilee
To emphasize that just because you see a `Scalar(I32)` that doesn't really tell you anything about the alignment it has -- one should be looking at the type (well, the place) for that.
No actual layout or behaviour changes in *this* PR.
They tend to have similar handling -- e.g., they should be the only
input to the `mir_shims` query -- so it's cleaner to group them
together. This will also make potential future refactorings easier, such
as only carrying `GenericArgsRef` for instances that actually use it
(e.g., `Item`) but not others (e.g., `CloneShim`).
Many of the shim variants still have `Shim` at the end of their names.
To make the refactoring easier and keep the diff clean, I will trim
those suffixes off in the next commit.
This is an UnordMap internally. Iteration order for the work product map
should not matter aside from the place it is serialized where sorting by
WorkProductId is sufficient.
add `extern "tail"` calling convention
Maps to LLVM's `tailcc` and hence inherits all its problems.
This calling convention at least compiles on:
- `x86_64`
- `aarch64`
It also compiles on
- `s390x`
- `loongarch64`
But I've been told by target maintainers that this is kind of unintentional, and it's not tested in LLVM.
For most backends LLVM does not have support and fails loudly.
Use a `ArrayVec` in `CastTarget`
This commit switches a fixed-size list of `[Option<Reg>; 8]` to instead
holding `ArrayVec<Reg, 8>` in the `CastTarget` type used when
calculating ABIs. This is inspired by [discussion on Zulip][link] where
I'm hoping to in the near future extend the usage of this to possibly
beyond 8 elements for a new WebAssembly ABI taking advantage of
multi-value. For now though this mostly just switches to
array/slice-like idioms of accessors rather than dealing with
`Option<Reg>` as the unit.
[link]: https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/Using.20.60ArgAbi.3A.3Amake_direct_deprecated.60/with/598607139
This commit switches a fixed-size list of `[Option<Reg>; 8]` to instead
holding `ArrayVec<Reg, 8>` in the `CastTarget` type used when
calculating ABIs. This is inspired by [discussion on Zulip][link] where
I'm hoping to in the near future extend the usage of this to possibly
beyond 8 elements for a new WebAssembly ABI taking advantage of
multi-value. For now though this mostly just switches to
array/slice-like idioms of accessors rather than dealing with
`Option<Reg>` as the unit.
[link]: https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/Using.20.60ArgAbi.3A.3Amake_direct_deprecated.60/with/598607139
compiler: `ops::RangeInclusive` → `range::RangeInclusive`
The type's been stable for over 6 weeks now, so let's use it! It's better for cases like this one where it's stored in a data structure.
Probably won't be materially faster, but does make the variant slightly smaller and lets some more things be `Copy`. And deletes a whole bunch of parens from things being fields instead of methods 😄
r? compiler
Allow two object files for a single CGU in CompiledModule
cg_clif needs this as it passes inline assembly to an external assembler, producing a separate object file. Currently it emits multiple CompiledModules, but this is not compatible with using the codegen coordinator of cg_ssa.
The type's been stable for over 6 weeks now, so let's use it! It's better for cases like this one where it's stored in a data structure.
Probably won't be materially faster, but does make the variant slightly smaller and lets some more things be `Copy`.
Stop needing an alloca for `catch_unwind`
Turns out these were all making `OperandValue::Immediate`s already -- the intrinsic always returns a primitive scalar -- so pretty easy to handle.
cc https://github.com/rust-lang/rust/issues/153250https://github.com/rust-lang/compiler-team/issues/970
While I was looking at it, I also "rustified" the intrinsic signature a bit: returning a `bool` and taking a generic pointee and `unsafe fn`s cleans up the call in `std` a bit without making the implementation in the backend any harder.
r? dianqk
Turns out these were all making `OperandValue::Immediate`s already -- the intrinsic always returns a primitive scalar -- so pretty easy to handle.
While I was looking at it, I also "rustified" the intrinsic signature a bit: returning a `bool` and taking a generic pointee and `unsafe fn`s cleans up the call in `std` a bit without making the implementation in the backend any harder.
cg_clif needs this as it passes inline assembly to an external assembler,
producing a separate object file. Currently it emits multiple
CompiledModules, but this is not compatible with using the codegen
coordinator of cg_ssa.
Adds an unstable `extern "Swift"` ABI behind the `abi_swift` feature
gate, mapping to LLVM's `swiftcc` calling convention. Cranelift and
GCC backends fall back to the platform default since they have no
equivalent.