Skip to content
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
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/target_features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ pub fn internal_target_features<'a, const N: usize>(
}

// Check feature stability.
if let Stability::InternalOnly { reason, hard_error } = stability {
if let Stability::InternalOnly { reason, hard_error, .. } = stability {
let diag = diagnostics::InternalOnlyCTargetFeature {
feature: base_feature,
enabled: if enable { "enabled" } else { "disabled" },
Expand Down
24 changes: 20 additions & 4 deletions compiler/rustc_interface/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ use rustc_middle::dep_graph::WorkProductMap;
use rustc_middle::ty::{CurrentGcx, TyCtxt};
use rustc_query_impl::{CollectActiveJobsKind, collect_active_query_jobs};
use rustc_session::config::{
Cfg, CrateType, Jobs, OutFileName, OutputFilenames, OutputTypes, Sysroot, host_tuple,
Cfg, CrateType, Jobs, OptionsTargetModifiers, OutFileName, OutputFilenames, OutputTypes,
Sysroot, host_tuple,
};
use rustc_session::{EarlyDiagCtxt, IncrCompSession, Session, filesearch};
use rustc_span::edition::Edition;
Expand Down Expand Up @@ -55,10 +56,10 @@ pub(crate) fn add_configuration(
sess.target
.rust_target_features()
.iter()
.filter_map(|(feature, gate, _)| {
if gate.in_cfg()
.filter_map(|(feature, stab, _)| {
if stab.in_cfg()
&& (sess.is_nightly_build()
|| gate.requires_nightly(/* in_cfg */ true).is_none())
|| stab.requires_nightly(/* in_cfg */ true).is_none())
{
Some(Symbol::intern(feature))
} else {
Expand All @@ -69,6 +70,21 @@ pub(crate) fn add_configuration(
.map(|feature| (sym::target_feature, Some(feature))),
);

// Record relevant target features as target modifier.
sess.opts.target_modifiers.insert(
OptionsTargetModifiers::TargetFeatures,
// Join all target-modifier target features into a single comma-separated string,
// sorted by the order they appear in in `rust_target_features`.
sess.target
.rust_target_features()
.iter()
.filter(|(_, stab, _)| stab.is_target_modifier())
.map(|(feature, ..)| *feature)
.filter(|feature| tf_cfg.internal_target_features.contains(&Symbol::intern(feature)))
.collect::<Vec<_>>()
.join(","),
);

// Store all of them in the session.
sess.internal_target_features.extend(tf_cfg.internal_target_features.into_sorted_stable_ord());

Expand Down
57 changes: 56 additions & 1 deletion compiler/rustc_metadata/src/creader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::owned_slice::OwnedSlice;
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::{self, FreezeReadGuard, FreezeWriteGuard};
use rustc_data_structures::unord::UnordMap;
use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_expand::base::SyntaxExtension;
use rustc_hir as hir;
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE, LocalDefId, StableCrateId};
Expand Down Expand Up @@ -361,6 +361,61 @@ impl CStore {
return;
}
let extern_crate = data.name();

if prefix.is_empty() {
// A synthetic target modifier, does not correspond to an actual flag.
match opt_name.as_str() {
"target-feature" => {
// Compute the features we have locally that don't exist in the other crate,
// and the features the other crate has that are missing locally.
let mut local_features = FxHashSet::from_iter(
flag_local_value.unwrap().split(",").filter(|s| !s.is_empty()),
);
let mut extern_features = FxHashSet::from_iter(
flag_extern_value.unwrap().split(",").filter(|s| !s.is_empty()),
);
#[allow(rustc::potential_query_instability)] // we are sorting below
let both_features = FxHashSet::from_iter(
local_features.intersection(&extern_features).copied(),
);
#[allow(rustc::potential_query_instability)] // we are sorting below
for feature in both_features {
local_features.remove(feature);
extern_features.remove(feature);
}
let local_features =
UnordSet::from(local_features).into_sorted_stable_ord();
let extern_features =
UnordSet::from(extern_features).into_sorted_stable_ord();
assert!(local_features.len() > 0 || extern_features.len() > 0);

let diag = format!(
"mixing target features will cause an ABI mismatch in crate `{local_crate}`"
);
let mut diag = tcx.dcx().struct_warn(diag);
diag.help("some target features modify the ABI so Rust crates compiled with different values for these target features cannot be used together safely");
if local_features.len() > 0 {
let features = local_features.join(", ");
let before =
if local_features.len() == 1 { "feature" } else { "features" };
let after = if local_features.len() == 1 { "is" } else { "are" };
diag.help(format!("the target {before} {features} {after} enabled in this crate but disabled in `{extern_crate}`"));
}
if extern_features.len() > 0 {
let features = extern_features.join(", ");
let before =
if extern_features.len() == 1 { "feature" } else { "features" };
let after = if extern_features.len() == 1 { "is" } else { "are" };
diag.help(format!("the target {before} {features} {after} enabled in `{extern_crate}` but disabled in this crate"));
}
diag.help("if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch=target-feature` to silence this warning");
diag.emit();
}
_ => panic!("unhandled synthetic target feature {opt_name}"),
}
return;
}

let flag_name = opt_name.clone();
let flag_name_prefixed = format!("-{}{}", prefix, opt_name);

Expand Down
21 changes: 19 additions & 2 deletions compiler/rustc_session/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,11 @@ macro_rules! hash_substruct {
/// Target modifier enum value + user value ('2') from external crate
/// is converted into description: prefix ('Z'), name ('regparm'), tech value ('Some(2)').
pub struct ExtendedTargetModifierInfo {
/// Flag prefix (usually, 'C' for codegen flags or 'Z' for unstable flags)
/// Flag prefix (usually, 'C' for codegen flags or 'Z' for unstable flags). And empty string
/// indicates a synthetic target modifier, which does not correspond directly to a flag.
pub prefix: String,
/// Flag name
/// Flag name. For synthetic features, this is still relevant as the name used to suppress
/// the error for mismatches involving this target modifier.
pub name: String,
/// Flag parsed technical value
pub tech_value: String,
Expand Down Expand Up @@ -180,6 +182,7 @@ impl TargetModifier {
return target_modifier_consistency_check::target_cpu(sess, self, other);
}
},
_ => {}
};
match other {
Some(other) => self.extend().tech_value == other.extend().tech_value,
Expand Down Expand Up @@ -218,6 +221,9 @@ macro_rules! top_level_options {
$tmod_variant($tmod_enum),
)?
)*
// Synthetic target modifiers, manually computed.
/// List of target features that are actually target modifiers.
TargetFeatures,
}

impl OptionsTargetModifiers {
Expand All @@ -228,6 +234,13 @@ macro_rules! top_level_options {
Self::$tmod_variant(v) => v.reparse(user_value),
)?
)*
Self::TargetFeatures => {
ExtendedTargetModifierInfo {
prefix: String::new(),
name: "target-feature".into(),
tech_value: format!("{:?}", user_value),
}
}
#[allow(unreachable_patterns)]
_ => panic!("unknown target modifier option: {self:?}"),
}
Expand All @@ -252,6 +265,8 @@ macro_rules! top_level_options {
$(#[$attr])*
pub $opt: $t,
)*
/// Store values for target modifiers. `gather_target_modifiers` takes those values
/// to decide what to store in metadata.
pub target_modifiers: BTreeMap<OptionsTargetModifiers, String>,
Comment on lines +268 to 270

@RalfJung RalfJung Aug 5, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

FWIW I could not quite understand why we have both this map and some extra logic in gather_target_modifiers. When I found this map I had assumed that the entire contents of this map will be stored as target modifier, but instead there's a separate filtering step. Why?

Cc @azhogin

View changes since the review

pub mitigation_coverage_map: mitigation_coverage::MitigationCoverageMap,
}
Expand Down Expand Up @@ -290,13 +305,15 @@ macro_rules! top_level_options {

pub fn gather_target_modifiers(&self) -> Vec<TargetModifier> {
let mut mods = Vec::<TargetModifier>::new();
// Forward values from `self.target_modifiers` into `mods`.
$(
$(
// Only expand for flags that have `TARGET_MODIFIER`.
${ignore($tmod_enum)}
self.$opt.gather_target_modifiers(&mut mods, &self.target_modifiers);
)?
)*
tmod_push_impl(OptionsTargetModifiers::TargetFeatures, &self.target_modifiers, &mut mods);
mods.sort_by(|a, b| a.opt.cmp(&b.opt));
mods
}
Expand Down
Loading
Loading