rustc_codegen_ssa/
target_features.rs

1use rustc_attr_data_structures::InstructionSetAttr;
2use rustc_data_structures::fx::FxIndexSet;
3use rustc_data_structures::unord::{UnordMap, UnordSet};
4use rustc_errors::Applicability;
5use rustc_hir as hir;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
8use rustc_middle::middle::codegen_fn_attrs::TargetFeature;
9use rustc_middle::query::Providers;
10use rustc_middle::ty::TyCtxt;
11use rustc_session::lint::builtin::AARCH64_SOFTFLOAT_NEON;
12use rustc_session::parse::feature_err;
13use rustc_span::{Span, Symbol, sym};
14use rustc_target::target_features::{self, Stability};
15
16use crate::errors;
17
18/// Compute the enabled target features from the `#[target_feature]` function attribute.
19/// Enabled target features are added to `target_features`.
20pub(crate) fn from_target_feature_attr(
21    tcx: TyCtxt<'_>,
22    did: LocalDefId,
23    attr: &hir::Attribute,
24    rust_target_features: &UnordMap<String, target_features::Stability>,
25    target_features: &mut Vec<TargetFeature>,
26) {
27    let Some(list) = attr.meta_item_list() else { return };
28    let bad_item = |span| {
29        let msg = "malformed `target_feature` attribute input";
30        let code = "enable = \"..\"";
31        tcx.dcx()
32            .struct_span_err(span, msg)
33            .with_span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
34            .emit();
35    };
36    let rust_features = tcx.features();
37    let abi_feature_constraints = tcx.sess.target.abi_required_features();
38    for item in list {
39        // Only `enable = ...` is accepted in the meta-item list.
40        if !item.has_name(sym::enable) {
41            bad_item(item.span());
42            continue;
43        }
44
45        // Must be of the form `enable = "..."` (a string).
46        let Some(value) = item.value_str() else {
47            bad_item(item.span());
48            continue;
49        };
50
51        // We allow comma separation to enable multiple features.
52        for feature in value.as_str().split(',') {
53            let Some(stability) = rust_target_features.get(feature) else {
54                let msg = format!("the feature named `{feature}` is not valid for this target");
55                let mut err = tcx.dcx().struct_span_err(item.span(), msg);
56                err.span_label(item.span(), format!("`{feature}` is not valid for this target"));
57                if let Some(stripped) = feature.strip_prefix('+') {
58                    let valid = rust_target_features.contains_key(stripped);
59                    if valid {
60                        err.help("consider removing the leading `+` in the feature name");
61                    }
62                }
63                err.emit();
64                continue;
65            };
66
67            // Only allow target features whose feature gates have been enabled
68            // and which are permitted to be toggled.
69            if let Err(reason) = stability.toggle_allowed() {
70                tcx.dcx().emit_err(errors::ForbiddenTargetFeatureAttr {
71                    span: item.span(),
72                    feature,
73                    reason,
74                });
75            } else if let Some(nightly_feature) = stability.requires_nightly()
76                && !rust_features.enabled(nightly_feature)
77            {
78                feature_err(
79                    &tcx.sess,
80                    nightly_feature,
81                    item.span(),
82                    format!("the target feature `{feature}` is currently unstable"),
83                )
84                .emit();
85            } else {
86                // Add this and the implied features.
87                let feature_sym = Symbol::intern(feature);
88                for &name in tcx.implied_target_features(feature_sym) {
89                    // But ensure the ABI does not forbid enabling this.
90                    // Here we do assume that LLVM doesn't add even more implied features
91                    // we don't know about, at least no features that would have ABI effects!
92                    // We skip this logic in rustdoc, where we want to allow all target features of
93                    // all targets, so we can't check their ABI compatibility and anyway we are not
94                    // generating code so "it's fine".
95                    if !tcx.sess.opts.actually_rustdoc {
96                        if abi_feature_constraints.incompatible.contains(&name.as_str()) {
97                            // For "neon" specifically, we emit an FCW instead of a hard error.
98                            // See <https://github.com/rust-lang/rust/issues/134375>.
99                            if tcx.sess.target.arch == "aarch64" && name.as_str() == "neon" {
100                                tcx.emit_node_span_lint(
101                                    AARCH64_SOFTFLOAT_NEON,
102                                    tcx.local_def_id_to_hir_id(did),
103                                    item.span(),
104                                    errors::Aarch64SoftfloatNeon,
105                                );
106                            } else {
107                                tcx.dcx().emit_err(errors::ForbiddenTargetFeatureAttr {
108                                    span: item.span(),
109                                    feature: name.as_str(),
110                                    reason: "this feature is incompatible with the target ABI",
111                                });
112                            }
113                        }
114                    }
115                    target_features.push(TargetFeature { name, implied: name != feature_sym })
116                }
117            }
118        }
119    }
120}
121
122/// Computes the set of target features used in a function for the purposes of
123/// inline assembly.
124fn asm_target_features(tcx: TyCtxt<'_>, did: DefId) -> &FxIndexSet<Symbol> {
125    let mut target_features = tcx.sess.unstable_target_features.clone();
126    if tcx.def_kind(did).has_codegen_attrs() {
127        let attrs = tcx.codegen_fn_attrs(did);
128        target_features.extend(attrs.target_features.iter().map(|feature| feature.name));
129        match attrs.instruction_set {
130            None => {}
131            Some(InstructionSetAttr::ArmA32) => {
132                // FIXME(#120456) - is `swap_remove` correct?
133                target_features.swap_remove(&sym::thumb_mode);
134            }
135            Some(InstructionSetAttr::ArmT32) => {
136                target_features.insert(sym::thumb_mode);
137            }
138        }
139    }
140
141    tcx.arena.alloc(target_features)
142}
143
144/// Checks the function annotated with `#[target_feature]` is not a safe
145/// trait method implementation, reporting an error if it is.
146pub(crate) fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
147    if let DefKind::AssocFn = tcx.def_kind(id) {
148        let parent_id = tcx.local_parent(id);
149        if let DefKind::Trait | DefKind::Impl { of_trait: true } = tcx.def_kind(parent_id) {
150            tcx.dcx().emit_err(errors::TargetFeatureSafeTrait {
151                span: attr_span,
152                def: tcx.def_span(id),
153            });
154        }
155    }
156}
157
158pub(crate) fn provide(providers: &mut Providers) {
159    *providers = Providers {
160        rust_target_features: |tcx, cnum| {
161            assert_eq!(cnum, LOCAL_CRATE);
162            if tcx.sess.opts.actually_rustdoc {
163                // HACK: rustdoc would like to pretend that we have all the target features, so we
164                // have to merge all the lists into one. To ensure an unstable target never prevents
165                // a stable one from working, we merge the stability info of all instances of the
166                // same target feature name, with the "most stable" taking precedence. And then we
167                // hope that this doesn't cause issues anywhere else in the compiler...
168                let mut result: UnordMap<String, Stability> = Default::default();
169                for (name, stability) in rustc_target::target_features::all_rust_features() {
170                    use std::collections::hash_map::Entry;
171                    match result.entry(name.to_owned()) {
172                        Entry::Vacant(vacant_entry) => {
173                            vacant_entry.insert(stability);
174                        }
175                        Entry::Occupied(mut occupied_entry) => {
176                            // Merge the two stabilities, "more stable" taking precedence.
177                            match (occupied_entry.get(), stability) {
178                                (Stability::Stable, _)
179                                | (
180                                    Stability::Unstable { .. },
181                                    Stability::Unstable { .. } | Stability::Forbidden { .. },
182                                )
183                                | (Stability::Forbidden { .. }, Stability::Forbidden { .. }) => {
184                                    // The stability in the entry is at least as good as the new one, just keep it.
185                                }
186                                _ => {
187                                    // Overwrite stabilite.
188                                    occupied_entry.insert(stability);
189                                }
190                            }
191                        }
192                    }
193                }
194                result
195            } else {
196                tcx.sess
197                    .target
198                    .rust_target_features()
199                    .iter()
200                    .map(|(a, b, _)| (a.to_string(), *b))
201                    .collect()
202            }
203        },
204        implied_target_features: |tcx, feature: Symbol| {
205            let feature = feature.as_str();
206            UnordSet::from(tcx.sess.target.implied_target_features(feature))
207                .into_sorted_stable_ord()
208                .into_iter()
209                .map(|s| Symbol::intern(s))
210                .collect()
211        },
212        asm_target_features,
213        ..*providers
214    }
215}