Skip to content

Commit 69a19f4

Browse files
committed
Implement struct_target_features for non-generic functions.
1 parent f6648f2 commit 69a19f4

File tree

27 files changed

+618
-28
lines changed

27 files changed

+618
-28
lines changed

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

+78-11
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
99
use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS;
1010
use rustc_hir::{LangItem, lang_items};
1111
use rustc_middle::middle::codegen_fn_attrs::{
12-
CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry,
12+
CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, TargetFeature,
1313
};
1414
use rustc_middle::mir::mono::Linkage;
1515
use rustc_middle::query::Providers;
16-
use rustc_middle::ty::{self as ty, TyCtxt};
16+
use rustc_middle::ty::{self as ty, Ty, TyCtxt};
1717
use rustc_session::parse::feature_err;
1818
use rustc_session::{Session, lint};
1919
use rustc_span::symbol::Ident;
@@ -79,23 +79,26 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
7979
let mut link_ordinal_span = None;
8080
let mut no_sanitize_span = None;
8181

82+
let fn_sig_outer = || {
83+
use DefKind::*;
84+
85+
let def_kind = tcx.def_kind(did);
86+
if let Fn | AssocFn | Variant | Ctor(..) = def_kind { Some(tcx.fn_sig(did)) } else { None }
87+
};
88+
8289
for attr in attrs.iter() {
8390
// In some cases, attribute are only valid on functions, but it's the `check_attr`
8491
// pass that check that they aren't used anywhere else, rather this module.
8592
// In these cases, we bail from performing further checks that are only meaningful for
8693
// functions (such as calling `fn_sig`, which ICEs if given a non-function). We also
8794
// report a delayed bug, just in case `check_attr` isn't doing its job.
8895
let fn_sig = || {
89-
use DefKind::*;
90-
91-
let def_kind = tcx.def_kind(did);
92-
if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
93-
Some(tcx.fn_sig(did))
94-
} else {
96+
let sig = fn_sig_outer();
97+
if sig.is_none() {
9598
tcx.dcx()
9699
.span_delayed_bug(attr.span, "this attribute can only be applied to functions");
97-
None
98100
}
101+
sig
99102
};
100103

101104
let Some(Ident { name, .. }) = attr.ident() else {
@@ -596,7 +599,30 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
596599
}
597600
}
598601

599-
// If a function uses #[target_feature] it can't be inlined into general
602+
if let Some(sig) = fn_sig_outer() {
603+
for ty in sig.skip_binder().inputs().skip_binder() {
604+
let additional_tf =
605+
tcx.struct_reachable_target_features(tcx.param_env(did.to_def_id()).and(*ty));
606+
// FIXME(struct_target_features): is this really necessary?
607+
if !additional_tf.is_empty() && sig.skip_binder().abi() != abi::Abi::Rust {
608+
tcx.dcx().span_err(
609+
tcx.hir().span(tcx.local_def_id_to_hir_id(did)),
610+
"cannot use a struct with target features in a function with non-Rust ABI",
611+
);
612+
}
613+
if !additional_tf.is_empty() && codegen_fn_attrs.inline == InlineAttr::Always {
614+
tcx.dcx().span_err(
615+
tcx.hir().span(tcx.local_def_id_to_hir_id(did)),
616+
"cannot use a struct with target features in a #[inline(always)] function",
617+
);
618+
}
619+
codegen_fn_attrs
620+
.target_features
621+
.extend(additional_tf.iter().map(|tf| TargetFeature { implied: true, ..*tf }));
622+
}
623+
}
624+
625+
// If a function uses non-default target_features it can't be inlined into general
600626
// purpose functions as they wouldn't have the right target features
601627
// enabled. For that reason we also forbid #[inline(always)] as it can't be
602628
// respected.
@@ -779,6 +805,47 @@ fn check_link_name_xor_ordinal(
779805
}
780806
}
781807

