Skip to content

retpoline and retpoline-external-thunk flags (target modifiers) to enable retpoline-related target features #135927

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion compiler/rustc_codegen_gcc/src/gcc_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use rustc_codegen_ssa::errors::TargetFeatureDisableOrEnable;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::unord::UnordSet;
use rustc_session::Session;
use rustc_session::features::StabilityExt;
use rustc_target::target_features::RUSTC_SPECIFIC_FEATURES;
use smallvec::{SmallVec, smallvec};

Expand Down Expand Up @@ -94,7 +95,7 @@ pub(crate) fn global_gcc_features(sess: &Session, diagnostics: bool) -> Vec<Stri
sess.dcx().emit_warn(unknown_feature);
}
Some(&(_, stability, _)) => {
if let Err(reason) = stability.toggle_allowed() {
if let Err(reason) = stability.is_toggle_permitted(sess) {
sess.dcx().emit_warn(ForbiddenCTargetFeature {
feature,
enabled: if enable { "enabled" } else { "disabled" },
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_codegen_llvm/src/llvm_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use rustc_fs_util::path_to_c_string;
use rustc_middle::bug;
use rustc_session::Session;
use rustc_session::config::{PrintKind, PrintRequest};
use rustc_session::features::StabilityExt;
use rustc_span::Symbol;
use rustc_target::spec::{MergeFunctions, PanicStrategy, SmallDataThresholdSupport};
use rustc_target::target_features::{RUSTC_SPECIAL_FEATURES, RUSTC_SPECIFIC_FEATURES};
Expand Down Expand Up @@ -832,7 +833,7 @@ pub(crate) fn global_llvm_features(
sess.dcx().emit_warn(unknown_feature);
}
Some((_, stability, _)) => {
if let Err(reason) = stability.toggle_allowed() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a bunch of duplication in the code around this between codegen backends and rustc_codegen_ssa, it's pre-existing, you could sort it if you wanted, but someone ought to.

if let Err(reason) = stability.is_toggle_permitted(sess) {
sess.dcx().emit_warn(ForbiddenCTargetFeature {
feature,
enabled: if enable { "enabled" } else { "disabled" },
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_codegen_ssa/src/target_features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
use rustc_middle::middle::codegen_fn_attrs::TargetFeature;
use rustc_middle::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_session::features::StabilityExt;
use rustc_session::parse::feature_err;
use rustc_span::{Span, Symbol, sym};
use rustc_target::target_features::{self, Stability};
Expand Down Expand Up @@ -64,7 +65,7 @@ pub(crate) fn from_target_feature_attr(

// Only allow target features whose feature gates have been enabled
// and which are permitted to be toggled.
if let Err(reason) = stability.toggle_allowed() {
if let Err(reason) = stability.is_toggle_permitted(tcx.sess) {
tcx.dcx().emit_err(errors::ForbiddenTargetFeatureAttr {
span: item.span(),
feature,
Expand Down
10 changes: 10 additions & 0 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2649,6 +2649,16 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M

let prints = collect_print_requests(early_dcx, &mut cg, &unstable_opts, matches);

// -Zretpoline-external-thunk also requires -Zretpoline
if unstable_opts.retpoline_external_thunk {
unstable_opts.retpoline = true;
target_modifiers.insert(
OptionsTargetModifiers::UnstableOptions(UnstableOptionsTargetModifiers::retpoline),
"true".to_string(),
);
}
Options::fill_target_features_by_flags(&unstable_opts, &mut cg);

let cg = cg;

let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
Expand Down
23 changes: 23 additions & 0 deletions compiler/rustc_session/src/features.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use rustc_target::target_features::Stability;

use crate::Session;

pub trait StabilityExt {
/// Returns whether the feature may be toggled via `#[target_feature]` or `-Ctarget-feature`.
/// Otherwise, some features also may only be enabled by flag (target modifier).
/// (It might still be nightly-only even if this returns `true`, so make sure to also check
/// `requires_nightly`.)
fn is_toggle_permitted(&self, sess: &Session) -> Result<(), &'static str>;
}

impl StabilityExt for Stability {
fn is_toggle_permitted(&self, sess: &Session) -> Result<(), &'static str> {
match self {
Stability::Forbidden { reason } => Err(reason),
Stability::TargetModifierOnly { reason, flag } => {
if !sess.opts.target_feature_flag_enabled(*flag) { Err(reason) } else { Ok(()) }
}
_ => Ok(()),
}
}
}
1 change: 1 addition & 0 deletions compiler/rustc_session/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pub use session::*;
pub mod output;

pub use getopts;
pub mod features;

rustc_fluent_macro::fluent_messages! { "../messages.ftl" }

Expand Down
42 changes: 42 additions & 0 deletions compiler/rustc_session/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,43 @@ macro_rules! top_level_options {
mods.sort_by(|a, b| a.opt.cmp(&b.opt));
mods
}

pub fn target_feature_flag_enabled(&self, flag: &str) -> bool {
match flag {
"retpoline" => self.unstable_opts.retpoline,
"retpoline-external-thunk" => self.unstable_opts.retpoline_external_thunk,
_ => false,
}
}

pub fn fill_target_features_by_flags(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't feel like the right place to do this, ideally there would be a query or something that we could add this logic to that would mean that codegen backends just get the features they need to enable and we'd insert this logic into that.

unstable_opts: &UnstableOptions, cg: &mut CodegenOptions
) {
// -Zretpoline without -Zretpoline-external-thunk enables
// retpoline-indirect-branches and retpoline-indirect-calls target features
if unstable_opts.retpoline && !unstable_opts.retpoline_external_thunk {
if !cg.target_feature.is_empty() {
cg.target_feature.push(',');
}
cg.target_feature.push_str(
"+retpoline-indirect-branches,\
+retpoline-indirect-calls"
);
}
// -Zretpoline-external-thunk (maybe, with -Zretpoline too) enables
// retpoline-external-thunk, retpoline-indirect-branches and
// retpoline-indirect-calls target features
if unstable_opts.retpoline_external_thunk {
if !cg.target_feature.is_empty() {
cg.target_feature.push(',');
}
cg.target_feature.push_str(
"+retpoline-external-thunk,\
+retpoline-indirect-branches,\
+retpoline-indirect-calls"
);
}
}
}
);
}
Expand Down Expand Up @@ -2446,6 +2483,11 @@ options! {
remark_dir: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
"directory into which to write optimization remarks (if not specified, they will be \
written to standard error output)"),
retpoline: bool = (false, parse_bool, [TRACKED TARGET_MODIFIER],
"enables retpoline-indirect-branches and retpoline-indirect-calls target features (default: no)"),
retpoline_external_thunk: bool = (false, parse_bool, [TRACKED TARGET_MODIFIER],
"enables retpoline-external-thunk, retpoline-indirect-branches and retpoline-indirect-calls \
target features (default: no)"),
sanitizer: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED],
"use a sanitizer"),
sanitizer_cfi_canonical_jump_tables: Option<bool> = (Some(true), parse_opt_bool, [TRACKED],
Expand Down
39 changes: 29 additions & 10 deletions compiler/rustc_target/src/target_features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ pub enum Stability {
/// particular for features are actually ABI configuration flags (not all targets are as nice as
/// RISC-V and have an explicit way to set the ABI separate from target features).
Forbidden { reason: &'static str },
/// This feature can not be set via `-Ctarget-feature` or `#[target_feature]`, it can only be set
/// by target modifier flag. Target modifier flags are tracked to be consistent in linked modules.
TargetModifierOnly { reason: &'static str, flag: &'static str },
}
use Stability::*;

Expand All @@ -49,6 +52,7 @@ impl<CTX> HashStable<CTX> for Stability {
Stability::Forbidden { reason } => {
reason.hash_stable(hcx, hasher);
}
Stability::TargetModifierOnly { .. } => {}
}
}
}
Expand All @@ -74,16 +78,7 @@ impl Stability {
Stability::Unstable(nightly_feature) => Some(nightly_feature),
Stability::Stable { .. } => None,
Stability::Forbidden { .. } => panic!("forbidden features should not reach this far"),
}
}

/// Returns whether the feature may be toggled via `#[target_feature]` or `-Ctarget-feature`.
/// (It might still be nightly-only even if this returns `true`, so make sure to also check
/// `requires_nightly`.)
pub fn toggle_allowed(&self) -> Result<(), &'static str> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this API seems confusing, at the very least change the doc comment.

match self {
Stability::Forbidden { reason } => Err(reason),
_ => Ok(()),
Stability::TargetModifierOnly { .. } => None,
}
}
}
Expand Down Expand Up @@ -453,6 +448,30 @@ static X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[
("prfchw", Unstable(sym::prfchw_target_feature), &[]),
("rdrand", Stable, &[]),
("rdseed", Stable, &[]),
(
"retpoline-external-thunk",
Stability::TargetModifierOnly {
reason: "use `retpoline-external-thunk` target modifier flag instead",
flag: "retpoline-external-thunk",
},
&[],
),
(
"retpoline-indirect-branches",
Stability::TargetModifierOnly {
reason: "use `retpoline` target modifier flag instead",
flag: "retpoline",
},
&[],
),
(
"retpoline-indirect-calls",
Stability::TargetModifierOnly {
reason: "use `retpoline` target modifier flag instead",
flag: "retpoline",
},
&[],
),
("rtm", Unstable(sym::rtm_target_feature), &[]),
("sha", Stable, &["sse2"]),
("sha512", Unstable(sym::sha512_sm_x86), &["avx2"]),
Expand Down
5 changes: 3 additions & 2 deletions src/librustdoc/json/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use rustc_data_structures::fx::FxHashSet;
use rustc_hir::def_id::{DefId, DefIdSet};
use rustc_middle::ty::TyCtxt;
use rustc_session::Session;
use rustc_session::features::StabilityExt;
use rustc_span::def_id::LOCAL_CRATE;
use rustdoc_json_types as types;
// It's important to use the FxHashMap from rustdoc_json_types here, instead of
Expand Down Expand Up @@ -148,7 +149,7 @@ fn target(sess: &rustc_session::Session) -> types::Target {
.copied()
.filter(|(_, stability, _)| {
// Describe only target features which the user can toggle
stability.toggle_allowed().is_ok()
stability.is_toggle_permitted(sess).is_ok()
})
.map(|(name, stability, implied_features)| {
types::TargetFeature {
Expand All @@ -164,7 +165,7 @@ fn target(sess: &rustc_session::Session) -> types::Target {
// Imply only target features which the user can toggle
feature_stability
.get(name)
.map(|stability| stability.toggle_allowed().is_ok())
.map(|stability| stability.is_toggle_permitted(sess).is_ok())
.unwrap_or(false)
})
.map(String::from)
Expand Down
29 changes: 29 additions & 0 deletions tests/codegen/retpoline.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// ignore-tidy-linelength
// Test that the
// `retpoline-external-thunk`, `retpoline-indirect-branches`, `retpoline-indirect-calls`
// target features are (not) emitted when the `retpoline/retpoline-external-thunk` flag is (not) set.

//@ revisions: disabled enabled_retpoline enabled_retpoline_external_thunk
//@ needs-llvm-components: x86
//@ compile-flags: --target x86_64-unknown-linux-gnu
//@ [enabled_retpoline] compile-flags: -Zretpoline
//@ [enabled_retpoline_external_thunk] compile-flags: -Zretpoline-external-thunk

#![crate_type = "lib"]
#![feature(no_core, lang_items)]
#![no_core]

#[lang = "sized"]
trait Sized {}

#[no_mangle]
pub fn foo() {
// CHECK: @foo() unnamed_addr #0

// disabled-NOT: attributes #0 = { {{.*}}"target-features"="{{[^"]*}}+retpoline-external-thunk{{.*}} }
// disabled-NOT: attributes #0 = { {{.*}}"target-features"="{{[^"]*}}+retpoline-indirect-branches{{.*}} }
// disabled-NOT: attributes #0 = { {{.*}}"target-features"="{{[^"]*}}+retpoline-indirect-calls{{.*}} }

// enabled_retpoline: attributes #0 = { {{.*}}"target-features"="{{[^"]*}}+retpoline-indirect-branches,+retpoline-indirect-calls{{.*}} }
// enabled_retpoline_external_thunk: attributes #0 = { {{.*}}"target-features"="{{[^"]*}}+retpoline-external-thunk,+retpoline-indirect-branches,+retpoline-indirect-calls{{.*}} }
}
3 changes: 3 additions & 0 deletions tests/ui/check-cfg/target_feature.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE");
`relax`
`relaxed-simd`
`reserve-x18`
`retpoline-external-thunk`
`retpoline-indirect-branches`
`retpoline-indirect-calls`
`rtm`
`sb`
`scq`
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
warning: target feature `retpoline-external-thunk` cannot be enabled with `-Ctarget-feature`: use `x86-retpoline` target modifier flag instead
|
= note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #116344 <https://github.com/rust-lang/rust/issues/116344>

warning: 1 warning emitted

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
warning: target feature `retpoline-external-thunk` cannot be enabled with `-Ctarget-feature`: use `retpoline-external-thunk` target modifier flag instead
|
= note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #116344 <https://github.com/rust-lang/rust/issues/116344>

warning: 1 warning emitted

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
warning: target feature `retpoline-indirect-branches` cannot be enabled with `-Ctarget-feature`: use `retpoline` target modifier flag instead
|
= note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #116344 <https://github.com/rust-lang/rust/issues/116344>

warning: 1 warning emitted

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
warning: target feature `retpoline-indirect-calls` cannot be enabled with `-Ctarget-feature`: use `retpoline` target modifier flag instead
|
= note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #116344 <https://github.com/rust-lang/rust/issues/116344>

warning: 1 warning emitted

23 changes: 23 additions & 0 deletions tests/ui/target-feature/retpoline-target-feature-flag.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//@ revisions: by_flag by_feature1 by_feature2 by_feature3
//@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=lib
//@ needs-llvm-components: x86
//@ [by_flag]compile-flags: -Zretpoline

//@ [by_feature1]compile-flags: -Ctarget-feature=+retpoline-external-thunk
//@ [by_feature2]compile-flags: -Ctarget-feature=+retpoline-indirect-branches
//@ [by_feature3]compile-flags: -Ctarget-feature=+retpoline-indirect-calls
//@ [by_flag]build-pass
// For now this is just a warning.
//@ [by_feature1]build-pass
//@ [by_feature2]build-pass
//@ [by_feature3]build-pass
#![feature(no_core, lang_items)]
#![no_std]
#![no_core]

#[lang = "sized"]
pub trait Sized {}

//[by_feature1]~? WARN target feature `retpoline-external-thunk` cannot be enabled with `-Ctarget-feature`: use `retpoline-external-thunk` target modifier flag instead
//[by_feature2]~? WARN target feature `retpoline-indirect-branches` cannot be enabled with `-Ctarget-feature`: use `retpoline` target modifier flag instead
//[by_feature3]~? WARN target feature `retpoline-indirect-calls` cannot be enabled with `-Ctarget-feature`: use `retpoline` target modifier flag instead
Loading