Skip to content

Commit 95e2c91

Browse files
committed
Auto merge of rust-lang#132173 - veluca93:abi_checks, r=<try>
Emit warning when calling/declaring functions with unavailable vectors. On some architectures, vector types may have a different ABI depending on whether the relevant target features are enabled. (The ABI when the feature is disabled is often not specified, but LLVM implements some de-facto ABI.) As discussed in rust-lang/lang-team#235, this turns out to very easily lead to unsound code. This commit makes it a post-monomorphization future-incompat warning to declare or call functions using those vector types in a context in which the corresponding target features are disabled, if using an ABI for which the difference is relevant. This ensures that these functions are always called with a consistent ABI. See the [nomination comment](rust-lang#127731 (comment)) for more discussion. Part of rust-lang#116558 r? RalfJung
2 parents 4d88de2 + 75c873a commit 95e2c91

20 files changed

+488
-61
lines changed

compiler/rustc_lint_defs/src/builtin.rs

+67
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ declare_lint_pass! {
1616
/// that are used by other parts of the compiler.
1717
HardwiredLints => [
1818
// tidy-alphabetical-start
19+
ABI_UNSUPPORTED_VECTOR_TYPES,
1920
ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE,
2021
AMBIGUOUS_ASSOCIATED_ITEMS,
2122
AMBIGUOUS_GLOB_IMPORTS,
@@ -5031,3 +5032,69 @@ declare_lint! {
50315032
};
50325033
crate_level_only
50335034
}
5035+
5036+
declare_lint! {
5037+
/// The `abi_unsupported_vector_types` lint detects function definitions and calls
5038+
/// whose ABI depends on enabling certain target features, but those features are not enabled.
5039+
///
5040+
/// ### Example
5041+
///
5042+
/// ```rust,ignore (fails on non-x86_64)
5043+
/// extern "C" fn missing_target_feature(_: std::arch::x86_64::__m256) {
5044+
/// todo!()
5045+
/// }
5046+
///
5047+
/// #[target_feature(enable = "avx")]
5048+
/// unsafe extern "C" fn with_target_feature(_: std::arch::x86_64::__m256) {
5049+
/// todo!()
5050+
/// }
5051+
///
5052+
/// fn main() {
5053+
/// let v = unsafe { std::mem::zeroed() };
5054+
/// unsafe { with_target_feature(v); }
5055+
/// }
5056+
/// ```
5057+
///
5058+
/// ```text
5059+
/// warning: ABI error: this function call uses a avx vector type, which is not enabled in the caller
5060+
/// --> lint_example.rs:18:12
5061+
/// |
5062+
/// | unsafe { with_target_feature(v); }
5063+
/// | ^^^^^^^^^^^^^^^^^^^^^^ function called here
5064+
/// |
5065+
/// = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
5066+
/// = note: for more information, see issue #116558 <https://github.com/rust-lang/rust/issues/116558>
5067+
/// = help: consider enabling it globally (-C target-feature=+avx) or locally (#[target_feature(enable="avx")])
5068+
/// = note: `#[warn(abi_unsupported_vector_types)]` on by default
5069+
///
5070+
///
5071+
/// warning: ABI error: this function definition uses a avx vector type, which is not enabled
5072+
/// --> lint_example.rs:3:1
5073+
/// |
5074+
/// | pub extern "C" fn with_target_feature(_: std::arch::x86_64::__m256) {
5075+
/// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function defined here
5076+
/// |
5077+
/// = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
5078+
/// = note: for more information, see issue #116558 <https://github.com/rust-lang/rust/issues/116558>
5079+
/// = help: consider enabling it globally (-C target-feature=+avx) or locally (#[target_feature(enable="avx")])
5080+
/// ```
5081+
///
5082+
///
5083+
///
5084+
/// ### Explanation
5085+
///
5086+
/// The C ABI for `__m256` requires the value to be passed in an AVX register,
5087+
/// which is only possible when the `avx` target feature is enabled.
5088+
/// Therefore, `missing_target_feature` cannot be compiled without that target feature.
5089+
/// A similar (but complementary) message is triggered when `with_target_feature` is called
5090+
/// by a function that does not enable the `avx` target feature.
5091+
///
5092+
/// Note that this lint is very similar to the `-Wpsabi` warning in `gcc`/`clang`.
5093+
pub ABI_UNSUPPORTED_VECTOR_TYPES,
5094+
Warn,
5095+
"this function call or definition uses a vector type which is not enabled",
5096+
@future_incompatible = FutureIncompatibleInfo {
5097+
reason: FutureIncompatibilityReason::FutureReleaseErrorDontReportInDeps,
5098+
reference: "issue #116558 <https://github.com/rust-lang/rust/issues/116558>",
5099+
};
5100+
}

compiler/rustc_middle/src/query/keys.rs

+8
Original file line numberDiff line numberDiff line change
@@ -591,3 +591,11 @@ impl<'tcx> Key for (ValidityRequirement, ty::ParamEnvAnd<'tcx, Ty<'tcx>>) {
591591
}
592592
}
593593
}
594+
595+
impl<'tcx> Key for (Ty<'tcx>, ty::InstanceKind<'tcx>) {
596+
type Cache<V> = DefaultCache<Self, V>;
597+
598+
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
599+
self.1.default_span(tcx)
600+
}
601+
}