808+
fn struct_target_features(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[TargetFeature] {
809+
let mut features = vec![];
810+
let supported_features = tcx.supported_target_features(LOCAL_CRATE);
811+
for attr in tcx.get_attrs(def_id, sym::target_feature) {
812+
from_target_feature(tcx, attr, supported_features, &mut features);
813+
}
814+
tcx.arena.alloc_slice(&features)
815+
}
816+
817+
fn struct_reachable_target_features<'tcx>(
818+
tcx: TyCtxt<'tcx>,
819+
env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
820+
) -> &'tcx [TargetFeature] {
821+
// Collect target features from types reachable from `env.value` by dereferencing a certain
822+
// number of references and resolving aliases.
823+
824+
let mut ty = env.value;
825+
if matches!(ty.kind(), ty::Alias(..)) {
826+
ty = match tcx.try_normalize_erasing_regions(env.param_env, ty) {
827+
Ok(ty) => ty,
828+
Err(_) => return tcx.arena.alloc_slice(&[]),
829+
};
830+
}
831+
while let ty::Ref(_, inner, _) = ty.kind() {
832+
ty = *inner;
833+
}
834+
835+
let tf = if let ty::Adt(adt_def, ..) = ty.kind() {
836+
tcx.struct_target_features(adt_def.did())
837+
} else {
838+
&[]
839+
};
840+
tcx.arena.alloc_slice(tf)
841+
}
842+
782843
pub(crate) fn provide(providers: &mut Providers) {
783-
*providers = Providers { codegen_fn_attrs, should_inherit_track_caller, ..*providers };
844+
*providers = Providers {
845+
codegen_fn_attrs,
846+
should_inherit_track_caller,
847+
struct_target_features,
848+
struct_reachable_target_features,
849+
..*providers
850+
};
784851
}

compiler/rustc_feature/src/unstable.rs

+2
Original file line numberDiff line numberDiff line change
@@ -601,6 +601,8 @@ declare_features! (
601601
(unstable, strict_provenance, "1.61.0", Some(95228)),
602602
/// Allows string patterns to dereference values to match them.
603603
(unstable, string_deref_patterns, "1.67.0", Some(87121)),
604+
/// Allows structs to carry target_feature information.
605+
(incomplete, struct_target_features, "CURRENT_RUSTC_VERSION", Some(129107)),
604606
/// Allows the use of `#[target_feature]` on safe functions.
605607
(unstable, target_feature_11, "1.45.0", Some(69098)),
606608
/// Allows using `#[thread_local]` on `static` items.

compiler/rustc_hir/src/def.rs

+37
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,43 @@ impl DefKind {
329329
| DefKind::ExternCrate => false,
330330
}
331331
}
332+
333+
/// Whether `query struct_target_features` should be used with this definition.
334+
pub fn has_struct_target_features(self) -> bool {
335+
match self {
336+
DefKind::Struct => true,
337+
DefKind::Fn
338+
| DefKind::Union
339+
| DefKind::Enum
340+
| DefKind::AssocFn
341+
| DefKind::Ctor(..)
342+
| DefKind::Closure
343+
| DefKind::Static { .. }
344+
| DefKind::Mod
345+
| DefKind::Variant
346+
| DefKind::Trait
347+
| DefKind::TyAlias
348+
| DefKind::ForeignTy
349+
| DefKind::TraitAlias
350+
| DefKind::AssocTy
351+
| DefKind::Const
352+
| DefKind::AssocConst
353+
| DefKind::Macro(..)
354+
| DefKind::Use
355+
| DefKind::ForeignMod
356+
| DefKind::OpaqueTy
357+
| DefKind::Impl { .. }
358+
| DefKind::Field
359+
| DefKind::TyParam
360+
| DefKind::ConstParam
361+
| DefKind::LifetimeParam
362+
| DefKind::AnonConst
363+
| DefKind::InlineConst
364+
| DefKind::SyntheticCoroutineBody
365+
| DefKind::GlobalAsm
366+
| DefKind::ExternCrate => false,
367+
}
368+
}
332369
}
333370

334371
/// The resolution of a path or export.

compiler/rustc_hir_typeck/src/coercion.rs

+2
Original file line numberDiff line numberDiff line change
@@ -921,6 +921,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
921921
}
922922

