miri/shims/x86/
sse.rs

1use rustc_apfloat::ieee::Single;
2use rustc_middle::ty::Ty;
3use rustc_span::Symbol;
4use rustc_target::callconv::{Conv, FnAbi};
5
6use super::{
7    FloatBinOp, FloatUnaryOp, bin_op_simd_float_all, bin_op_simd_float_first, unary_op_ps,
8    unary_op_ss,
9};
10use crate::*;
11
12impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
13pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
14    fn emulate_x86_sse_intrinsic(
15        &mut self,
16        link_name: Symbol,
17        abi: &FnAbi<'tcx, Ty<'tcx>>,
18        args: &[OpTy<'tcx>],
19        dest: &MPlaceTy<'tcx>,
20    ) -> InterpResult<'tcx, EmulateItemResult> {
21        let this = self.eval_context_mut();
22        this.expect_target_feature_for_intrinsic(link_name, "sse")?;
23        // Prefix should have already been checked.
24        let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.sse.").unwrap();
25        // All these intrinsics operate on 128-bit (f32x4) SIMD vectors unless stated otherwise.
26        // Many intrinsic names are sufixed with "ps" (packed single) or "ss" (scalar single),
27        // where single means single precision floating point (f32). "ps" means thet the operation
28        // is performed on each element of the vector, while "ss" means that the operation is
29        // performed only on the first element, copying the remaining elements from the input
30        // vector (for binary operations, from the left-hand side).
31        match unprefixed_name {
32            // Used to implement _mm_{min,max}_ss functions.
33            // Performs the operations on the first component of `left` and
34            // `right` and copies the remaining components from `left`.
35            "min.ss" | "max.ss" => {
36                let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
37
38                let which = match unprefixed_name {
39                    "min.ss" => FloatBinOp::Min,
40                    "max.ss" => FloatBinOp::Max,
41                    _ => unreachable!(),
42                };
43
44                bin_op_simd_float_first::<Single>(this, which, left, right, dest)?;
45            }
46            // Used to implement _mm_min_ps and _mm_max_ps functions.
47            // Note that the semantics are a bit different from Rust simd_min
48            // and simd_max intrinsics regarding handling of NaN and -0.0: Rust
49            // matches the IEEE min/max operations, while x86 has different
50            // semantics.
51            "min.ps" | "max.ps" => {
52                let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
53
54                let which = match unprefixed_name {
55                    "min.ps" => FloatBinOp::Min,
56                    "max.ps" => FloatBinOp::Max,
57                    _ => unreachable!(),
58                };
59
60                bin_op_simd_float_all::<Single>(this, which, left, right, dest)?;
61            }
62            // Used to implement _mm_{rcp,rsqrt}_ss functions.
63            // Performs the operations on the first component of `op` and
64            // copies the remaining components from `op`.
65            "rcp.ss" | "rsqrt.ss" => {
66                let [op] = this.check_shim(abi, Conv::C, link_name, args)?;
67
68                let which = match unprefixed_name {
69                    "rcp.ss" => FloatUnaryOp::Rcp,
70                    "rsqrt.ss" => FloatUnaryOp::Rsqrt,
71                    _ => unreachable!(),
72                };
73
74                unary_op_ss(this, which, op, dest)?;
75            }
76            // Used to implement _mm_{sqrt,rcp,rsqrt}_ps functions.
77            // Performs the operations on all components of `op`.
78            "rcp.ps" | "rsqrt.ps" => {
79                let [op] = this.check_shim(abi, Conv::C, link_name, args)?;
80
81                let which = match unprefixed_name {
82                    "rcp.ps" => FloatUnaryOp::Rcp,
83                    "rsqrt.ps" => FloatUnaryOp::Rsqrt,
84                    _ => unreachable!(),
85                };
86
87                unary_op_ps(this, which, op, dest)?;
88            }
89            // Used to implement the _mm_cmp*_ss functions.
90            // Performs a comparison operation on the first component of `left`
91            // and `right`, returning 0 if false or `u32::MAX` if true. The remaining
92            // components are copied from `left`.
93            // _mm_cmp_ss is actually an AVX function where the operation is specified
94            // by a const parameter.
95            // _mm_cmp{eq,lt,le,gt,ge,neq,nlt,nle,ngt,nge,ord,unord}_ss are SSE functions
96            // with hard-coded operations.
97            "cmp.ss" => {
98                let [left, right, imm] = this.check_shim(abi, Conv::C, link_name, args)?;
99
100                let which =
101                    FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?;
102
103                bin_op_simd_float_first::<Single>(this, which, left, right, dest)?;
104            }
105            // Used to implement the _mm_cmp*_ps functions.
106            // Performs a comparison operation on each component of `left`
107            // and `right`. For each component, returns 0 if false or u32::MAX
108            // if true.
109            // _mm_cmp_ps is actually an AVX function where the operation is specified
110            // by a const parameter.
111            // _mm_cmp{eq,lt,le,gt,ge,neq,nlt,nle,ngt,nge,ord,unord}_ps are SSE functions
112            // with hard-coded operations.
113            "cmp.ps" => {
114                let [left, right, imm] = this.check_shim(abi, Conv::C, link_name, args)?;
115
116                let which =
117                    FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?;
118
119                bin_op_simd_float_all::<Single>(this, which, left, right, dest)?;
120            }
121            // Used to implement _mm_{,u}comi{eq,lt,le,gt,ge,neq}_ss functions.
122            // Compares the first component of `left` and `right` and returns
123            // a scalar value (0 or 1).
124            "comieq.ss" | "comilt.ss" | "comile.ss" | "comigt.ss" | "comige.ss" | "comineq.ss"
125            | "ucomieq.ss" | "ucomilt.ss" | "ucomile.ss" | "ucomigt.ss" | "ucomige.ss"
126            | "ucomineq.ss" => {
127                let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
128
129                let (left, left_len) = this.project_to_simd(left)?;
130                let (right, right_len) = this.project_to_simd(right)?;
131
132                assert_eq!(left_len, right_len);
133
134                let left = this.read_scalar(&this.project_index(&left, 0)?)?.to_f32()?;
135                let right = this.read_scalar(&this.project_index(&right, 0)?)?.to_f32()?;
136                // The difference between the com* and ucom* variants is signaling
137                // of exceptions when either argument is a quiet NaN. We do not
138                // support accessing the SSE status register from miri (or from Rust,
139                // for that matter), so we treat both variants equally.
140                let res = match unprefixed_name {
141                    "comieq.ss" | "ucomieq.ss" => left == right,
142                    "comilt.ss" | "ucomilt.ss" => left < right,
143                    "comile.ss" | "ucomile.ss" => left <= right,
144                    "comigt.ss" | "ucomigt.ss" => left > right,
145                    "comige.ss" | "ucomige.ss" => left >= right,
146                    "comineq.ss" | "ucomineq.ss" => left != right,
147                    _ => unreachable!(),
148                };
149                this.write_scalar(Scalar::from_i32(i32::from(res)), dest)?;
150            }
151            // Use to implement the _mm_cvtss_si32, _mm_cvttss_si32,
152            // _mm_cvtss_si64 and _mm_cvttss_si64 functions.
153            // Converts the first component of `op` from f32 to i32/i64.
154            "cvtss2si" | "cvttss2si" | "cvtss2si64" | "cvttss2si64" => {
155                let [op] = this.check_shim(abi, Conv::C, link_name, args)?;
156                let (op, _) = this.project_to_simd(op)?;
157
158                let op = this.read_immediate(&this.project_index(&op, 0)?)?;
159
160                let rnd = match unprefixed_name {
161                    // "current SSE rounding mode", assume nearest
162                    // https://www.felixcloutier.com/x86/cvtss2si
163                    "cvtss2si" | "cvtss2si64" => rustc_apfloat::Round::NearestTiesToEven,
164                    // always truncate
165                    // https://www.felixcloutier.com/x86/cvttss2si
166                    "cvttss2si" | "cvttss2si64" => rustc_apfloat::Round::TowardZero,
167                    _ => unreachable!(),
168                };
169
170                let res = this.float_to_int_checked(&op, dest.layout, rnd)?.unwrap_or_else(|| {
171                    // Fallback to minimum according to SSE semantics.
172                    ImmTy::from_int(dest.layout.size.signed_int_min(), dest.layout)
173                });
174
175                this.write_immediate(*res, dest)?;
176            }
177            // Used to implement the _mm_cvtsi32_ss and _mm_cvtsi64_ss functions.
178            // Converts `right` from i32/i64 to f32. Returns a SIMD vector with
179            // the result in the first component and the remaining components
180            // are copied from `left`.
181            // https://www.felixcloutier.com/x86/cvtsi2ss
182            "cvtsi2ss" | "cvtsi642ss" => {
183                let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
184
185                let (left, left_len) = this.project_to_simd(left)?;
186                let (dest, dest_len) = this.project_to_simd(dest)?;
187
188                assert_eq!(dest_len, left_len);
189
190                let right = this.read_immediate(right)?;
191                let dest0 = this.project_index(&dest, 0)?;
192                let res0 = this.int_to_int_or_float(&right, dest0.layout)?;
193                this.write_immediate(*res0, &dest0)?;
194
195                for i in 1..dest_len {
196                    this.copy_op(&this.project_index(&left, i)?, &this.project_index(&dest, i)?)?;
197                }
198            }
199            _ => return interp_ok(EmulateItemResult::NotSupported),
200        }
201        interp_ok(EmulateItemResult::NeedsReturn)
202    }
203}