compiler/rustc_middle/src/query/mod.rs

+11
Original file line numberDiff line numberDiff line change
@@ -2299,6 +2299,17 @@ rustc_queries! {
22992299
desc { "whether the item should be made inlinable across crates" }
23002300
separate_provide_extern
23012301
}
2302+
2303+
query call_site_abi_missing_features(key: (Ty<'tcx>, ty::InstanceKind<'tcx>)) -> &'tcx Vec<String> {
2304+
arena_cache
2305+
desc { "missing features for ABI compatibility at call sites" }
2306+
cache_on_disk_if { true }
2307+
}
2308+
2309+
query check_instance_abi(key: ty::Instance<'tcx>) {
2310+
desc { "check ABI mismatch for instances" }
2311+
cache_on_disk_if { true }
2312+
}
23022313
}
23032314

23042315
rustc_query_append! { define_callbacks! }

compiler/rustc_monomorphize/messages.ftl

+9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
monomorphize_abi_error_disabled_vector_type_call =
2+
ABI error: this function call uses a vector type that requires the `{$required_feature}` target feature, which is not enabled in the caller
3+
.label = function called here
4+
.help = consider enabling it globally (`-C target-feature=+{$required_feature}`) or locally (`#[target_feature(enable="{$required_feature}")]`)
5+
monomorphize_abi_error_disabled_vector_type_def =
6+
ABI error: this function definition uses a vector type that requires the `{$required_feature}` target feature, which is not enabled
7+
.label = function defined here
8+
.help = consider enabling it globally (`-C target-feature=+{$required_feature}`) or locally (`#[target_feature(enable="{$required_feature}")]`)
9+
110
monomorphize_couldnt_dump_mono_stats =
211
unexpected error occurred while dumping monomorphization stats: {$error}
312

compiler/rustc_monomorphize/src/collector.rs

+6
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@
205205
//! this is not implemented however: a mono item will be produced
206206
//! regardless of whether it is actually needed or not.
207207
208+
mod abi_check;
208209
mod move_check;
209210

