Commit Graph

1212 Commits

Author SHA1 Message Date
mejrs
196dd2a174 Fix up lang_items import paths 2026-08-09 15:20:29 +02:00
Jonathan Brouwer
6a3b9acf14 Rollup merge of #160530 - RalfJung:internal-target-features, r=nnethercote
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.
2026-08-08 00:38:22 +02:00
Ralf Jung
8bb9f279a9 refactor handling of target features in Session 2026-08-06 14:45:53 +02:00
Jonathan Brouwer
592096bca8 Rollup merge of #160398 - moulins:layout-is-variant-uninhabited, r=oli-obk
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.
2026-08-06 12:41:07 +02:00
Moulins
fee8922aa3 rustc_abi: Add LayoutData::is_variant_uninhabited method
This is a cheaper alternative to `TyAndLayout::for_variant(_, idx).is_uninhabited()`
2026-08-05 15:38:43 +02:00
Jonathan Brouwer
900f0bcb32 Rollup merge of #159225 - bjorn3:split_incr_comp_session, r=oli-obk
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
2026-08-05 13:36:11 +02:00
Folkert de Vries
6ac1fe6c84 fix f128 libcall abi in the cranelift backend 2026-08-04 10:22:35 -04:00
Jonathan Brouwer
9956011498 Rollup merge of #160012 - RalfJung:deref-validity, r=oli-obk
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
2026-08-01 15:56:37 +02:00
Ralf Jung
fcf68f21cf introduce a new CastKind for ElaborateBoxDerefs 2026-08-01 09:27:16 +02:00
Scott McMurray
6da3077db9 Structurally prevent zero-count BackendRepr::SimdVectors
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).
2026-07-30 19:48:24 -07:00
Jacob Pratt
0e238fd6c3 Rollup merge of #138618 - nbdd0121:asm_const_ptr, r=bjorn3
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.
2026-07-26 00:21:39 -04:00
Daniel Paoliello
fe37a8afad Update bootstrap to use -Zembed-metadata=no instead of -Zno-embed-metadata
The recent Cargo submodule update picked up <https://github.com/rust-lang/cargo/pull/17149>

However, bootstrap was still using the old name, resulting in:

```
Building stage1 library artifacts (stage1 -> stage1, arm64ec-pc-windows-msvc)
error: unknown `-Z` flag specified: no-embed-metadata
```

Fix is to switch to the rename.

I also removed the diff in the Cranelift setup script, since they must have already hit this issue and no longer need the workaround.
2026-07-23 11:09:16 -07:00
bjorn3
f9679fa4df 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.
2026-07-23 12:14:56 +02:00
Gary Guo
338d560eaf Handle pointers with offset for asm const 2026-07-22 13:47:31 +01:00
Gary Guo
ca4033987e Unify handling of asm const and sym using CTFE
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.
2026-07-22 13:47:31 +01:00
Gary Guo
b44bea2b5d Delay stringification of const to backend 2026-07-22 13:47:31 +01:00
bjorn3
39c2db0934 Merge commit 'cb89537d435ec9cc9c812cd47c6130bd96aa0050' into sync_cg_clif-2026-07-22 2026-07-22 13:06:34 +02:00
Jonathan Brouwer
8e9fb78173 Rollup merge of #150732 - kulst:cpu_is_target_modifier, r=bjorn3
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
2026-07-19 23:26:25 +02:00
kulst
76d5107658 Treat -Ctarget-cpu as a target-modifier when targeting AVR, AMDGCN and NVPTX
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
2026-07-17 15:46:00 +02:00
Guillaume Gomez
db1695d47e Update uses of rustc_codegen_ssa::errors 2026-07-15 17:23:13 +02:00
Jonathan Brouwer
09e4f79388 Rollup merge of #159183 - bjorn3:instance_llvm_intrinsic, r=RalfJung,folkertdev
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.
2026-07-14 16:49:04 +02:00
bjorn3
8c2ed2f9a1 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.
2026-07-13 14:20:37 +00:00
addie.sh
8fb83aba33 place FnDef behind a binder, instantiate w/ Dummy 2026-07-10 14:53:35 -04:00
Scott McMurray
2efdc665a7 Carry the b_offset inside BackendRepr::ScalarPair 2026-07-07 01:15:36 -07:00
Raushan kumar
1a982425b6 Distinguish null reference production from null pointer dereference
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.
2026-07-05 17:09:30 +00:00
Jacob Pratt
9272c6d92a Rollup merge of #158542 - scottmcm:scalar-but-packed, r=workingjubilee
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
2026-07-01 01:03:18 -04:00
Scott McMurray
f98365f1f3 Rename align to platform_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.