923923
// Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
924+
// FIXME(struct_target_features): should this be true also for functions that inherit
925+
// target features from structs?
924926

925927
if b_hdr.safety == hir::Safety::Safe
926928
&& !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()

compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs

+1
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ provide! { tcx, def_id, other, cdata,
254254
variances_of => { table }
255255
fn_sig => { table }
256256
codegen_fn_attrs => { table }
257+
struct_target_features => { table_defaulted_array }
257258
impl_trait_header => { table }
258259
const_param_default => { table }
259260
object_lifetime_default => { table }

compiler/rustc_metadata/src/rmeta/encoder.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1401,6 +1401,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
14011401
if def_kind.has_codegen_attrs() {
14021402
record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
14031403
}
1404+
if def_kind.has_struct_target_features() {
1405+
record_defaulted_array!(self.tables.struct_target_features[def_id] <- self.tcx.struct_target_features(def_id));
1406+
}
14041407
if should_encode_visibility(def_kind) {
14051408
let vis =
14061409
self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);

compiler/rustc_metadata/src/rmeta/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use rustc_macros::{
1919
Decodable, Encodable, MetadataDecodable, MetadataEncodable, TyDecodable, TyEncodable,
2020
};
2121
use rustc_middle::metadata::ModChild;
22-
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
22+
use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature};
2323
use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
2424
use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
2525
use rustc_middle::middle::lib_features::FeatureStability;
@@ -404,6 +404,7 @@ define_tables! {
404404
// individually instead of `DefId`s.
405405
module_children_reexports: Table<DefIndex, LazyArray<ModChild>>,
406406
cross_crate_inlinable: Table<DefIndex, bool>,
407+
struct_target_features: Table<DefIndex, LazyArray<TargetFeature>>,
407408

408409
- optional:
409410
attributes: Table<DefIndex, LazyArray<ast::Attribute>>,

compiler/rustc_middle/src/middle/codegen_fn_attrs.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ pub struct CodegenFnAttrs {
2626
/// be set when `link_name` is set. This is for foreign items with the
2727
/// "raw-dylib" kind.
2828
pub link_ordinal: Option<u16>,
29-
/// The `#[target_feature(enable = "...")]` attribute and the enabled
30-
/// features (only enabled features are supported right now).
29+
/// All the target features that are enabled for this function. Some features might be enabled
30+
/// implicitly.
3131
pub target_features: Vec<TargetFeature>,
3232
/// The `#[linkage = "..."]` attribute on Rust-defined items and the value we found.
3333
pub linkage: Option<Linkage>,
@@ -55,8 +55,8 @@ pub struct CodegenFnAttrs {
5555
pub struct TargetFeature {
5656
/// The name of the target feature (e.g. "avx")
5757
pub name: Symbol,
58-
/// The feature is implied by another feature, rather than explicitly added by the
59-
/// `#[target_feature]` attribute
58+
/// The feature is implied by another feature or by an argument, rather than explicitly
59+
/// added by the `#[target_feature]` attribute
6060
pub implied: bool,
6161
}
6262

compiler/rustc_middle/src/query/mod.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir};
4848
use crate::infer::canonical::{self, Canonical};
4949
use crate::lint::LintExpectation;
5050
use crate::metadata::ModChild;
51-
use crate::middle::codegen_fn_attrs::CodegenFnAttrs;
51+
use crate::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature};
5252
use crate::middle::debugger_visualizer::DebuggerVisualizerFile;
5353
use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
5454
use crate::middle::lib_features::LibFeatures;
@@ -1256,6 +1256,15 @@ rustc_queries! {
12561256
feedable
12571257
}
12581258

1259+
query struct_target_features(def_id: DefId) -> &'tcx [TargetFeature] {
1260+
separate_provide_extern
1261+
desc { |tcx| "computing target features for struct `{}`", tcx.def_path_str(def_id) }
1262+
}
1263+
1264+
query struct_reachable_target_features(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx [TargetFeature] {
1265+
desc { |tcx| "computing target features reachable from {}", env.value }
1266+
}
1267+
12591268
query asm_target_features(def_id: DefId) -> &'tcx FxIndexSet<Symbol> {
12601269
desc { |tcx| "computing target features for inline asm of `{}`", tcx.def_path_str(def_id) }
12611270
}