210211
use std::path::PathBuf;
@@ -766,6 +767,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> {
766767
self.used_mentioned_items.insert(MentionedItem::Fn(callee_ty));
767768
let callee_ty = self.monomorphize(callee_ty);
768769
self.check_fn_args_move_size(callee_ty, args, *fn_span, location);
770+
abi_check::check_call_site_abi(tcx, callee_ty, *fn_span, self.body.source.instance);
769771
visit_fn_use(self.tcx, callee_ty, true, source, &mut self.used_items)
770772
}
771773
mir::TerminatorKind::Drop { ref place, .. } => {
@@ -1207,6 +1209,9 @@ fn collect_items_of_instance<'tcx>(
12071209
mentioned_items: &mut MonoItems<'tcx>,
12081210
mode: CollectionMode,
12091211
) {
1212+
// Check the instance for feature-dependent ABI.
1213+
let _ = tcx.check_instance_abi(instance);
1214+
12101215
let body = tcx.instance_mir(instance.def);
12111216
// Naively, in "used" collection mode, all functions get added to *both* `used_items` and
12121217
// `mentioned_items`. Mentioned items processing will then notice that they have already been
@@ -1623,4 +1628,5 @@ pub(crate) fn collect_crate_mono_items<'tcx>(
16231628

16241629
pub(crate) fn provide(providers: &mut Providers) {
16251630
providers.hooks.should_codegen_locally = should_codegen_locally;
1631+
abi_check::provide(providers);
16261632
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
//! This module ensures that if a function's ABI requires a particular target feature,
2+
//! that target feature is enabled both on the callee and all callers.
3+
use rustc_hir::CRATE_HIR_ID;
4+
use rustc_middle::query::Providers;
5+
use rustc_middle::ty::{self, Instance, InstanceKind, ParamEnv, Ty, TyCtxt};
6+
use rustc_session::lint::builtin::ABI_UNSUPPORTED_VECTOR_TYPES;
7+
use rustc_span::def_id::DefId;
8+
use rustc_span::{DUMMY_SP, Span, Symbol};
9+
use rustc_target::abi::call::{FnAbi, PassMode};
10+
use rustc_target::abi::{Abi, RegKind};
11+
12+
use crate::errors::{AbiErrorDisabledVectorTypeCall, AbiErrorDisabledVectorTypeDef};
13+
14+
fn uses_vector_registers(mode: &PassMode, abi: &Abi) -> bool {
15+
match mode {
16+
PassMode::Ignore | PassMode::Indirect { .. } => false,
17+
PassMode::Cast { pad_i32: _, cast } => {
18+
cast.prefix.iter().any(|r| r.is_some_and(|x| x.kind == RegKind::Vector))
19+
|| cast.rest.unit.kind == RegKind::Vector
20+
}
21+
PassMode::Direct(..) | PassMode::Pair(..) => matches!(abi, Abi::Vector { .. }),
22+
}
23+
}
24+
25+
fn do_check_abi<'tcx>(
26+
tcx: TyCtxt<'tcx>,
27+
abi: &FnAbi<'tcx, Ty<'tcx>>,
28+
target_feature_def: DefId,
29+
mut emit_err: impl FnMut(&'static str),
30+
) {
31+
let Some(feature_def) = tcx.sess.target.features_for_correct_vector_abi() else {
32+
return;
33+
};
34+
let codegen_attrs = tcx.codegen_fn_attrs(target_feature_def);
35+
for arg_abi in abi.args.iter().chain(std::iter::once(&abi.ret)) {
36+
let size = arg_abi.layout.size;
37+
if uses_vector_registers(&arg_abi.mode, &arg_abi.layout.abi) {
38+
// Find the first feature that provides at least this vector size.
39+
let feature = match feature_def.iter().find(|(bits, _)| size.bits() <= *bits) {
40+
Some((_, feature)) => feature,
41+
None => {
42+
emit_err("<no available feature for this size>");
43+
continue;
44+
}
45+
};
46+
let feature_sym = Symbol::intern(feature);
47+
if !tcx.sess.unstable_target_features.contains(&feature_sym)
48+
&& !codegen_attrs.target_features.iter().any(|x| x.name == feature_sym)
49+
{
50+
emit_err(feature);
51+
}
52+
}
53+
}
54+
}
55+
56+
/// Checks that the ABI of a given instance of a function does not contain vector-passed arguments
57+
/// or return values for which the corresponding target feature is not enabled.
58+
fn check_instance_abi<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) {
59+
let param_env = ParamEnv::reveal_all();
60+
let Ok(abi) = tcx.fn_abi_of_instance(param_env.and((instance, ty::List::empty()))) else {
61+
// An error will be reported during codegen if we cannot determine the ABI of this
62+
// function.
63+
return;
64+
};
65+
do_check_abi(tcx, abi, instance.def_id(), |required_feature| {
66+
let span = tcx.def_span(instance.def_id());
67+
tcx.emit_node_span_lint(
68+
ABI_UNSUPPORTED_VECTOR_TYPES,
69+
CRATE_HIR_ID,
70+
span,
71+
AbiErrorDisabledVectorTypeDef { span, required_feature },
72+
);
73+
})
74+
}
75+
76+
fn call_site_abi_missing_features<'tcx>(
77+
tcx: TyCtxt<'tcx>,
78+
(ty, caller): (Ty<'tcx>, InstanceKind<'tcx>),
79+
) -> Vec<String> {
80+
let mut answer = vec![];
81+
let param_env = ParamEnv::reveal_all();
82+
let callee_abi = match *ty.kind() {
83+
ty::FnPtr(..) => tcx.fn_abi_of_fn_ptr(param_env.and((ty.fn_sig(tcx), ty::List::empty()))),
84+
ty::FnDef(def_id, args) => {
85+
// Intrinsics are handled separately by the compiler.
86+
if tcx.intrinsic(def_id).is_some() {
87+
return vec![];
88+
}
89+
let instance = ty::Instance::expect_resolve(tcx, param_env, def_id, args, DUMMY_SP);
90+
tcx.fn_abi_of_instance(param_env.and((instance, ty::List::empty())))
91+
}
92+
_ => {
93+
panic!("Invalid function call");
94+
}
95+
};
96+
97+
let Ok(callee_abi) = callee_abi else {
98+
// ABI failed to compute; this will not get through codegen.
99+
return vec![];
100+
};
101+
do_check_abi(tcx, callee_abi, caller.def_id(), |required_feature| {
102+
answer.push(required_feature.to_string());
103+
});
104+
answer
105+
}
106+
107+
/// Checks that a call expression does not try to pass a vector-passed argument which requires a
108+
/// target feature that the caller does not have, as doing so causes UB because of ABI mismatch.
109+
pub(super) fn check_call_site_abi<'tcx>(
110+
tcx: TyCtxt<'tcx>,
111+
ty: Ty<'tcx>,
112+
span: Span,
113+
caller: InstanceKind<'tcx>,
114+
) {
115+
for required_feature in tcx.call_site_abi_missing_features((ty, caller)) {
116+
tcx.emit_node_span_lint(
117+
ABI_UNSUPPORTED_VECTOR_TYPES,
118+
CRATE_HIR_ID,
119+
span,
120+
AbiErrorDisabledVectorTypeCall { span, required_feature },
121+
);
122+
}
123+
}
124+
125+
pub(super) fn provide(providers: &mut Providers) {
126+
*providers = Providers { check_instance_abi, call_site_abi_missing_features, ..*providers }
127+
}

