Skip to content
/ rust Public
forked from rust-lang/rust

Commit

Permalink
Rollup merge of rust-lang#134090 - veluca93:stable-tf11, r=oli-obk
Browse files Browse the repository at this point in the history
Stabilize target_feature_11

# Stabilization report

This is an updated version of rust-lang#116114, which is itself a redo of rust-lang#99767. Most of this commit and report were copied from those PRs. Thanks ``@LeSeulArtichaut`` and ``@calebzulawski!``

## Summary
Allows for safe functions to be marked with `#[target_feature]` attributes.

Functions marked with `#[target_feature]` are generally considered as unsafe functions: they are unsafe to call, cannot *generally* be assigned to safe function pointers, and don't implement the `Fn*` traits.

However, calling them from other `#[target_feature]` functions with a superset of features is safe.

```rust
// Demonstration function
#[target_feature(enable = "avx2")]
fn avx2() {}

fn foo() {
    // Calling `avx2` here is unsafe, as we must ensure
    // that AVX is available first.
    unsafe {
        avx2();
    }
}

#[target_feature(enable = "avx2")]
fn bar() {
    // Calling `avx2` here is safe.
    avx2();
}
```

Moreover, once rust-lang#135504 is merged, they can be converted to safe function pointers in a context in which calling them is safe:

```rust
// Demonstration function
#[target_feature(enable = "avx2")]
fn avx2() {}

fn foo() -> fn() {
    // Converting `avx2` to fn() is a compilation error here.
    avx2
}

#[target_feature(enable = "avx2")]
fn bar() -> fn() {
    // `avx2` coerces to fn() here
    avx2
}
```

See the section "Closures" below for justification of this behaviour.