No actual layout or behaviour changes in *this* PR.
2026-06-29 09:48:16 -07:00
Jacob Pratt
6bc6675972 Rollup merge of #158497 - folkertdev:stdarch-sync-2026-06-27, r=folkertdev
stdarch subtree update

Subtree update of `stdarch` to 62d559568a.

Created using https://github.com/rust-lang/josh-sync.

r? @ghost
2026-06-27 22:13:44 -04:00
Folkert de Vries
3515461784 use "llvm.prefetch.p0" instead of "llvm.prefetch"
LLVM updated the name, the old one still works but stdarch is now using the new one
2026-06-27 23:14:21 +02:00
teor
9e48cd9e1f Impl MIR lowering side-tables for #[splat] 2026-06-26 10:44:14 +02:00
Adwin White
3dbe96a5a1 add IsRigid marker to TyKind::Alias and constants 2026-06-25 17:12:10 +08:00
Noah Lev
c329a0e6c9 Strip vestigial Shim suffix from ShimKind variants 2026-06-22 19:29:17 +00:00
Noah Lev
0eb146cbab Extract all instance shim variants into new ShimKind enum
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.
2026-06-22 19:28:42 +00:00
Folkert de Vries
d297af408d remove LLVM va_end calls
The operation is a no-op, so we skip it.
2026-06-15 19:52:50 +02:00
bjorn3
9419baeee8 Use WorkProductMap instead of FxIndexMap
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.
2026-06-07 13:24:12 +00:00
Jacob Pratt
d66ac2434a Rollup merge of #157016 - folkertdev:add-tailcc-abi, r=WaffleLapkin
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.
2026-06-07 00:37:48 -04:00
bjorn3
eb31c84a0a Merge commit 'f2ef4150da1c50e5b04607cdab771530cac4ffe4' into sync_cg_clif-2026-06-06 2026-06-06 16:27:31 +02:00
Folkert de Vries
4e59f4c54b add extern "tail" calling convention 2026-06-05 20:19:51 +02:00
Jonathan Brouwer
99bb120cf8 Rollup merge of #157130 - alexcrichton:refactor-cast-target-internals, r=nnethercote
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
2026-06-02 13:20:49 +02:00
Alex Crichton
c668b83eed 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
2026-06-01 07:34:12 -07:00
Camille Gillot
a27155e691 Remove async_fut.
This is now unused.
2026-05-31 16:02:15 +00:00
Jonathan Brouwer
cf39dc63f4 Rollup merge of #157139 - scottmcm:abi-range-inclusive, r=oli-obk
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
2026-05-30 11:40:21 +02:00
Jonathan Brouwer
b8c03eeded Rollup merge of #157051 - bjorn3:lto_refactors20, r=saethlin
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.
2026-05-30 11:40:16 +02:00
Scott McMurray
f7cf361f3c 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`.
2026-05-29 21:57:45 -07:00
Jonathan Brouwer
0f27774436 Rollup merge of #156867 - scottmcm:WIP-no-alloca-for-catch-unwind, r=dianqk
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/153250 https://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
2026-05-29 09:06:19 +02:00
Scott McMurray
6aa9c0325e 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.

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.
2026-05-28 19:53:59 -07:00
bjorn3
e731b4e5f9 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.
2026-05-28 09:20:02 +00:00
Ralf Jung
59428e76e8 MIR inlining: allow backends to opt-in to inlining intrinsics 2026-05-27 13:59:25 +02:00
Dirkjan Ochtman
f49e45101c Add Swift function call ABI
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.
2026-05-12 17:09:19 +02:00
Jonathan Brouwer
8cfae220da Rollup merge of #156393 - RalfJung:core-miri-tests, r=tgross35
enable more f16/f128 tests in Miri

See the individual commit messages for details.

The last commit is a drive-by comment fix that was not worth its own PR.
r? @tgross35
2026-05-12 07:03:55 +02:00