Skip to content

Commit

Permalink
Auto merge of rust-lang#135408 - RalfJung:x86-sse2, r=<try>
Browse files Browse the repository at this point in the history
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

try-job: aarch64-apple
try-job: aarch64-gnu
try-job: aarch64-gnu-debug
try-job: test-various
  • Loading branch information
bors committed Feb 10, 2025
2 parents 4bb6ec0 + f4966f0 commit 1779e76
Show file tree
Hide file tree
Showing 34 changed files with 309 additions and 141 deletions.
118 changes: 74 additions & 44 deletions compiler/rustc_target/src/callconv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use rustc_abi::{
use rustc_macros::HashStable_Generic;
use rustc_span::Symbol;

use crate::spec::{HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, WasmCAbi};
use crate::spec::{HasTargetSpec, HasWasmCAbiOpt, HasX86AbiOpt, RustcAbi, WasmCAbi};

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

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

/// Same as `make_indirect`, but for arguments that are ignored. Only needed for ABIs that pass
/// ZSTs indirectly.
#[track_caller]
pub fn make_indirect_from_ignore(&mut self) {
match self.mode {
PassMode::Ignore => {
Expand Down Expand Up @@ -736,27 +739,46 @@ impl<'a, Ty> FnAbi<'a, Ty> {
C: HasDataLayout + HasTargetSpec,
{
let spec = cx.target_spec();
match &spec.arch[..] {
match &*spec.arch {
"x86" => x86::compute_rust_abi_info(cx, self, abi),
"riscv32" | "riscv64" => riscv::compute_rust_abi_info(cx, self, abi),
"loongarch64" => loongarch::compute_rust_abi_info(cx, self, abi),
"aarch64" => aarch64::compute_rust_abi_info(cx, self),
_ => {}
};

// Decides whether we can pass the given SIMD argument via `PassMode::Direct`.
// May only return `true` if the target will always pass those arguments the same way,
// no matter what the user does with `-Ctarget-feature`! In other words, whatever
// target features are required to pass a SIMD value in registers must be listed in
// the `abi_required_features` for the current target and ABI.
let can_pass_simd_directly = |arg: &ArgAbi<'_, Ty>| match &*spec.arch {
// On x86, if we have SSE2 (which we have by default for x86_64), we can always pass up
// to 128-bit-sized vectors.
"x86" if spec.rustc_abi == Some(RustcAbi::X86Sse2) => arg.layout.size.bits() <= 128,
"x86_64" if spec.rustc_abi != Some(RustcAbi::X86Softfloat) => {
arg.layout.size.bits() <= 128
}
// So far, we haven't implemented this logic for any other target.
_ => false,
};

for (arg_idx, arg) in self
.args
.iter_mut()
.enumerate()
.map(|(idx, arg)| (Some(idx), arg))
.chain(iter::once((None, &mut self.ret)))
{
if arg.is_ignore() {
// If the logic above already picked a specific type to cast the argument to, leave that
// in place.
if matches!(arg.mode, PassMode::Ignore | PassMode::Cast { .. }) {
continue;
}

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

match arg.layout.backend_repr {
BackendRepr::Memory { .. } => {}

// This is a fun case! The gist of what this is doing is
// that we want callers and callees to always agree on the
// ABI of how they pass SIMD arguments. If we were to *not*
// make these arguments indirect then they'd be immediates
// in LLVM, which means that they'd used whatever the
// appropriate ABI is for the callee and the caller. That
// means, for example, if the caller doesn't have AVX
// enabled but the callee does, then passing an AVX argument
// across this boundary would cause corrupt data to show up.
//
// This problem is fixed by unconditionally passing SIMD
// arguments through memory between callers and callees
// which should get them all to agree on ABI regardless of
// target feature sets. Some more information about this
// issue can be found in #44367.
//
// Note that the intrinsic ABI is exempt here as
// that's how we connect up to LLVM and it's unstable
// anyway, we control all calls to it in libstd.
BackendRepr::Vector { .. }
if abi != ExternAbi::RustIntrinsic && spec.simd_types_indirect =>
{
arg.make_indirect();
continue;
BackendRepr::Memory { .. } => {
// Compute `Aggregate` ABI.

let is_indirect_not_on_stack =
matches!(arg.mode, PassMode::Indirect { on_stack: false, .. });
assert!(is_indirect_not_on_stack);

let size = arg.layout.size;
if arg.layout.is_sized()
&& size <= Primitive::Pointer(AddressSpace::DATA).size(cx)
{
// We want to pass small aggregates as immediates, but using
// an LLVM aggregate type for this leads to bad optimizations,
// so we pick an appropriately sized integer type instead.
arg.cast_to(Reg { kind: RegKind::Integer, size });
}
}

_ => continue,
}
// Compute `Aggregate` ABI.

let is_indirect_not_on_stack =
matches!(arg.mode, PassMode::Indirect { on_stack: false, .. });
assert!(is_indirect_not_on_stack);

let size = arg.layout.size;
if !arg.layout.is_unsized() && size <= Primitive::Pointer(AddressSpace::DATA).size(cx) {
// We want to pass small aggregates as immediates, but using
// an LLVM aggregate type for this leads to bad optimizations,
// so we pick an appropriately sized integer type instead.
arg.cast_to(Reg { kind: RegKind::Integer, size });
BackendRepr::Vector { .. } => {
// This is a fun case! The gist of what this is doing is
// that we want callers and callees to always agree on the
// ABI of how they pass SIMD arguments. If we were to *not*
// make these arguments indirect then they'd be immediates
// in LLVM, which means that they'd used whatever the
// appropriate ABI is for the callee and the caller. That
// means, for example, if the caller doesn't have AVX
// enabled but the callee does, then passing an AVX argument
// across this boundary would cause corrupt data to show up.
//
// This problem is fixed by unconditionally passing SIMD
// arguments through memory between callers and callees
// which should get them all to agree on ABI regardless of
// target feature sets. Some more information about this
// issue can be found in #44367.
//
// Note that the intrinsic ABI is exempt here as those are not
// real functions anyway, and the backend expects very specific types.
if abi != ExternAbi::RustIntrinsic
&& spec.simd_types_indirect
&& !can_pass_simd_directly(arg)
{
arg.make_indirect();
}
}

_ => {}
}
}
}
Expand Down
14 changes: 11 additions & 3 deletions compiler/rustc_target/src/callconv/x86.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rustc_abi::{
};

use crate::callconv::{ArgAttribute, FnAbi, PassMode};
use crate::spec::HasTargetSpec;
use crate::spec::{HasTargetSpec, RustcAbi};

#[derive(PartialEq)]
pub(crate) enum Flavor {
Expand Down Expand Up @@ -236,8 +236,16 @@ where
_ => false, // anyway not passed via registers on x86
};
if has_float {
if fn_abi.ret.layout.size <= Primitive::Pointer(AddressSpace::DATA).size(cx) {
// Same size or smaller than pointer, return in a register.
if cx.target_spec().rustc_abi == Some(RustcAbi::X86Sse2)
&& fn_abi.ret.layout.backend_repr.is_scalar()
&& fn_abi.ret.layout.size.bits() <= 128
{
// This is a single scalar that fits into an SSE register, and the target uses the
// SSE ABI. We prefer this over integer registers as float scalars need to be in SSE
// registers for float operations, so that's the best place to pass them around.
fn_abi.ret.cast_to(Reg { kind: RegKind::Vector, size: fn_abi.ret.layout.size });
} else if fn_abi.ret.layout.size <= Primitive::Pointer(AddressSpace::DATA).size(cx) {
// Same size or smaller than pointer, return in an integer register.
fn_abi.ret.cast_to(Reg { kind: RegKind::Integer, size: fn_abi.ret.layout.size });
} else {
// Larger than a pointer, return indirectly.
Expand Down
10 changes: 7 additions & 3 deletions compiler/rustc_target/src/spec/base/apple/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use std::borrow::Cow;
use std::env;

use crate::spec::{
Cc, DebuginfoKind, FloatAbi, FramePointer, LinkerFlavor, Lld, SplitDebuginfo, StackProbeType,
StaticCow, TargetOptions, cvs,
Cc, DebuginfoKind, FloatAbi, FramePointer, LinkerFlavor, Lld, RustcAbi, SplitDebuginfo,
StackProbeType, StaticCow, TargetOptions, cvs,
};

#[cfg(test)]
Expand Down Expand Up @@ -103,7 +103,7 @@ pub(crate) fn base(
arch: Arch,
abi: TargetAbi,
) -> (TargetOptions, StaticCow<str>, StaticCow<str>) {
let opts = TargetOptions {
let mut opts = TargetOptions {
abi: abi.target_abi().into(),
llvm_floatabi: Some(FloatAbi::Hard),
os: os.into(),
Expand Down Expand Up @@ -154,6 +154,10 @@ pub(crate) fn base(

..Default::default()
};
if matches!(arch, Arch::I386 | Arch::I686) {
// All Apple x86-32 targets have SSE2.
opts.rustc_abi = Some(RustcAbi::X86Sse2);
}
(opts, unversioned_llvm_target(os, arch, abi), arch.target_arch())
}

Expand Down
9 changes: 9 additions & 0 deletions compiler/rustc_target/src/spec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1116,6 +1116,8 @@ impl ToJson for FloatAbi {
/// The Rustc-specific variant of the ABI used for this target.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum RustcAbi {
/// On x86-32 only: make use of SSE and SSE2 for ABI purposes.
X86Sse2,
/// On x86-32/64 only: do not use any FPU or SIMD registers for the ABI.
X86Softfloat,
}
Expand All @@ -1125,6 +1127,7 @@ impl FromStr for RustcAbi {

fn from_str(s: &str) -> Result<RustcAbi, ()> {
Ok(match s {
"x86-sse2" => RustcAbi::X86Sse2,
"x86-softfloat" => RustcAbi::X86Softfloat,
_ => return Err(()),
})
Expand All @@ -1134,6 +1137,7 @@ impl FromStr for RustcAbi {
impl ToJson for RustcAbi {
fn to_json(&self) -> Json {
match *self {
RustcAbi::X86Sse2 => "x86-sse2",
RustcAbi::X86Softfloat => "x86-softfloat",
}
.to_json()
Expand Down Expand Up @@ -3270,6 +3274,11 @@ impl Target {
// Check consistency of Rust ABI declaration.
if let Some(rust_abi) = self.rustc_abi {
match rust_abi {
RustcAbi::X86Sse2 => check_matches!(
&*self.arch,
"x86",
"`x86-sse2` ABI is only valid for x86-32 targets"
),
RustcAbi::X86Softfloat => check_matches!(
&*self.arch,
"x86" | "x86_64",
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::spec::base::nto_qnx;
use crate::spec::{StackProbeType, Target, TargetOptions, base};
use crate::spec::{RustcAbi, StackProbeType, Target, TargetOptions, base};

pub(crate) fn target() -> Target {
let mut meta = nto_qnx::meta();
Expand All @@ -14,6 +14,7 @@ pub(crate) fn target() -> Target {
.into(),
arch: "x86".into(),
options: TargetOptions {
rustc_abi: Some(RustcAbi::X86Sse2),
cpu: "pentium4".into(),
max_atomic_width: Some(64),
pre_link_args: nto_qnx::pre_link_args(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::spec::Target;

pub(crate) fn target() -> Target {
let mut base = super::i686_unknown_linux_gnu::target();
base.rustc_abi = None; // overwrite the SSE2 ABI set by the base target
base.cpu = "pentium".into();
base.llvm_target = "i586-unknown-linux-gnu".into();
base
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::spec::Target;

pub(crate) fn target() -> Target {
let mut base = super::i686_unknown_linux_musl::target();
base.rustc_abi = None; // overwrite the SSE2 ABI set by the base target
base.cpu = "pentium".into();
base.llvm_target = "i586-unknown-linux-musl".into();
// FIXME(compiler-team#422): musl targets should be dynamically linked by default.
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_target/src/spec/targets/i686_linux_android.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base};
use crate::spec::{RustcAbi, SanitizerSet, StackProbeType, Target, TargetOptions, base};

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

base.max_atomic_width = Some(64);

base.rustc_abi = Some(RustcAbi::X86Sse2);
// https://developer.android.com/ndk/guides/abis.html#x86
base.cpu = "pentiumpro".into();
base.features = "+mmx,+sse,+sse2,+sse3,+ssse3".into();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base};
use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, RustcAbi, Target, base};

pub(crate) fn target() -> Target {
let mut base = base::windows_gnu::opts();
base.rustc_abi = Some(RustcAbi::X86Sse2);
base.cpu = "pentium4".into();
base.max_atomic_width = Some(64);
base.frame_pointer = FramePointer::Always; // Required for backtraces
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base};
use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, RustcAbi, Target, base};

pub(crate) fn target() -> Target {
let mut base = base::windows_gnullvm::opts();
base.rustc_abi = Some(RustcAbi::X86Sse2);
base.cpu = "pentium4".into();
base.max_atomic_width = Some(64);
base.frame_pointer = FramePointer::Always; // Required for backtraces
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::spec::{LinkerFlavor, Lld, SanitizerSet, Target, base};
use crate::spec::{LinkerFlavor, Lld, RustcAbi, SanitizerSet, Target, base};

pub(crate) fn target() -> Target {
let mut base = base::windows_msvc::opts();
base.rustc_abi = Some(RustcAbi::X86Sse2);
base.cpu = "pentium4".into();
base.max_atomic_width = Some(64);
base.supported_sanitizers = SanitizerSet::ADDRESS;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base};
use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, base};

pub(crate) fn target() -> Target {
let mut base = base::freebsd::opts();
base.rustc_abi = Some(RustcAbi::X86Sse2);
base.cpu = "pentium4".into();
base.max_atomic_width = Some(64);
base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m32", "-Wl,-znotext"]);
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base};
use crate::spec::{Cc, LinkerFlavor, Lld, RustcAbi, StackProbeType, Target, base};

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

0 comments on commit 1779e76

Please # to comment.