## Test cases
Tests for this feature can be found in [`tests/ui/target_feature/`](https://github.com/rust-lang/rust/tree/f6cb952dc115fd1311b02b694933e31d8dc8b002/tests/ui/target-feature).

## Edge cases
### Closures
 * [target-feature 1.1: should closures inherit target-feature annotations? rust-lang#73631](rust-lang#73631)

Closures defined inside functions marked with #[target_feature] inherit the target features of their parent function. They can still be assigned to safe function pointers and implement the appropriate `Fn*` traits.

```rust
#[target_feature(enable = "avx2")]
fn qux() {
    let my_closure = || avx2(); // this call to `avx2` is safe
    let f: fn() = my_closure;
}
```
This means that in order to call a function with #[target_feature], you must guarantee that the target-feature is available while the function, any closures defined inside it, as well as any safe function pointers obtained from target-feature functions inside it, execute.

This is usually ensured because target features are assumed to never disappear, and:
- on any unsafe call to a `#[target_feature]` function, presence of the target feature is guaranteed by the programmer through the safety requirements of the unsafe call.
- on any safe call, this is guaranteed recursively by the caller.

If you work in an environment where target features can be disabled, it is your responsibility to ensure that no code inside a target feature function (including inside a closure) runs after this (until the feature is enabled again).

**Note:** this has an effect on existing code, as nowadays closures do not inherit features from the enclosing function, and thus this strengthens a safety requirement. It was originally proposed in rust-lang#73631 to solve this by adding a new type of UB: “taking a target feature away from your process after having run code that uses that target feature is UB” .
This was motivated by userspace code already assuming in a few places that CPU features never disappear from a program during execution (see i.e. https://github.com/rust-lang/stdarch/blob/2e29bdf90832931ea499755bb4ad7a6b0809295a/crates/std_detect/src/detect/arch/x86.rs); however, concerns were raised in the context of the Linux kernel; thus, we propose to relax that requirement to "causing the set of usable features to be reduced is unsafe; when doing so, the programmer is required to ensure that no closures or safe fn pointers that use removed features are still in scope".

* [Fix #[inline(always)] on closures with target feature 1.1 rust-lang#111836](rust-lang#111836)

Closures accept `#[inline(always)]`, even within functions marked with `#[target_feature]`. Since these attributes conflict, `#[inline(always)]` wins out to maintain compatibility.

### ABI concerns
* [The extern "C" ABI of SIMD vector types depends on target features rust-lang#116558](rust-lang#116558)

The ABI of some types can change when compiling a function with different target features. This could have introduced unsoundness with target_feature_11, but recent fixes (rust-lang#133102, rust-lang#132173) either make those situations invalid or make the ABI no longer dependent on features. Thus, those issues should no longer occur.

### Special functions
The `#[target_feature]` attribute is forbidden from a variety of special functions, such as main, current and future lang items (e.g. `#[start]`, `#[panic_handler]`), safe default trait implementations and safe trait methods.

This was not disallowed at the time of the first stabilization PR for target_features_11, and resulted in the following issues/PRs:
* [`#[target_feature]` is allowed on `main` rust-lang#108645](rust-lang#108645)
* [`#[target_feature]` is allowed on default implementations rust-lang#108646](rust-lang#108646)
* [#[target_feature] is allowed on #[panic_handler] with target_feature 1.1 rust-lang#109411](rust-lang#109411)
* [Prevent using `#[target_feature]` on lang item functions rust-lang#115910](rust-lang#115910)

## Documentation
 * Reference: [Document the `target_feature_11` feature reference#1181](rust-lang/reference#1181)
---

cc tracking issue rust-lang#69098
cc ``@workingjubilee``
cc ``@RalfJung``
r? ``@rust-lang/lang``
  • Loading branch information
jhpratt authored Feb 13, 2025
2 parents ef148cd + 44b2e6c commit 1307fe0
Show file tree
Hide file tree
Showing 34 changed files with 77 additions and 165 deletions.
27 changes: 8 additions & 19 deletions compiler/rustc_codegen_ssa/src/codegen_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,10 +272,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
if safe_target_features {
if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
// The `#[target_feature]` attribute is allowed on
// WebAssembly targets on all functions, including safe
// ones. Other targets require that `#[target_feature]` is
// only applied to unsafe functions (pending the
// `target_feature_11` feature) because on most targets
// WebAssembly targets on all functions. Prior to stabilizing
// the `target_feature_11` feature, `#[target_feature]` was
// only permitted on unsafe functions because on most targets
// execution of instructions that are not supported is
// considered undefined behavior. For WebAssembly which is a
// 100% safe target at execution time it's not possible to
Expand All @@ -289,17 +288,10 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
// if a target is documenting some wasm-specific code then
// it's not spuriously denied.
//
// This exception needs to be kept in sync with allowing
// `#[target_feature]` on `main` and `start`.
} else if !tcx.features().target_feature_11() {
feature_err(
&tcx.sess,
sym::target_feature_11,
attr.span,
"`#[target_feature(..)]` can only be applied to `unsafe` functions",
)
.with_span_label(tcx.def_span(did), "not an `unsafe` function")
.emit();
// Now that `#[target_feature]` is permitted on safe functions,
// this exception must still exist for allowing the attribute on
// `main`, `start`, and other functions that are not usually
// allowed.
} else {
check_target_feature_trait_unsafe(tcx, did, attr.span);
}
Expand Down Expand Up @@ -628,10 +620,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
// its parent function, which effectively inherits the features anyway. Boxing this closure
// would result in this closure being compiled without the inherited target features, but this
// is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
if tcx.features().target_feature_11()
&& tcx.is_closure_like(did.to_def_id())
&& !codegen_fn_attrs.inline.always()
{
if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
let owner_id = tcx.parent(did.to_def_id());
if tcx.def_kind(owner_id).has_codegen_attrs() {
codegen_fn_attrs
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_feature/src/accepted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,8 @@ declare_features! (
(accepted, struct_variant, "1.0.0", None),
/// Allows `#[target_feature(...)]`.
(accepted, target_feature, "1.27.0", None),
/// Allows the use of `#[target_feature]` on safe functions.
(accepted, target_feature_11, "CURRENT_RUSTC_VERSION", Some(69098)),
/// Allows `fn main()` with return types which implements `Termination` (RFC 1937).
(accepted, termination_trait, "1.26.0", Some(43301)),
/// Allows `#[test]` functions where the return type implements `Termination` (RFC 1937).
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_feature/src/unstable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -633,8 +633,6 @@ declare_features! (
(unstable, strict_provenance_lints, "1.61.0", Some(130351)),
/// Allows string patterns to dereference values to match them.
(unstable, string_deref_patterns, "1.67.0", Some(87121)),
/// Allows the use of `#[target_feature]` on safe functions.
(unstable, target_feature_11, "1.45.0", Some(69098)),
/// Allows using `#[thread_local]` on `static` items.
(unstable, thread_local, "1.0.0", Some(29594)),
/// Allows defining `trait X = A + B;` alias items.
Expand Down
1 change: 0 additions & 1 deletion library/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,6 @@
#![feature(staged_api)]
#![feature(stmt_expr_attributes)]
#![feature(strict_provenance_lints)]
#![feature(target_feature_11)]
#![feature(trait_alias)]
#![feature(transparent_unions)]
#![feature(try_blocks)]
Expand Down
1 change: 0 additions & 1 deletion tests/assembly/closure-inherit-target-feature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
// make sure the feature is not enabled at compile-time
//@ compile-flags: -C opt-level=3 -C target-feature=-sse4.1 -C llvm-args=-x86-asm-syntax=intel

#![feature(target_feature_11)]
#![crate_type = "rlib"]

use std::arch::x86_64::{__m128, _mm_blend_ps};
Expand Down
1 change: 0 additions & 1 deletion tests/codegen/target-feature-inline-closure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
//@ compile-flags: -Copt-level=3 -Ctarget-cpu=x86-64

#![crate_type = "lib"]
#![feature(target_feature_11)]

#[cfg(target_arch = "x86_64")]
use std::arch::x86_64::*;
Expand Down
1 change: 0 additions & 1 deletion tests/mir-opt/inline/inline_compatibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

#![crate_type = "lib"]
#![feature(no_sanitize)]
#![feature(target_feature_11)]
#![feature(c_variadic)]

#[inline]
Expand Down
2 changes: 0 additions & 2 deletions tests/ui/asm/x86_64/issue-89875.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
//@ needs-asm-support
//@ only-x86_64

#![feature(target_feature_11)]

use std::arch::asm;

#[target_feature(enable = "avx")]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
//@ edition: 2021
//@ only-x86_64

#![feature(target_feature_11)]
// `target_feature_11` just to test safe functions w/ target features.

use std::pin::Pin;
use std::future::Future;
use std::pin::Pin;

#[target_feature(enable = "sse2")]
fn target_feature() -> Pin<Box<dyn Future<Output = ()> + 'static>> { todo!() }
fn target_feature() -> Pin<Box<dyn Future<Output = ()> + 'static>> {
todo!()
}

fn test(f: impl AsyncFn()) {}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error[E0277]: the trait bound `#[target_features] fn() -> Pin<Box<(dyn Future<Output = ()> + 'static)>> {target_feature}: AsyncFn()` is not satisfied
--> $DIR/fn-exception-target-features.rs:16:10
--> $DIR/fn-exception-target-features.rs:15:10
|
LL | test(target_feature);
| ---- ^^^^^^^^^^^^^^ unsatisfied trait bound
Expand All @@ -8,7 +8,7 @@ LL | test(target_feature);
|
= help: the trait `AsyncFn()` is not implemented for fn item `#[target_features] fn() -> Pin<Box<(dyn Future<Output = ()> + 'static)>> {target_feature}`
note: required by a bound in `test`
--> $DIR/fn-exception-target-features.rs:13:17
--> $DIR/fn-exception-target-features.rs:12:17
|
LL | fn test(f: impl AsyncFn()) {}
| ^^^^^^^^^ required by this bound in `test`
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/lang-items/start_lang_item_with_target_feature.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//@ only-x86_64
//@ check-fail

#![feature(lang_items, no_core, target_feature_11)]
#![feature(lang_items, no_core)]
#![no_core]

#[lang = "copy"]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//@ compile-flags:-C panic=abort
//@ only-x86_64

#![feature(target_feature_11)]
#![no_std]
#![no_main]

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: `#[panic_handler]` function is not allowed to have `#[target_feature]`
--> $DIR/panic-handler-with-target-feature.rs:11:1
--> $DIR/panic-handler-with-target-feature.rs:10:1
|
LL | #[target_feature(enable = "avx2")]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Expand Down
2 changes: 0 additions & 2 deletions tests/ui/rfcs/rfc-2396-target_feature-11/check-pass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
//@ check-pass
//@ only-x86_64

#![feature(target_feature_11)]

#[target_feature(enable = "sse2")]
const fn sse2() {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
//@ check-pass
//@ only-x86_64

#![feature(target_feature_11)]

#[target_feature(enable = "avx")]
fn also_use_avx() {
println!("Hello from AVX")
Expand Down

This file was deleted.

This file was deleted.

2 changes: 0 additions & 2 deletions tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//@ only-x86_64

#![feature(target_feature_11)]

#[target_feature(enable = "avx")]
fn foo_avx() {}

Expand Down
4 changes: 2 additions & 2 deletions tests/ui/rfcs/rfc-2396-target_feature-11/fn-ptr.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error[E0308]: mismatched types
--> $DIR/fn-ptr.rs:14:21
--> $DIR/fn-ptr.rs:12:21
|
LL | #[target_feature(enable = "avx")]
| --------------------------------- `#[target_feature]` added here
Expand All @@ -14,7 +14,7 @@ LL | let foo: fn() = foo_avx;
= note: functions with `#[target_feature]` can only be coerced to `unsafe` function pointers

error[E0308]: mismatched types
--> $DIR/fn-ptr.rs:23:21
--> $DIR/fn-ptr.rs:21:21
|
LL | #[target_feature(enable = "sse2")]
| ---------------------------------- `#[target_feature]` added here
Expand Down
2 changes: 0 additions & 2 deletions tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//@ only-x86_64

#![feature(target_feature_11)]

#[target_feature(enable = "avx")]
fn foo() {}

Expand Down
28 changes: 14 additions & 14 deletions tests/ui/rfcs/rfc-2396-target_feature-11/fn-traits.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error[E0277]: expected a `Fn()` closure, found `#[target_features] fn() {foo}`
--> $DIR/fn-traits.rs:31:10
--> $DIR/fn-traits.rs:29:10
|
LL | call(foo);
| ---- ^^^ expected an `Fn()` closure, found `#[target_features] fn() {foo}`
Expand All @@ -11,13 +11,13 @@ LL | call(foo);
= note: `#[target_feature]` functions do not implement the `Fn` traits
= note: try casting the function to a `fn` pointer or wrapping it in a closure
note: required by a bound in `call`
--> $DIR/fn-traits.rs:14:17
--> $DIR/fn-traits.rs:12:17
|
LL | fn call(f: impl Fn()) {
| ^^^^ required by this bound in `call`

error[E0277]: expected a `FnMut()` closure, found `#[target_features] fn() {foo}`
--> $DIR/fn-traits.rs:32:14
--> $DIR/fn-traits.rs:30:14
|
LL | call_mut(foo);
| -------- ^^^ expected an `FnMut()` closure, found `#[target_features] fn() {foo}`
Expand All @@ -29,13 +29,13 @@ LL | call_mut(foo);
= note: `#[target_feature]` functions do not implement the `Fn` traits
= note: try casting the function to a `fn` pointer or wrapping it in a closure
note: required by a bound in `call_mut`
--> $DIR/fn-traits.rs:18:25
--> $DIR/fn-traits.rs:16:25
|
LL | fn call_mut(mut f: impl FnMut()) {
| ^^^^^^^ required by this bound in `call_mut`

error[E0277]: expected a `FnOnce()` closure, found `#[target_features] fn() {foo}`
--> $DIR/fn-traits.rs:33:15
--> $DIR/fn-traits.rs:31:15
|
LL | call_once(foo);
| --------- ^^^ expected an `FnOnce()` closure, found `#[target_features] fn() {foo}`
Expand All @@ -47,13 +47,13 @@ LL | call_once(foo);
= note: `#[target_feature]` functions do not implement the `Fn` traits
= note: try casting the function to a `fn` pointer or wrapping it in a closure
note: required by a bound in `call_once`
--> $DIR/fn-traits.rs:22:22
--> $DIR/fn-traits.rs:20:22
|
LL | fn call_once(f: impl FnOnce()) {
| ^^^^^^^^ required by this bound in `call_once`

error[E0277]: expected a `FnOnce(i32)` closure, found `#[target_features] fn(i32) {bar}`
--> $DIR/fn-traits.rs:34:19
--> $DIR/fn-traits.rs:32:19
|
LL | call_once_i32(bar);
| ------------- ^^^ expected an `FnOnce(i32)` closure, found `#[target_features] fn(i32) {bar}`
Expand All @@ -64,13 +64,13 @@ LL | call_once_i32(bar);
= note: `#[target_feature]` functions do not implement the `Fn` traits
= note: try casting the function to a `fn` pointer or wrapping it in a closure
note: required by a bound in `call_once_i32`
--> $DIR/fn-traits.rs:26:26
--> $DIR/fn-traits.rs:24:26
|
LL | fn call_once_i32(f: impl FnOnce(i32)) {
| ^^^^^^^^^^^ required by this bound in `call_once_i32`

error[E0277]: expected a `Fn()` closure, found `unsafe fn() {foo_unsafe}`
--> $DIR/fn-traits.rs:36:10
--> $DIR/fn-traits.rs:34:10
|
LL | call(foo_unsafe);
| ---- ^^^^^^^^^^ call the function in a closure: `|| unsafe { /* code */ }`
Expand All @@ -83,13 +83,13 @@ LL | call(foo_unsafe);
= note: `#[target_feature]` functions do not implement the `Fn` traits
= note: try casting the function to a `fn` pointer or wrapping it in a closure
note: required by a bound in `call`
--> $DIR/fn-traits.rs:14:17
--> $DIR/fn-traits.rs:12:17
|
LL | fn call(f: impl Fn()) {
| ^^^^ required by this bound in `call`

error[E0277]: expected a `FnMut()` closure, found `unsafe fn() {foo_unsafe}`
--> $DIR/fn-traits.rs:38:14
--> $DIR/fn-traits.rs:36:14
|
LL | call_mut(foo_unsafe);
| -------- ^^^^^^^^^^ call the function in a closure: `|| unsafe { /* code */ }`
Expand All @@ -102,13 +102,13 @@ LL | call_mut(foo_unsafe);
= note: `#[target_feature]` functions do not implement the `Fn` traits
= note: try casting the function to a `fn` pointer or wrapping it in a closure
note: required by a bound in `call_mut`
--> $DIR/fn-traits.rs:18:25
--> $DIR/fn-traits.rs:16:25
|
LL | fn call_mut(mut f: impl FnMut()) {
| ^^^^^^^ required by this bound in `call_mut`

error[E0277]: expected a `FnOnce()` closure, found `unsafe fn() {foo_unsafe}`
--> $DIR/fn-traits.rs:40:15
--> $DIR/fn-traits.rs:38:15
|
LL | call_once(foo_unsafe);
| --------- ^^^^^^^^^^ call the function in a closure: `|| unsafe { /* code */ }`
Expand All @@ -121,7 +121,7 @@ LL | call_once(foo_unsafe);
= note: `#[target_feature]` functions do not implement the `Fn` traits
= note: try casting the function to a `fn` pointer or wrapping it in a closure
note: required by a bound in `call_once`
--> $DIR/fn-traits.rs:22:22
--> $DIR/fn-traits.rs:20:22
|
LL | fn call_once(f: impl FnOnce()) {
| ^^^^^^^^ required by this bound in `call_once`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//@ only-x86_64

#![feature(target_feature_11)]

#[target_feature(enable = "avx2")]
fn main() {}
//~^ ERROR `main` function is not allowed to have `#[target_feature]`
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: `main` function is not allowed to have `#[target_feature]`
--> $DIR/issue-108645-target-feature-on-main.rs:6:1
--> $DIR/issue-108645-target-feature-on-main.rs:4:1
|
LL | fn main() {}
| ^^^^^^^^^ `main` function is not allowed to have `#[target_feature]`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
//@ check-pass
//@ only-x86_64

#![feature(target_feature_11)]

#[target_feature(enable = "avx")]
pub unsafe fn test() {
({
Expand Down
2 changes: 0 additions & 2 deletions tests/ui/rfcs/rfc-2396-target_feature-11/issue-99876.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//@ check-pass

#![feature(target_feature_11)]

struct S<T>(T)
where
[T; (|| {}, 1).1]: Copy;
Expand Down
2 changes: 0 additions & 2 deletions tests/ui/rfcs/rfc-2396-target_feature-11/return-fn-ptr.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
//@ only-x86_64
//@ run-pass

#![feature(target_feature_11)]

#[target_feature(enable = "sse2")]
fn foo() -> bool {
true
Expand Down
Loading

0 comments on commit 1307fe0

Please sign in to comment.