compiler/rustc_middle/src/ty/parameterized.rs

+1
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ trivially_parameterized_over_tcx! {
5959
std::string::String,
6060
crate::metadata::ModChild,
6161
crate::middle::codegen_fn_attrs::CodegenFnAttrs,
62+
crate::middle::codegen_fn_attrs::TargetFeature,
6263
crate::middle::debugger_visualizer::DebuggerVisualizerFile,
6364
crate::middle::exported_symbols::SymbolExportInfo,
6465
crate::middle::lib_features::FeatureStability,

compiler/rustc_mir_build/messages.ftl

+46
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,37 @@ mir_build_initializing_type_with_requires_unsafe_unsafe_op_in_unsafe_fn_allowed
125125
.note = initializing a layout restricted type's field with a value outside the valid range is undefined behavior
126126
.label = initializing type with `rustc_layout_scalar_valid_range` attr
127127
128+
mir_build_initializing_type_with_target_feature_requires_unsafe =
129+
initializing type `{$adt}` with `#[target_feature]` is unsafe and requires unsafe block
130+
.help = in order for the call to be safe, the context requires the following additional target {$missing_target_features_count ->
131+
[1] feature
132+
*[count] features
133+
}: {$missing_target_features}
134+
.note = the {$build_target_features} target {$build_target_features_count ->
135+
[1] feature
136+
*[count] features
137+
} being enabled in the build configuration does not remove the requirement to list {$build_target_features_count ->
138+
[1] it
139+
*[count] them
140+
} in `#[target_feature]`
141+
.label = call to function with `#[target_feature]`
142+
143+
mir_build_initializing_type_with_target_feature_requires_unsafe_unsafe_op_in_unsafe_fn_allowed =
144+
initializing type `{$adt}` with `#[target_feature]` is unsafe and requires unsafe function or block
145+
.help = in order for the call to be safe, the context requires the following additional target {$missing_target_features_count ->
146+
[1] feature
147+
*[count] features
148+
}: {$missing_target_features}
149+
.note = the {$build_target_features} target {$build_target_features_count ->
150+
[1] feature
151+
*[count] features
152+
} being enabled in the build configuration does not remove the requirement to list {$build_target_features_count ->
153+
[1] it
154+
*[count] them
155+
} in `#[target_feature]`
156+
.label = call to function with `#[target_feature]`
157+
158+
128159
mir_build_inline_assembly_requires_unsafe =
129160
use of inline assembly is unsafe and requires unsafe block
130161
.note = inline assembly is entirely unchecked and can cause undefined behavior
@@ -388,6 +419,21 @@ mir_build_unsafe_op_in_unsafe_fn_initializing_type_with_requires_unsafe =
388419
.note = initializing a layout restricted type's field with a value outside the valid range is undefined behavior
389420
.label = initializing type with `rustc_layout_scalar_valid_range` attr
390421
422+
mir_build_unsafe_op_in_unsafe_fn_initializing_type_with_target_feature_requires_unsafe =
423+
initializing type `{$adt}` with `#[target_feature]` is unsafe and requires unsafe block
424+
.help = in order for the call to be safe, the context requires the following additional target {$missing_target_features_count ->
425+
[1] feature
426+
*[count] features
427+
}: {$missing_target_features}
428+
.note = the {$build_target_features} target {$build_target_features_count ->
429+
[1] feature
430+
*[count] features
431+
} being enabled in the build configuration does not remove the requirement to list {$build_target_features_count ->
432+
[1] it
433+
*[count] them
434+
} in `#[target_feature]`
435+
.label = call to function with `#[target_feature]`
436+
391437
mir_build_unsafe_op_in_unsafe_fn_inline_assembly_requires_unsafe =
392438
use of inline assembly is unsafe and requires unsafe block
393439
.note = inline assembly is entirely unchecked and can cause undefined behavior

0 commit comments

Comments
 (0)