compiler/rustc_monomorphize/src/errors.rs

+18
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,21 @@ pub(crate) struct StartNotFound;
9292
pub(crate) struct UnknownCguCollectionMode<'a> {
9393
pub mode: &'a str,
9494
}
95+
96+
#[derive(LintDiagnostic)]
97+
#[diag(monomorphize_abi_error_disabled_vector_type_def)]
98+
#[help]
99+
pub(crate) struct AbiErrorDisabledVectorTypeDef<'a> {
100+
#[label]
101+
pub span: Span,
102+
pub required_feature: &'a str,
103+
}
104+
105+
#[derive(LintDiagnostic)]
106+
#[diag(monomorphize_abi_error_disabled_vector_type_call)]
107+
#[help]
108+
pub(crate) struct AbiErrorDisabledVectorTypeCall<'a> {
109+
#[label]
110+
pub span: Span,
111+
pub required_feature: &'a str,
112+
}

compiler/rustc_target/src/target_features.rs

+17
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,13 @@ pub fn all_known_features() -> impl Iterator<Item = (&'static str, Stability)> {
522522
.map(|(f, s, _)| (f, s))
523523
}
524524

525+
// These arrays represent the least-constraining feature that is required for vector types up to a
526+
// certain size to have their "proper" ABI on each architecture.
527+
// Note that they must be kept sorted by vector size.
528+
const X86_FEATURES_FOR_CORRECT_VECTOR_ABI: &'static [(u64, &'static str)] =
529+
&[(128, "sse"), (256, "avx"), (512, "avx512f")];
530+
const AARCH64_FEATURES_FOR_CORRECT_VECTOR_ABI: &'static [(u64, &'static str)] = &[(128, "neon")];
531+
525532
impl super::spec::Target {
526533
pub fn supported_target_features(
527534
&self,
@@ -543,6 +550,16 @@ impl super::spec::Target {
543550
}
544551
}
545552

553+
// Returns None if we do not support ABI checks on the given target yet.
554+
pub fn features_for_correct_vector_abi(&self) -> Option<&'static [(u64, &'static str)]> {
555+
match &*self.arch {
556+
"x86" | "x86_64" => Some(X86_FEATURES_FOR_CORRECT_VECTOR_ABI),
557+
"aarch64" => Some(AARCH64_FEATURES_FOR_CORRECT_VECTOR_ABI),
558+
// FIXME: add support for non-tier1 architectures
559+
_ => None,
560+
}
561+
}
562+
546563
pub fn tied_target_features(&self) -> &'static [&'static [&'static str]] {
547564
match &*self.arch {
548565
"aarch64" | "arm64ec" => AARCH64_TIED_FEATURES,

tests/crashes/131342-2.rs

-40
This file was deleted.

tests/crashes/131342.rs

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
//@ known-bug: #131342
2-
// see also: 131342-2.rs
32

43
fn main() {
54
let mut items = vec![1, 2, 3, 4, 5].into_iter();

tests/ui/layout/post-mono-layout-cycle-2.rs

-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ where
4545
T: Blah,
4646
{
4747
async fn ice(&mut self) {
48-
//~^ ERROR a cycle occurred during layout computation
4948
let arr: [(); 0] = [];
5049
self.t.iter(arr.into_iter()).await;
5150
}

0 commit comments

Comments
 (0)