Skip to content

Commit 4656104

Browse files
Rollup merge of rust-lang#135408 - RalfJung:x86-sse2, r=workingjubilee
x86: make SSE2 required for i686 hardfloat targets and use it to pass SIMD types The primary goal of this is to make SSE2 *required* for our i686 targets (at least for the ones that use Pentium 4 as their baseline), to ensure they cannot be affected by rust-lang#114479. This has been MCPd in rust-lang/compiler-team#808, and is tracked in rust-lang#133611. We do this by defining a new ABI that these targets select, and making SSE2 required by the ABI (that's the first commit). That's kind of a hack, but (a) it is the easiest way to make a target feature required via the target spec, and (b) we actually *can* use SSE2 for the Rust ABI now that it is required, so the second commit goes ahead and does that. Specifically, we use it in two ways: to return `f64` values in a register rather than by-ptr, and to pass vectors of size up to 128bit in a register (or, well, whatever LLVM does when passing `<4 x float>` by-val, I don't actually know if this ends up in a register). Cc `@workingjubilee` Fixes rust-lang#133611
2 parents c26f1ab + a2fe644 commit 4656104

34 files changed

+300
-141
lines changed

compiler/rustc_target/src/callconv/mod.rs

+74-44
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_abi::{
88
use rustc_macros::HashStable_Generic;
99
use rustc_span::Symbol;
1010

11-
use crate::spec::{HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, WasmCAbi};
11+
use crate::spec::{HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, RustcAbi, WasmCAbi};
1212

1313
mod aarch64;
1414
mod amdgpu;
@@ -387,6 +387,7 @@ impl<'a, Ty> ArgAbi<'a, Ty> {
387387
/// Pass this argument directly instead. Should NOT be used!
388388
/// Only exists because of past ABI mistakes that will take time to fix
389389
/// (see <https://github.com/rust-lang/rust/issues/115666>).
390+
#[track_caller]
390391
pub fn make_direct_deprecated(&mut self) {
391392
match self.mode {
392393
PassMode::Indirect { .. } => {
@@ -399,6 +400,7 @@ impl<'a, Ty> ArgAbi<'a, Ty> {
399400

400401
/// Pass this argument indirectly, by passing a (thin or wide) pointer to the argument instead.
401402
/// This is valid for both sized and unsized arguments.
403+
#[track_caller]
402404
pub fn make_indirect(&mut self) {
403405
match self.mode {
404406
PassMode::Direct(_) | PassMode::Pair(_, _) => {
@@ -413,6 +415,7 @@ impl<'a, Ty> ArgAbi<'a, Ty> {
413415

414416
/// Same as `make_indirect`, but for arguments that are ignored. Only needed for ABIs that pass
415417
/// ZSTs indirectly.
418+
#[track_caller]
416419
pub fn make_indirect_from_ignore(&mut self) {
417420
match self.mode {
418421
PassMode::Ignore => {
@@ -736,27 +739,46 @@ impl<'a, Ty> FnAbi<'a, Ty> {
736739
C: HasDataLayout + HasTargetSpec,
737740
{
738741
let spec = cx.target_spec();
739-
match &spec.arch[..] {
742+
match &*spec.arch {
740743
"x86" => x86::compute_rust_abi_info(cx, self, abi),
741744
"riscv32" | "riscv64" => riscv::compute_rust_abi_info(cx, self, abi),
742745
"loongarch64" => loongarch::compute_rust_abi_info(cx, self, abi),
743746
"aarch64" => aarch64::compute_rust_abi_info(cx, self),
744747
_ => {}
745748
};
746749

750+
// Decides whether we can pass the given SIMD argument via `PassMode::Direct`.
751+
// May only return `true` if the target will always pass those arguments the same way,
752+
// no matter what the user does with `-Ctarget-feature`! In other words, whatever
753+
// target features are required to pass a SIMD value in registers must be listed in
754+
// the `abi_required_features` for the current target and ABI.
755+
let can_pass_simd_directly = |arg: &ArgAbi<'_, Ty>| match &*spec.arch {
756+
// On x86, if we have SSE2 (which we have by default for x86_64), we can always pass up
757+
// to 128-bit-sized vectors.
758+
"x86" if spec.rustc_abi == Some(RustcAbi::X86Sse2) => arg.layout.size.bits() <= 128,
759+
"x86_64" if spec.rustc_abi != Some(RustcAbi::X86Softfloat) => {
760+
arg.layout.size.bits() <= 128
761+
}
762+
// So far, we haven't implemented this logic for any other target.
763+
_ => false,
764+
};
765+
747766
for (arg_idx, arg) in self
748767
.args
749768
.iter_mut()
750769
.enumerate()
751770
.map(|(idx, arg)| (Some(idx), arg))
752771
.chain(iter::once((None, &mut self.ret)))
753772
{
754-
if arg.is_ignore() {
773+
// If the logic above already picked a specific type to cast the argument to, leave that
774+
// in place.
775+
if matches!(arg.mode, PassMode::Ignore | PassMode::Cast { .. }) {
755776
continue;
756777
}
757778

758779
if arg_idx.is_none()
759780
&& arg.layout.size > Primitive::Pointer(AddressSpace::DATA).size(cx) * 2
781+
&& !matches!(arg.layout.backend_repr, BackendRepr::Vector { .. })
760782
{
761783
// Return values larger than 2 registers using a return area
762784
// pointer. LLVM and Cranelift disagree about how to return
@@ -766,7 +788,8 @@ impl<'a, Ty> FnAbi<'a, Ty> {
766788
// return value independently and decide to pass it in a
767789
// register or not, which would result in the return value
768790
// being passed partially in registers and partially through a
769-
// return area pointer.
791+
// return area pointer. For large IR-level values such as `i128`,
792+
// cranelift will even split up the value into smaller chunks.
770793
//
771794
// While Cranelift may need to be fixed as the LLVM behavior is
772795
// generally more correct with respect to the surface language,
@@ -796,53 +819,60 @@ impl<'a, Ty> FnAbi<'a, Ty> {
796819
// rustc_target already ensure any return value which doesn't
797820
// fit in the available amount of return registers is passed in
798821
// the right way for the current target.
822+
//
823+
// The adjustment is not necessary nor desired for types with a vector
824+
// representation; those are handled below.
799825
arg.make_indirect();
800826
continue;
801827
}
802828

803829
match arg.layout.backend_repr {
804-
BackendRepr::Memory { .. } => {}
805-
806-
// This is a fun case! The gist of what this is doing is
807-
// that we want callers and callees to always agree on the
808-
// ABI of how they pass SIMD arguments. If we were to *not*
809-
// make these arguments indirect then they'd be immediates
810-
// in LLVM, which means that they'd used whatever the
811-
// appropriate ABI is for the callee and the caller. That
812-
// means, for example, if the caller doesn't have AVX
813-
// enabled but the callee does, then passing an AVX argument
814-
// across this boundary would cause corrupt data to show up.
815-
//
816-
// This problem is fixed by unconditionally passing SIMD
817-
// arguments through memory between callers and callees
818-
// which should get them all to agree on ABI regardless of
819-
// target feature sets. Some more information about this
820-
// issue can be found in #44367.
821-
//
822-
// Note that the intrinsic ABI is exempt here as
823-
// that's how we connect up to LLVM and it's unstable
824-
// anyway, we control all calls to it in libstd.
825-
BackendRepr::Vector { .. }
826-
if abi != ExternAbi::RustIntrinsic && spec.simd_types_indirect =>
827-
{
828-
arg.make_indirect();
829-
continue;
830+
BackendRepr::Memory { .. } => {
831+
// Compute `Aggregate` ABI.
832+
833+
let is_indirect_not_on_stack =
834+
matches!(arg.mode, PassMode::Indirect { on_stack: false, .. });
835+
assert!(is_indirect_not_on_stack);
836+
837+
let size = arg.layout.size;
838+
if arg.layout.is_sized()
839+
&& size <= Primitive::Pointer(AddressSpace::DATA).size(cx)
840+
{
841+
// We want to pass small aggregates as immediates, but using
842+
// an LLVM aggregate type for this leads to bad optimizations,
843+
// so we pick an appropriately sized integer type instead.
844+
arg.cast_to(Reg { kind: RegKind::Integer, size });
845+
}
830846
}
831847

832-
_ => continue,
833-
}
834-
// Compute `Aggregate` ABI.
835-
836-
let is_indirect_not_on_stack =
837-
matches!(arg.mode, PassMode::Indirect { on_stack: false, .. });
838-
assert!(is_indirect_not_on_stack);
839-
840-
let size = arg.layout.size;
841-
if !arg.layout.is_unsized() && size <= Primitive::Pointer(AddressSpace::DATA).size(cx) {
842-
// We want to pass small aggregates as immediates, but using
843-
// an LLVM aggregate type for this leads to bad optimizations,
844-
// so we pick an appropriately sized integer type instead.
845-
arg.cast_to(Reg { kind: RegKind::Integer, size });
848+
BackendRepr::Vector { .. } => {
849+
// This is a fun case! The gist of what this is doing is
850+
// that we want callers and callees to always agree on the
851+
// ABI of how they pass SIMD arguments. If we were to *not*
852+
// make these arguments indirect then they'd be immediates
853+
// in LLVM, which means that they'd used whatever the
854+
// appropriate ABI is for the callee and the caller. That
855+
// means, for example, if the caller doesn't have AVX
856+
// enabled but the callee does, then passing an AVX argument
857+
// across this boundary would cause corrupt data to show up.
858+
//
859+
// This problem is fixed by unconditionally passing SIMD
860+
// arguments through memory between callers and callees
861+
// which should get them all to agree on ABI regardless of
862+
// target feature sets. Some more information about this
863+
// issue can be found in #44367.
864+
//
865+
// Note that the intrinsic ABI is exempt here as those are not
866+
// real functions anyway, and the backend expects very specific types.
867+
if abi != ExternAbi::RustIntrinsic
868+
&& spec.simd_types_indirect
869+
&& !can_pass_simd_directly(arg)
870+
{
871+
arg.make_indirect();
872+
}
873+
}
874+
875+
_ => {}
846876
}
847877
}
848878
}

compiler/rustc_target/src/callconv/x86.rs

+11-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_abi::{
44
};
55

66
use crate::callconv::{ArgAttribute, FnAbi, PassMode};
7-
use crate::spec::HasTargetSpec;
7+
use crate::spec::{HasTargetSpec, RustcAbi};
88

99
#[derive(PartialEq)]
1010
pub(crate) enum Flavor {
@@ -236,8 +236,16 @@ where
236236
_ => false, // anyway not passed via registers on x86
237237
};
238238
if has_float {
239-
if fn_abi.ret.layout.size <= Primitive::Pointer(AddressSpace::DATA).size(cx) {
240-
// Same size or smaller than pointer, return in a register.
239+
if cx.target_spec().rustc_abi == Some(RustcAbi::X86Sse2)
240+
&& fn_abi.ret.layout.backend_repr.is_scalar()
241+
&& fn_abi.ret.layout.size.bits() <= 128
242+
{
243+
// This is a single scalar that fits into an SSE register, and the target uses the
244+
// SSE ABI. We prefer this over integer registers as float scalars need to be in SSE
245+
// registers for float operations, so that's the best place to pass them around.
246+
fn_abi.ret.cast_to(Reg { kind: RegKind::Vector, size: fn_abi.ret.layout.size });
247+
} else if fn_abi.ret.layout.size <= Primitive::Pointer(AddressSpace::DATA).size(cx) {
248+
// Same size or smaller than pointer, return in an integer register.
241249
fn_abi.ret.cast_to(Reg { kind: RegKind::Integer, size: fn_abi.ret.layout.size });
242250
} else {
243251
// Larger than a pointer, return indirectly.

compiler/rustc_target/src/spec/base/apple/mod.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ use std::borrow::Cow;
22
use std::env;
33

44
use crate::spec::{
5-
Cc, DebuginfoKind, FloatAbi, FramePointer, LinkerFlavor, Lld, SplitDebuginfo, StackProbeType,
6-
StaticCow, TargetOptions, cvs,
5+
Cc, DebuginfoKind, FloatAbi, FramePointer, LinkerFlavor, Lld, RustcAbi, SplitDebuginfo,
6+
StackProbeType, StaticCow, TargetOptions, cvs,
77
};
88

99
#[cfg(test)]
@@ -103,7 +103,7 @@ pub(crate) fn base(
103103
arch: Arch,
104104
abi: TargetAbi,
105105
) -> (TargetOptions, StaticCow<str>, StaticCow<str>) {
106-
let opts = TargetOptions {
106+
let mut opts = TargetOptions {
107107
abi: abi.target_abi().into(),
108108
llvm_floatabi: Some(FloatAbi::Hard),
109109
os: os.into(),
@@ -154,6 +154,10 @@ pub(crate) fn base(
154154

155155
..Default::default()
156156
};
157+
if matches!(arch, Arch::I386 | Arch::I686) {
158+
// All Apple x86-32 targets have SSE2.
159+
opts.rustc_abi = Some(RustcAbi::X86Sse2);
160+
}
157161
(opts, unversioned_llvm_target(os, arch, abi), arch.target_arch())
158162
}
159163

compiler/rustc_target/src/spec/mod.rs

+9
Original file line numberDiff line numberDiff line change
@@ -1116,6 +1116,8 @@ impl ToJson for FloatAbi {
11161116
/// The Rustc-specific variant of the ABI used for this target.
11171117
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
11181118
pub enum RustcAbi {
1119+
/// On x86-32 only: make use of SSE and SSE2 for ABI purposes.
1120+
X86Sse2,
11191121
/// On x86-32/64 only: do not use any FPU or SIMD registers for the ABI.
11201122
X86Softfloat,
11211123
}
@@ -1125,6 +1127,7 @@ impl FromStr for RustcAbi {
11251127

11261128
fn from_str(s: &str) -> Result<RustcAbi, ()> {
11271129
Ok(match s {
1130+
"x86-sse2" => RustcAbi::X86Sse2,
11281131
"x86-softfloat" => RustcAbi::X86Softfloat,
11291132
_ => return Err(()),
11301133
})
@@ -1134,6 +1137,7 @@ impl FromStr for RustcAbi {
11341137
impl ToJson for RustcAbi {
11351138
fn to_json(&self) -> Json {
11361139
match *self {
1140+
RustcAbi::X86Sse2 => "x86-sse2",
11371141
RustcAbi::X86Softfloat => "x86-softfloat",
11381142
}
11391143
.to_json()
@@ -3270,6 +3274,11 @@ impl Target {
32703274
// Check consistency of Rust ABI declaration.
32713275
if let Some(rust_abi) = self.rustc_abi {
32723276
match rust_abi {
3277+
RustcAbi::X86Sse2 => check_matches!(
3278+
&*self.arch,
3279+
"x86",
3280+
"`x86-sse2` ABI is only valid for x86-32 targets"
3281+
),
32733282
RustcAbi::X86Softfloat => check_matches!(
32743283
&*self.arch,
32753284
"x86" | "x86_64",

compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::spec::base::nto_qnx;
2-
use crate::spec::{StackProbeType, Target, TargetOptions, base};
2+
use crate::spec::{RustcAbi, StackProbeType, Target, TargetOptions, base};
33

44
pub(crate) fn target() -> Target {
55
let mut meta = nto_qnx::meta();
@@ -14,6 +14,7 @@ pub(crate) fn target() -> Target {
1414
.into(),
1515
arch: "x86".into(),
1616
options: TargetOptions {
17+
rustc_abi: Some(RustcAbi::X86Sse2),
1718
cpu: "pentium4".into(),
1819
max_atomic_width: Some(64),
1920
pre_link_args: nto_qnx::pre_link_args(

compiler/rustc_target/src/spec/targets/i586_unknown_linux_gnu.rs

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use crate::spec::Target;
22

33
pub(crate) fn target() -> Target {
44
let mut base = super::i686_unknown_linux_gnu::target();
5+
base.rustc_abi = None; // overwrite the SSE2 ABI set by the base target
56
base.cpu = "pentium".into();
67
base.llvm_target = "i586-unknown-linux-gnu".into();
78
base

compiler/rustc_target/src/spec/targets/i586_unknown_linux_musl.rs

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use crate::spec::Target;
22

33
pub(crate) fn target() -> Target {
44
let mut base = super::i686_unknown_linux_musl::target();
5+
base.rustc_abi = None; // overwrite the SSE2 ABI set by the base target
56
base.cpu = "pentium".into();
67
base.llvm_target = "i586-unknown-linux-musl".into();
78
// FIXME(compiler-team#422): musl targets should be dynamically linked by default.

compiler/rustc_target/src/spec/targets/i686_linux_android.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base};
1+
use crate::spec::{RustcAbi, SanitizerSet, StackProbeType, Target, TargetOptions, base};
22

33
// See https://developer.android.com/ndk/guides/abis.html#x86
44
// for target ABI requirements.
@@ -8,6 +8,7 @@ pub(crate) fn target() -> Target {
88

99
base.max_atomic_width = Some(64);
1010

11+
base.rustc_abi = Some(RustcAbi::X86Sse2);
1112
// https://developer.android.com/ndk/guides/abis.html#x86
1213
base.cpu = "pentiumpro".into();
1314
base.features = "+mmx,+sse,+sse2,+sse3,+ssse3".into();

compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base};
1+
use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, RustcAbi, Target, base};
22

33
pub(crate) fn target() -> Target {
44
let mut base = base::windows_gnu::opts();
5+
base.rustc_abi = Some(RustcAbi::X86Sse2);
56
base.cpu = "pentium4".into();
67
base.max_atomic_width = Some(64);
78
base.frame_pointer = FramePointer::Always; // Required for backtraces

compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base};
1+
use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, RustcAbi, Target, base};
22

33
pub(crate) fn target() -> Target {
44
let mut base = base::windows_gnullvm::opts();
5+
base.rustc_abi = Some(RustcAbi::X86Sse2);
56
base.cpu = "pentium4".into();
67
base.max_atomic_width = Some(64);
78
base.frame_pointer = FramePointer::Always; // Required for backtraces

compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
use crate::spec::{LinkerFlavor, Lld, SanitizerSet, Target, base};
1+
use crate::spec::{LinkerFlavor, Lld, RustcAbi, SanitizerSet, Target, base};
22

33
pub(crate) fn target() -> Target {
44
let mut base = base::windows_msvc::opts();
5+
base.rustc_abi = Some(RustcAbi::X86Sse2);
56
base.cpu = "pentium4".into();
67
base.max_atomic_width = Some(64);
78
base.supported_sanitizers = SanitizerSet::ADDRESS;

compiler/rustc_target/src/spec/targets/i686_unknown_freebsd.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base};
1+
use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, base};
22

33
pub(crate) fn target() -> Target {
44
let mut base = base::freebsd::opts();
5+
base.rustc_abi = Some(RustcAbi::X86Sse2);
56
base.cpu = "pentium4".into();
67
base.max_atomic_width = Some(64);
78
base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32", "-Wl,-znotext"]);

compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base};
1+
use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, base};
22

33
pub(crate) fn target() -> Target {
44
let mut base = base::haiku::opts();
5+
base.rustc_abi = Some(RustcAbi::X86Sse2);
56
base.cpu = "pentium4".into();
67
base.max_atomic_width = Some(64);
78
base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32"]);

0 commit comments

Comments
 (0)