Skip to content
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

Treat safe target_feature functions as unsafe by default #134317

Open
wants to merge 3 commits 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
10 changes: 9 additions & 1 deletion compiler/rustc_ast_lowering/src/delegation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,15 @@ impl<'hir> LoweringContext<'_, 'hir> {
) -> hir::FnSig<'hir> {
let header = if let Some(local_sig_id) = sig_id.as_local() {
match self.resolver.delegation_fn_sigs.get(&local_sig_id) {
Some(sig) => self.lower_fn_header(sig.header, hir::Safety::Safe),
Some(sig) => self.lower_fn_header(
sig.header,
if sig.target_feature && !matches!(sig.header.safety, Safety::Unsafe(_)) {
hir::Safety::Unsafe { target_feature: true }
} else {
hir::Safety::Safe
},
&[],
),
None => self.generate_header_error(),
}
} else {
Expand Down
36 changes: 28 additions & 8 deletions compiler/rustc_ast_lowering/src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
});
let sig = hir::FnSig {
decl,
header: this.lower_fn_header(*header, hir::Safety::Safe),
header: this.lower_fn_header(*header, hir::Safety::Safe, attrs),
span: this.lower_span(*fn_sig_span),
};
hir::ItemKind::Fn(sig, generics, body_id)
Expand Down Expand Up @@ -609,7 +609,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
let owner_id = hir_id.expect_owner();
self.lower_attrs(hir_id, &i.attrs);
let attrs = self.lower_attrs(hir_id, &i.attrs);
let item = hir::ForeignItem {
owner_id,
ident: self.lower_ident(i.ident),
Expand All @@ -633,7 +633,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
});

// Unmarked safety in unsafe block defaults to unsafe.
let header = self.lower_fn_header(sig.header, hir::Safety::Unsafe);
let header = self.lower_fn_header(
sig.header,
hir::Safety::Unsafe { target_feature: false },
attrs,
);

hir::ForeignItemKind::Fn(
hir::FnSig { header, decl, span: self.lower_span(sig.span) },
Expand All @@ -644,7 +648,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
ForeignItemKind::Static(box StaticItem { ty, mutability, expr: _, safety }) => {
let ty = self
.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
let safety = self.lower_safety(*safety, hir::Safety::Unsafe);
let safety =
self.lower_safety(*safety, hir::Safety::Unsafe { target_feature: false });

hir::ForeignItemKind::Static(ty, *mutability, safety)
}
Expand Down Expand Up @@ -748,7 +753,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
self.lower_attrs(hir_id, &i.attrs);
let attrs = self.lower_attrs(hir_id, &i.attrs);
let trait_item_def_id = hir_id.expect_owner();

let (generics, kind, has_default) = match &i.kind {
Expand All @@ -775,6 +780,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
i.id,
FnDeclKind::Trait,
sig.header.coroutine_kind,
attrs,
);
(generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
}
Expand All @@ -793,6 +799,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
i.id,
FnDeclKind::Trait,
sig.header.coroutine_kind,
attrs,
);
(generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
}
Expand Down Expand Up @@ -878,7 +885,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let has_value = true;
let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
self.lower_attrs(hir_id, &i.attrs);
let attrs = self.lower_attrs(hir_id, &i.attrs);

let (generics, kind) = match &i.kind {
AssocItemKind::Const(box ConstItem { generics, ty, expr, .. }) => self.lower_generics(
Expand Down Expand Up @@ -908,6 +915,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
i.id,
if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
sig.header.coroutine_kind,
attrs,
);

(generics, hir::ImplItemKind::Fn(sig, body_id))
Expand Down Expand Up @@ -1322,8 +1330,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
id: NodeId,
kind: FnDeclKind,
coroutine_kind: Option<CoroutineKind>,
attrs: &[Attribute],
) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
let header = self.lower_fn_header(sig.header, hir::Safety::Safe);
let header = self.lower_fn_header(sig.header, hir::Safety::Safe, attrs);
let itctx = ImplTraitContext::Universal;
let (generics, decl) = self.lower_generics(generics, id, itctx, |this| {
this.lower_fn_decl(&sig.decl, id, sig.span, kind, coroutine_kind)
Expand All @@ -1335,12 +1344,23 @@ impl<'hir> LoweringContext<'_, 'hir> {
&mut self,
h: FnHeader,
default_safety: hir::Safety,
attrs: &[Attribute],
) -> hir::FnHeader {
let asyncness = if let Some(CoroutineKind::Async { span, .. }) = h.coroutine_kind {
hir::IsAsync::Async(span)
} else {
hir::IsAsync::NotAsync
};

let default_safety = if attrs.iter().any(|attr| attr.has_name(sym::target_feature))
&& !matches!(h.safety, Safety::Unsafe(_))
&& default_safety.is_safe()
{
hir::Safety::Unsafe { target_feature: true }
} else {
default_safety
};

hir::FnHeader {
safety: self.lower_safety(h.safety, default_safety),
asyncness,
Expand Down Expand Up @@ -1394,7 +1414,7 @@ impl<'hir> LoweringContext<'_, 'hir> {

pub(super) fn lower_safety(&mut self, s: Safety, default: hir::Safety) -> hir::Safety {
match s {
Safety::Unsafe(_) => hir::Safety::Unsafe,
Safety::Unsafe(_) => hir::Safety::Unsafe { target_feature: false },
Safety::Default => default,
Safety::Safe(_) => hir::Safety::Safe,
}
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_codegen_gcc/src/intrinsic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1222,7 +1222,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>(
iter::once(i8p),
tcx.types.unit,
false,
rustc_hir::Safety::Unsafe,
rustc_hir::Safety::Unsafe { target_feature: false },
Abi::Rust,
)),
);
Expand All @@ -1233,7 +1233,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>(
[i8p, i8p].iter().cloned(),
tcx.types.unit,
false,
rustc_hir::Safety::Unsafe,
rustc_hir::Safety::Unsafe { target_feature: false },
Abi::Rust,
)),
);
Expand All @@ -1242,7 +1242,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>(
[try_fn_ty, i8p, catch_fn_ty],
tcx.types.i32,
false,
rustc_hir::Safety::Unsafe,
rustc_hir::Safety::Unsafe { target_feature: false },
Abi::Rust,
));
let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_codegen_llvm/src/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1091,7 +1091,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
[i8p],
tcx.types.unit,
false,
hir::Safety::Unsafe,
hir::Safety::Unsafe { target_feature: false },
ExternAbi::Rust,
)),
);
Expand All @@ -1102,7 +1102,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
[i8p, i8p],
tcx.types.unit,
false,
hir::Safety::Unsafe,
hir::Safety::Unsafe { target_feature: false },
ExternAbi::Rust,
)),
);
Expand All @@ -1111,7 +1111,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
[try_fn_ty, i8p, catch_fn_ty],
tcx.types.i32,
false,
hir::Safety::Unsafe,
hir::Safety::Unsafe { target_feature: false },
ExternAbi::Rust,
));
let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_codegen_ssa/src/codegen_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
sym::target_feature => {
if !tcx.is_closure_like(did.to_def_id())
&& let Some(fn_sig) = fn_sig()
&& fn_sig.skip_binder().safety() == hir::Safety::Safe
&& matches!(fn_sig.skip_binder().safety(), hir::Safety::Unsafe {
target_feature: true
})
{
if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
// The `#[target_feature]` attribute is allowed on
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_const_eval/src/const_eval/fn_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,8 @@ fn is_promotable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
Some(stab) => {
if cfg!(debug_assertions) && stab.promotable {
let sig = tcx.fn_sig(def_id);
assert_eq!(
sig.skip_binder().safety(),
hir::Safety::Safe,
assert!(
sig.skip_binder().safety().is_safe(),
"don't mark const unsafe fns as promotable",
// https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682
);
Expand Down
29 changes: 25 additions & 4 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3390,23 +3390,44 @@ impl<'hir> Item<'hir> {
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[derive(Encodable, Decodable, HashStable_Generic)]
pub enum Safety {
Unsafe,
Unsafe {
/// Whether this is a safe target_feature function.
/// We treat those as unsafe almost everywhere, but in unsafeck,
/// which allows calling them from other target_feature functions
/// without an `unsafe` block.
target_feature: bool,
},
Safe,
}

impl Safety {
pub fn prefix_str(self) -> &'static str {
match self {
Self::Unsafe => "unsafe ",
Self::Unsafe { target_feature: false } => "unsafe ",
Self::Unsafe { target_feature: true } => "#[target_feature] ",
Self::Safe => "",
}
}

#[inline]
pub fn is_unsafe(self) -> bool {
!self.is_safe()
}

#[inline]
pub fn is_safe(self) -> bool {
match self {
Self::Unsafe { .. } => false,
Self::Safe => true,
}
}
}

impl fmt::Display for Safety {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match *self {
Self::Unsafe => "unsafe",
Self::Unsafe { target_feature: false } => "unsafe",
Self::Unsafe { target_feature: true } => "#[target_feature] safe",
Self::Safe => "safe",
})
}
Expand Down Expand Up @@ -3445,7 +3466,7 @@ impl FnHeader {
}

pub fn is_unsafe(&self) -> bool {
matches!(&self.safety, Safety::Unsafe)
self.safety.is_unsafe()
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_analysis/src/check/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_errors::MultiSpan;
use rustc_errors::codes::*;
use rustc_hir::def::{CtorKind, DefKind};
use rustc_hir::{Node, Safety, intravisit};
use rustc_hir::{Node, intravisit};
use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
use rustc_infer::traits::{Obligation, ObligationCauseCode};
use rustc_lint_defs::builtin::{
Expand Down Expand Up @@ -161,7 +161,7 @@ fn check_unsafe_fields(tcx: TyCtxt<'_>, item_def_id: LocalDefId) {
};
let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
for field in def.all_fields() {
if field.safety != Safety::Unsafe {
if !field.safety.is_unsafe() {
continue;
}
let Ok(field_ty) = tcx.try_normalize_erasing_regions(typing_env, field.ty(tcx, args))
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_hir_analysis/src/check/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -
tcx.fn_sig(intrinsic_id).skip_binder().safety()
} else {
// Old-style intrinsics are never safe
Safety::Unsafe
Safety::Unsafe { target_feature: false }
};
let is_in_list = match tcx.item_name(intrinsic_id.into()) {
// When adding a new intrinsic to this list,
Expand Down Expand Up @@ -137,7 +137,7 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -
| sym::fdiv_algebraic
| sym::frem_algebraic
| sym::const_eval_select => hir::Safety::Safe,
_ => hir::Safety::Unsafe,
_ => hir::Safety::Unsafe { target_feature: false },
};

if has_safe_attr != is_in_list {
Expand Down Expand Up @@ -216,7 +216,7 @@ pub fn check_intrinsic_type(
return;
}
};
(n_tps, 0, 0, inputs, output, hir::Safety::Unsafe)
(n_tps, 0, 0, inputs, output, hir::Safety::Unsafe { target_feature: false })
} else {
let safety = intrinsic_operation_unsafety(tcx, intrinsic_id);
let (n_tps, n_cts, inputs, output) = match intrinsic_name {
Expand Down
12 changes: 6 additions & 6 deletions compiler/rustc_hir_analysis/src/coherence/unsafety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub(super) fn check_item(
let trait_def_safety = if is_copy {
// If `Self` has unsafe fields, `Copy` is unsafe to implement.
if trait_header.trait_ref.skip_binder().self_ty().has_unsafe_fields() {
rustc_hir::Safety::Unsafe
rustc_hir::Safety::Unsafe { target_feature: false }
} else {
rustc_hir::Safety::Safe
}
Expand All @@ -33,7 +33,7 @@ pub(super) fn check_item(
};

match (trait_def_safety, unsafe_attr, trait_header.safety, trait_header.polarity) {
(Safety::Safe, None, Safety::Unsafe, Positive | Reservation) => {
(Safety::Safe, None, Safety::Unsafe { .. }, Positive | Reservation) => {
let span = tcx.def_span(def_id);
return Err(struct_span_code_err!(
tcx.dcx(),
Expand All @@ -51,7 +51,7 @@ pub(super) fn check_item(
.emit());
}

(Safety::Unsafe, _, Safety::Safe, Positive | Reservation) => {
(Safety::Unsafe { .. }, _, Safety::Safe, Positive | Reservation) => {
let span = tcx.def_span(def_id);
return Err(struct_span_code_err!(
tcx.dcx(),
Expand Down Expand Up @@ -109,14 +109,14 @@ pub(super) fn check_item(
.emit());
}

(_, _, Safety::Unsafe, Negative) => {
(_, _, Safety::Unsafe { .. }, Negative) => {
// Reported in AST validation
assert!(tcx.dcx().has_errors().is_some(), "unsafe negative impl");
Ok(())
}
(_, _, Safety::Safe, Negative)
| (Safety::Unsafe, _, Safety::Unsafe, Positive | Reservation)
| (Safety::Safe, Some(_), Safety::Unsafe, Positive | Reservation)
| (Safety::Unsafe { .. }, _, Safety::Unsafe { .. }, Positive | Reservation)
| (Safety::Safe, Some(_), Safety::Unsafe { .. }, Positive | Reservation)
| (Safety::Safe, None, Safety::Safe, _) => Ok(()),
}
}
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1371,7 +1371,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_, ty::PolyFn
// constructors for structs with `layout_scalar_valid_range` are unsafe to call
let safety = match tcx.layout_scalar_valid_range(adt_def_id) {
(Bound::Unbounded, Bound::Unbounded) => hir::Safety::Safe,
_ => hir::Safety::Unsafe,
_ => hir::Safety::Unsafe { target_feature: false },
};
ty::Binder::dummy(tcx.mk_fn_sig(inputs, ty, false, safety, ExternAbi::Rust))
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2293,8 +2293,8 @@ impl<'a> State<'a> {

fn print_safety(&mut self, s: hir::Safety) {
match s {
hir::Safety::Safe => {}
hir::Safety::Unsafe => self.word_nbsp("unsafe"),
hir::Safety::Unsafe { target_feature: true } | hir::Safety::Safe => {}
hir::Safety::Unsafe { target_feature: false } => self.word_nbsp("unsafe"),
}
}

Expand Down
Loading
Loading