Skip to main content

miri/intrinsics/x86/
mod.rs

1use rustc_abi::{FieldIdx, Size};
2use rustc_apfloat::Float;
3use rustc_apfloat::ieee::Single;
4use rustc_middle::ty::Ty;
5use rustc_middle::{mir, ty};
6use rustc_span::Symbol;
7use rustc_target::spec::Arch;
8
9use self::helpers::bool_to_simd_element;
10use crate::*;
11
12mod aesni;
13mod avx;
14mod avx2;
15mod avx512;
16mod bmi;
17mod gfni;
18mod sha;
19mod sse;
20mod sse2;
21mod sse3;
22mod sse41;
23mod sse42;
24mod ssse3;
25
26impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
27pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
28    fn emulate_x86_intrinsic(
29        &mut self,
30        link_name: Symbol,
31        args: &[OpTy<'tcx>],
32        dest: &MPlaceTy<'tcx>,
33    ) -> InterpResult<'tcx, EmulateItemResult> {
34        let this = self.eval_context_mut();
35        // Prefix should have already been checked.
36        let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.").unwrap();
37        match unprefixed_name {
38            // Used to implement the `_addcarry_u{32, 64}` and the `_subborrow_u{32, 64}` functions.
39            // Computes a + b or a - b with input and output carry/borrow. The input carry/borrow is an 8-bit
40            // value, which is interpreted as 1 if it is non-zero. The output carry/borrow is an 8-bit value that will be 0 or 1.
41            // https://www.intel.com/content/www/us/en/docs/cpp-compiler/developer-guide-reference/2021-8/addcarry-u32-addcarry-u64.html
42            // https://www.intel.com/content/www/us/en/docs/cpp-compiler/developer-guide-reference/2021-8/subborrow-u32-subborrow-u64.html
43            "addcarry.32" | "addcarry.64" | "subborrow.32" | "subborrow.64" => {
44                if unprefixed_name.ends_with("64") && this.tcx.sess.target.arch != Arch::X86_64 {
45                    return interp_ok(EmulateItemResult::NotSupported);
46                }
47
48                let [cb_in, a, b] = this.check_shim_sig_unadjusted(link_name, args)?;
49                let op = if unprefixed_name.starts_with("add") {
50                    mir::BinOp::AddWithOverflow
51                } else {
52                    mir::BinOp::SubWithOverflow
53                };
54
55                let (sum, cb_out) = carrying_add(this, cb_in, a, b, op)?;
56                this.write_scalar(cb_out, &this.project_field(dest, FieldIdx::ZERO)?)?;
57                this.write_immediate(*sum, &this.project_field(dest, FieldIdx::ONE)?)?;
58            }
59
60            // Used to implement the `_mm_pause` function.
61            // The intrinsic is used to hint the processor that the code is in a spin-loop.
62            // It is compiled down to a `pause` instruction. When SSE2 is not available,
63            // the instruction behaves like a no-op, so it is always safe to call the
64            // intrinsic.
65            "sse2.pause" => {
66                let [] = this.check_shim_sig_unadjusted(link_name, args)?;
67                // Only exhibit the spin-loop hint behavior when SSE2 is enabled.
68                if this.tcx.sess.unstable_target_features.contains(&Symbol::intern("sse2")) {
69                    this.yield_active_thread();
70                }
71            }
72
73            "pclmulqdq" | "pclmulqdq.256" | "pclmulqdq.512" => {
74                let mut len = 2; // in units of 64bits
75                this.expect_target_feature_for_intrinsic(link_name, "pclmulqdq")?;
76                if unprefixed_name.ends_with(".256") {
77                    this.expect_target_feature_for_intrinsic(link_name, "vpclmulqdq")?;
78                    len = 4;
79                } else if unprefixed_name.ends_with(".512") {
80                    this.expect_target_feature_for_intrinsic(link_name, "vpclmulqdq")?;
81                    this.expect_target_feature_for_intrinsic(link_name, "avx512f")?;
82                    len = 8;
83                }
84
85                let [left, right, imm] = this.check_shim_sig_unadjusted(link_name, args)?;
86
87                pclmulqdq(this, left, right, imm, dest, len)?;
88            }
89
90            name if name.starts_with("bmi.") => {
91                return bmi::EvalContextExt::emulate_x86_bmi_intrinsic(this, link_name, args, dest);
92            }
93            // The GFNI extension does not get its own namespace.
94            // Check for instruction names instead.
95            name if name.starts_with("vgf2p8affine") || name.starts_with("vgf2p8mulb") => {
96                return gfni::EvalContextExt::emulate_x86_gfni_intrinsic(
97                    this, link_name, args, dest,
98                );
99            }
100            name if name.starts_with("sha") => {
101                return sha::EvalContextExt::emulate_x86_sha_intrinsic(this, link_name, args, dest);
102            }
103            name if name.starts_with("sse.") => {
104                return sse::EvalContextExt::emulate_x86_sse_intrinsic(this, link_name, args, dest);
105            }
106            name if name.starts_with("sse2.") => {
107                return sse2::EvalContextExt::emulate_x86_sse2_intrinsic(
108                    this, link_name, args, dest,
109                );
110            }
111            name if name.starts_with("sse3.") => {
112                return sse3::EvalContextExt::emulate_x86_sse3_intrinsic(
113                    this, link_name, args, dest,
114                );
115            }
116            name if name.starts_with("ssse3.") => {
117                return ssse3::EvalContextExt::emulate_x86_ssse3_intrinsic(
118                    this, link_name, args, dest,
119                );
120            }
121            name if name.starts_with("sse41.") => {
122                return sse41::EvalContextExt::emulate_x86_sse41_intrinsic(
123                    this, link_name, args, dest,
124                );
125            }
126            name if name.starts_with("sse42.") => {
127                return sse42::EvalContextExt::emulate_x86_sse42_intrinsic(
128                    this, link_name, args, dest,
129                );
130            }
131            name if name.starts_with("aesni.") => {
132                return aesni::EvalContextExt::emulate_x86_aesni_intrinsic(
133                    this, link_name, args, dest,
134                );
135            }
136            name if name.starts_with("avx.") => {
137                return avx::EvalContextExt::emulate_x86_avx_intrinsic(this, link_name, args, dest);
138            }
139            name if name.starts_with("avx2.") => {
140                return avx2::EvalContextExt::emulate_x86_avx2_intrinsic(
141                    this, link_name, args, dest,
142                );
143            }
144            name if name.starts_with("avx512.") => {
145                return avx512::EvalContextExt::emulate_x86_avx512_intrinsic(
146                    this, link_name, args, dest,
147                );
148            }
149
150            _ => return interp_ok(EmulateItemResult::NotSupported),
151        }
152        interp_ok(EmulateItemResult::NeedsReturn)
153    }
154}
155
156#[derive(Copy, Clone)]
157enum FloatBinOp {
158    /// Comparison
159    ///
160    /// The semantics of this operator is a case distinction: we compare the two operands,
161    /// and then we return one of the four booleans `gt`, `lt`, `eq`, `unord` depending on
162    /// which class they fall into.
163    ///
164    /// AVX supports all 16 combinations, SSE only a subset
165    ///
166    /// <https://www.felixcloutier.com/x86/cmpss>
167    /// <https://www.felixcloutier.com/x86/cmpps>
168    /// <https://www.felixcloutier.com/x86/cmpsd>
169    /// <https://www.felixcloutier.com/x86/cmppd>
170    Cmp {
171        /// Result when lhs < rhs
172        gt: bool,
173        /// Result when lhs > rhs
174        lt: bool,
175        /// Result when lhs == rhs
176        eq: bool,
177        /// Result when lhs is NaN or rhs is NaN
178        unord: bool,
179    },
180    /// Minimum value (with SSE semantics)
181    ///
182    /// <https://www.felixcloutier.com/x86/minss>
183    /// <https://www.felixcloutier.com/x86/minps>
184    /// <https://www.felixcloutier.com/x86/minsd>
185    /// <https://www.felixcloutier.com/x86/minpd>
186    Min,
187    /// Maximum value (with SSE semantics)
188    ///
189    /// <https://www.felixcloutier.com/x86/maxss>
190    /// <https://www.felixcloutier.com/x86/maxps>
191    /// <https://www.felixcloutier.com/x86/maxsd>
192    /// <https://www.felixcloutier.com/x86/maxpd>
193    Max,
194}
195
196impl FloatBinOp {
197    /// Convert from the `imm` argument used to specify the comparison
198    /// operation in intrinsics such as `llvm.x86.sse.cmp.ss`.
199    fn cmp_from_imm<'tcx>(
200        ecx: &crate::MiriInterpCx<'tcx>,
201        imm: i8,
202        intrinsic: Symbol,
203    ) -> InterpResult<'tcx, Self> {
204        // Only bits 0..=4 are used, remaining should be zero.
205        if imm & !0b1_1111 != 0 {
206            panic!("invalid `imm` parameter of {intrinsic}: 0x{imm:x}");
207        }
208        // Bit 4 specifies whether the operation is quiet or signaling, which
209        // we do not care in Miri.
210        // Bits 0..=2 specifies the operation.
211        // `gt` indicates the result to be returned when the LHS is strictly
212        // greater than the RHS, and so on.
213        let (gt, lt, eq, mut unord) = match imm & 0b111 {
214            // Equal
215            0x0 => (false, false, true, false),
216            // Less-than
217            0x1 => (false, true, false, false),
218            // Less-or-equal
219            0x2 => (false, true, true, false),
220            // Unordered (either is NaN)
221            0x3 => (false, false, false, true),
222            // Not equal
223            0x4 => (true, true, false, true),
224            // Not less-than
225            0x5 => (true, false, true, true),
226            // Not less-or-equal
227            0x6 => (true, false, false, true),
228            // Ordered (neither is NaN)
229            0x7 => (true, true, true, false),
230            _ => unreachable!(),
231        };
232        // When bit 3 is 1 (only possible in AVX), unord is toggled.
233        if imm & 0b1000 != 0 {
234            ecx.expect_target_feature_for_intrinsic(intrinsic, "avx")?;
235            unord = !unord;
236        }
237        interp_ok(Self::Cmp { gt, lt, eq, unord })
238    }
239}
240
241/// Performs `which` scalar operation on `left` and `right` and returns
242/// the result.
243fn bin_op_float<'tcx, F: rustc_apfloat::Float>(
244    which: FloatBinOp,
245    left: &ImmTy<'tcx>,
246    right: &ImmTy<'tcx>,
247) -> InterpResult<'tcx, Scalar> {
248    match which {
249        FloatBinOp::Cmp { gt, lt, eq, unord } => {
250            let left = left.to_scalar().to_float::<F>()?;
251            let right = right.to_scalar().to_float::<F>()?;
252
253            let res = match left.partial_cmp(&right) {
254                None => unord,
255                Some(std::cmp::Ordering::Less) => lt,
256                Some(std::cmp::Ordering::Equal) => eq,
257                Some(std::cmp::Ordering::Greater) => gt,
258            };
259            interp_ok(bool_to_simd_element(res, Size::from_bits(F::BITS)))
260        }
261        FloatBinOp::Min => {
262            let left_scalar = left.to_scalar();
263            let left = left_scalar.to_float::<F>()?;
264            let right_scalar = right.to_scalar();
265            let right = right_scalar.to_float::<F>()?;
266            // SSE semantics to handle zero and NaN. Note that `x == F::ZERO`
267            // is true when `x` is either +0 or -0.
268            if (left == F::ZERO && right == F::ZERO)
269                || left.is_nan()
270                || right.is_nan()
271                || left >= right
272            {
273                interp_ok(right_scalar)
274            } else {
275                interp_ok(left_scalar)
276            }
277        }
278        FloatBinOp::Max => {
279            let left_scalar = left.to_scalar();
280            let left = left_scalar.to_float::<F>()?;
281            let right_scalar = right.to_scalar();
282            let right = right_scalar.to_float::<F>()?;
283            // SSE semantics to handle zero and NaN. Note that `x == F::ZERO`
284            // is true when `x` is either +0 or -0.
285            if (left == F::ZERO && right == F::ZERO)
286                || left.is_nan()
287                || right.is_nan()
288                || left <= right
289            {
290                interp_ok(right_scalar)
291            } else {
292                interp_ok(left_scalar)
293            }
294        }
295    }
296}
297
298/// Performs `which` operation on the first component of `left` and `right`
299/// and copies the other components from `left`. The result is stored in `dest`.
300fn bin_op_simd_float_first<'tcx, F: rustc_apfloat::Float>(
301    ecx: &mut crate::MiriInterpCx<'tcx>,
302    which: FloatBinOp,
303    left: &OpTy<'tcx>,
304    right: &OpTy<'tcx>,
305    dest: &MPlaceTy<'tcx>,
306) -> InterpResult<'tcx, ()> {
307    let (left, left_len) = ecx.project_to_simd(left)?;
308    let (right, right_len) = ecx.project_to_simd(right)?;
309    let (dest, dest_len) = ecx.project_to_simd(dest)?;
310
311    assert_eq!(dest_len, left_len);
312    assert_eq!(dest_len, right_len);
313
314    let res0 = bin_op_float::<F>(
315        which,
316        &ecx.read_immediate(&ecx.project_index(&left, 0)?)?,
317        &ecx.read_immediate(&ecx.project_index(&right, 0)?)?,
318    )?;
319    ecx.write_scalar(res0, &ecx.project_index(&dest, 0)?)?;
320
321    for i in 1..dest_len {
322        ecx.copy_op(&ecx.project_index(&left, i)?, &ecx.project_index(&dest, i)?)?;
323    }
324
325    interp_ok(())
326}
327
328/// Performs `which` operation on each component of `left` and
329/// `right`, storing the result is stored in `dest`.
330fn bin_op_simd_float_all<'tcx, F: rustc_apfloat::Float>(
331    ecx: &mut crate::MiriInterpCx<'tcx>,
332    which: FloatBinOp,
333    left: &OpTy<'tcx>,
334    right: &OpTy<'tcx>,
335    dest: &MPlaceTy<'tcx>,
336) -> InterpResult<'tcx, ()> {
337    let (left, left_len) = ecx.project_to_simd(left)?;
338    let (right, right_len) = ecx.project_to_simd(right)?;
339    let (dest, dest_len) = ecx.project_to_simd(dest)?;
340
341    assert_eq!(dest_len, left_len);
342    assert_eq!(dest_len, right_len);
343
344    for i in 0..dest_len {
345        let left = ecx.read_immediate(&ecx.project_index(&left, i)?)?;
346        let right = ecx.read_immediate(&ecx.project_index(&right, i)?)?;
347        let dest = ecx.project_index(&dest, i)?;
348
349        let res = bin_op_float::<F>(which, &left, &right)?;
350        ecx.write_scalar(res, &dest)?;
351    }
352
353    interp_ok(())
354}
355
356#[derive(Copy, Clone)]
357enum FloatUnaryOp {
358    /// Approximation of 1/x
359    ///
360    /// <https://www.felixcloutier.com/x86/rcpss>
361    /// <https://www.felixcloutier.com/x86/rcpps>
362    Rcp,
363    /// Approximation of 1/sqrt(x)
364    ///
365    /// <https://www.felixcloutier.com/x86/rsqrtss>
366    /// <https://www.felixcloutier.com/x86/rsqrtps>
367    Rsqrt,
368}
369
370/// Performs `which` scalar operation on `op` and returns the result.
371fn unary_op_f32<'tcx>(
372    ecx: &mut crate::MiriInterpCx<'tcx>,
373    which: FloatUnaryOp,
374    op: &ImmTy<'tcx>,
375) -> InterpResult<'tcx, Scalar> {
376    match which {
377        FloatUnaryOp::Rcp => {
378            let op = op.to_scalar().to_f32()?;
379            let div = (Single::from_u128(1).value / op).value;
380            // Apply a relative error with a magnitude on the order of 2^-12 to simulate the
381            // inaccuracy of RCP.
382            let res = math::apply_random_float_error(ecx, div, -12);
383            interp_ok(Scalar::from_f32(res))
384        }
385        FloatUnaryOp::Rsqrt => {
386            let op = op.to_scalar().to_f32()?;
387            let rsqrt = (Single::from_u128(1).value / math::sqrt(op)).value;
388            // Apply a relative error with a magnitude on the order of 2^-12 to simulate the
389            // inaccuracy of RSQRT.
390            let res = math::apply_random_float_error(ecx, rsqrt, -12);
391            interp_ok(Scalar::from_f32(res))
392        }
393    }
394}
395
396/// Performs `which` operation on the first component of `op` and copies
397/// the other components. The result is stored in `dest`.
398fn unary_op_ss<'tcx>(
399    ecx: &mut crate::MiriInterpCx<'tcx>,
400    which: FloatUnaryOp,
401    op: &OpTy<'tcx>,
402    dest: &MPlaceTy<'tcx>,
403) -> InterpResult<'tcx, ()> {
404    let (op, op_len) = ecx.project_to_simd(op)?;
405    let (dest, dest_len) = ecx.project_to_simd(dest)?;
406
407    assert_eq!(dest_len, op_len);
408
409    let res0 = unary_op_f32(ecx, which, &ecx.read_immediate(&ecx.project_index(&op, 0)?)?)?;
410    ecx.write_scalar(res0, &ecx.project_index(&dest, 0)?)?;
411
412    for i in 1..dest_len {
413        ecx.copy_op(&ecx.project_index(&op, i)?, &ecx.project_index(&dest, i)?)?;
414    }
415
416    interp_ok(())
417}
418
419/// Performs `which` operation on each component of `op`, storing the
420/// result is stored in `dest`.
421fn unary_op_ps<'tcx>(
422    ecx: &mut crate::MiriInterpCx<'tcx>,
423    which: FloatUnaryOp,
424    op: &OpTy<'tcx>,
425    dest: &MPlaceTy<'tcx>,
426) -> InterpResult<'tcx, ()> {
427    let (op, op_len) = ecx.project_to_simd(op)?;
428    let (dest, dest_len) = ecx.project_to_simd(dest)?;
429
430    assert_eq!(dest_len, op_len);
431
432    for i in 0..dest_len {
433        let op = ecx.read_immediate(&ecx.project_index(&op, i)?)?;
434        let dest = ecx.project_index(&dest, i)?;
435
436        let res = unary_op_f32(ecx, which, &op)?;
437        ecx.write_scalar(res, &dest)?;
438    }
439
440    interp_ok(())
441}
442
443enum ShiftOp {
444    /// Shift left, logically (shift in zeros) -- same as shift left, arithmetically
445    Left,
446    /// Shift right, logically (shift in zeros)
447    RightLogic,
448    /// Shift right, arithmetically (shift in sign)
449    RightArith,
450}
451
452/// Shifts each element of `left` by a scalar amount. The shift amount
453/// is determined by the lowest 64 bits of `right` (which is a 128-bit vector).
454///
455/// For logic shifts, when right is larger than BITS - 1, zero is produced.
456/// For arithmetic right-shifts, when right is larger than BITS - 1, the sign
457/// bit is copied to all bits.
458fn shift_simd_by_scalar<'tcx>(
459    ecx: &mut crate::MiriInterpCx<'tcx>,
460    left: &OpTy<'tcx>,
461    right: &OpTy<'tcx>,
462    which: ShiftOp,
463    dest: &MPlaceTy<'tcx>,
464) -> InterpResult<'tcx, ()> {
465    let (left, left_len) = ecx.project_to_simd(left)?;
466    let (dest, dest_len) = ecx.project_to_simd(dest)?;
467
468    assert_eq!(dest_len, left_len);
469    // `right` may have a different length, and we only care about its
470    // lowest 64bit anyway.
471
472    // Get the 64-bit shift operand and convert it to the type expected
473    // by checked_{shl,shr} (u32).
474    // It is ok to saturate the value to u32::MAX because any value
475    // above BITS - 1 will produce the same result.
476    let shift = u32::try_from(extract_first_u64(ecx, right)?).unwrap_or(u32::MAX);
477
478    for i in 0..dest_len {
479        let left = ecx.read_scalar(&ecx.project_index(&left, i)?)?;
480        let dest = ecx.project_index(&dest, i)?;
481
482        let res = match which {
483            ShiftOp::Left => {
484                let left = left.to_uint(dest.layout.size)?;
485                let res = left.checked_shl(shift).unwrap_or(0);
486                // `truncate` is needed as left-shift can make the absolute value larger.
487                Scalar::from_uint(dest.layout.size.truncate(res), dest.layout.size)
488            }
489            ShiftOp::RightLogic => {
490                let left = left.to_uint(dest.layout.size)?;
491                let res = left.checked_shr(shift).unwrap_or(0);
492                // No `truncate` needed as right-shift can only make the absolute value smaller.
493                Scalar::from_uint(res, dest.layout.size)
494            }
495            ShiftOp::RightArith => {
496                let left = left.to_int(dest.layout.size)?;
497                // On overflow, copy the sign bit to the remaining bits
498                let res = left.checked_shr(shift).unwrap_or(left >> 127);
499                // No `truncate` needed as right-shift can only make the absolute value smaller.
500                Scalar::from_int(res, dest.layout.size)
501            }
502        };
503        ecx.write_scalar(res, &dest)?;
504    }
505
506    interp_ok(())
507}
508
509/// Takes a 128-bit vector, transmutes it to `[u64; 2]` and extracts
510/// the first value.
511fn extract_first_u64<'tcx>(
512    ecx: &crate::MiriInterpCx<'tcx>,
513    op: &OpTy<'tcx>,
514) -> InterpResult<'tcx, u64> {
515    // Transmute vector to `[u64; 2]`
516    let array_layout = ecx.layout_of(Ty::new_array(ecx.tcx.tcx, ecx.tcx.types.u64, 2))?;
517    let op = op.transmute(array_layout, ecx)?;
518
519    // Get the first u64 from the array
520    ecx.read_scalar(&ecx.project_index(&op, 0)?)?.to_u64()
521}
522
523// Rounds the first element of `right` according to `rounding`
524// and copies the remaining elements from `left`.
525fn round_first<'tcx, F: rustc_apfloat::Float>(
526    ecx: &mut crate::MiriInterpCx<'tcx>,
527    left: &OpTy<'tcx>,
528    right: &OpTy<'tcx>,
529    rounding: &OpTy<'tcx>,
530    dest: &MPlaceTy<'tcx>,
531) -> InterpResult<'tcx, ()> {
532    let (left, left_len) = ecx.project_to_simd(left)?;
533    let (right, right_len) = ecx.project_to_simd(right)?;
534    let (dest, dest_len) = ecx.project_to_simd(dest)?;
535
536    assert_eq!(dest_len, left_len);
537    assert_eq!(dest_len, right_len);
538
539    let rounding = rounding_from_imm(ecx.read_scalar(rounding)?.to_i32()?)?;
540
541    let op0: F = ecx.read_scalar(&ecx.project_index(&right, 0)?)?.to_float()?;
542    let res = op0.round_to_integral(rounding).value;
543    ecx.write_scalar(
544        Scalar::from_uint(res.to_bits(), Size::from_bits(F::BITS)),
545        &ecx.project_index(&dest, 0)?,
546    )?;
547
548    for i in 1..dest_len {
549        ecx.copy_op(&ecx.project_index(&left, i)?, &ecx.project_index(&dest, i)?)?;
550    }
551
552    interp_ok(())
553}
554
555// Rounds all elements of `op` according to `rounding`.
556fn round_all<'tcx, F: rustc_apfloat::Float>(
557    ecx: &mut crate::MiriInterpCx<'tcx>,
558    op: &OpTy<'tcx>,
559    rounding: &OpTy<'tcx>,
560    dest: &MPlaceTy<'tcx>,
561) -> InterpResult<'tcx, ()> {
562    let (op, op_len) = ecx.project_to_simd(op)?;
563    let (dest, dest_len) = ecx.project_to_simd(dest)?;
564
565    assert_eq!(dest_len, op_len);
566
567    let rounding = rounding_from_imm(ecx.read_scalar(rounding)?.to_i32()?)?;
568
569    for i in 0..dest_len {
570        let op: F = ecx.read_scalar(&ecx.project_index(&op, i)?)?.to_float()?;
571        let res = op.round_to_integral(rounding).value;
572        ecx.write_scalar(
573            Scalar::from_uint(res.to_bits(), Size::from_bits(F::BITS)),
574            &ecx.project_index(&dest, i)?,
575        )?;
576    }
577
578    interp_ok(())
579}
580
581/// Gets equivalent `rustc_apfloat::Round` from rounding mode immediate of
582/// `round.{ss,sd,ps,pd}` intrinsics.
583fn rounding_from_imm<'tcx>(rounding: i32) -> InterpResult<'tcx, rustc_apfloat::Round> {
584    // The fourth bit of `rounding` only affects the SSE status
585    // register, which cannot be accessed from Miri (or from Rust,
586    // for that matter), so we can ignore it.
587    match rounding & !0b1000 {
588        // When the third bit is 0, the rounding mode is determined by the
589        // first two bits.
590        0b000 => interp_ok(rustc_apfloat::Round::NearestTiesToEven),
591        0b001 => interp_ok(rustc_apfloat::Round::TowardNegative),
592        0b010 => interp_ok(rustc_apfloat::Round::TowardPositive),
593        0b011 => interp_ok(rustc_apfloat::Round::TowardZero),
594        // When the third bit is 1, the rounding mode is determined by the
595        // SSE status register. Since we do not support modifying it from
596        // Miri (or Rust), we assume it to be at its default mode (round-to-nearest).
597        0b100..=0b111 => interp_ok(rustc_apfloat::Round::NearestTiesToEven),
598        rounding => panic!("invalid rounding mode 0x{rounding:02x}"),
599    }
600}
601
602/// Converts each element of `op` from floating point to signed integer.
603///
604/// When the input value is NaN or out of range, fall back to minimum value.
605///
606/// If `op` has more elements than `dest`, extra elements are ignored. If `op`
607/// has less elements than `dest`, the rest is filled with zeros.
608fn convert_float_to_int<'tcx>(
609    ecx: &mut crate::MiriInterpCx<'tcx>,
610    op: &OpTy<'tcx>,
611    rnd: rustc_apfloat::Round,
612    dest: &MPlaceTy<'tcx>,
613) -> InterpResult<'tcx, ()> {
614    let (op, op_len) = ecx.project_to_simd(op)?;
615    let (dest, dest_len) = ecx.project_to_simd(dest)?;
616
617    // Output must be *signed* integers.
618    assert!(matches!(dest.layout.field(ecx, 0).ty.kind(), ty::Int(_)));
619
620    for i in 0..op_len.min(dest_len) {
621        let op = ecx.read_immediate(&ecx.project_index(&op, i)?)?;
622        let dest = ecx.project_index(&dest, i)?;
623
624        let res = ecx.float_to_int_checked(&op, dest.layout, rnd)?.unwrap_or_else(|| {
625            // Fallback to minimum according to SSE/AVX semantics.
626            ImmTy::from_int(dest.layout.size.signed_int_min(), dest.layout)
627        });
628        ecx.write_immediate(*res, &dest)?;
629    }
630    // Fill remainder with zeros
631    for i in op_len..dest_len {
632        let dest = ecx.project_index(&dest, i)?;
633        ecx.write_scalar(Scalar::from_int(0, dest.layout.size), &dest)?;
634    }
635
636    interp_ok(())
637}
638
639/// Splits `op` (which must be a SIMD vector) into 128-bit chunks.
640///
641/// Returns a tuple where:
642/// * The first element is the number of 128-bit chunks (let's call it `N`).
643/// * The second element is the number of elements per chunk (let's call it `M`).
644/// * The third element is the `op` vector split into chunks, i.e, it's
645///   type is `[[T; M]; N]` where `T` is the element type of `op`.
646fn split_simd_to_128bit_chunks<'tcx, P: Projectable<'tcx, Provenance>>(
647    ecx: &mut crate::MiriInterpCx<'tcx>,
648    op: &P,
649) -> InterpResult<'tcx, (u64, u64, P)> {
650    let simd_layout = op.layout();
651    let (simd_len, element_ty) = simd_layout.ty.simd_size_and_type(ecx.tcx.tcx);
652
653    assert_eq!(simd_layout.size.bits() % 128, 0);
654    let num_chunks = simd_layout.size.bits() / 128;
655    let items_per_chunk = simd_len.strict_div(num_chunks);
656
657    // Transmute to `[[T; items_per_chunk]; num_chunks]`
658    let chunked_layout = ecx
659        .layout_of(Ty::new_array(
660            ecx.tcx.tcx,
661            Ty::new_array(ecx.tcx.tcx, element_ty, items_per_chunk),
662            num_chunks,
663        ))
664        .unwrap();
665    let chunked_op = op.transmute(chunked_layout, ecx)?;
666
667    interp_ok((num_chunks, items_per_chunk, chunked_op))
668}
669
670/// Horizontally performs `which` operation on adjacent values of
671/// `left` and `right` SIMD vectors and stores the result in `dest`.
672/// "Horizontal" means that the i-th output element is calculated
673/// from the elements 2*i and 2*i+1 of the concatenation of `left` and
674/// `right`.
675///
676/// Each 128-bit chunk is treated independently (i.e., the value for
677/// the is i-th 128-bit chunk of `dest` is calculated with the i-th
678/// 128-bit chunks of `left` and `right`).
679fn horizontal_bin_op<'tcx>(
680    ecx: &mut crate::MiriInterpCx<'tcx>,
681    which: mir::BinOp,
682    saturating: bool,
683    left: &OpTy<'tcx>,
684    right: &OpTy<'tcx>,
685    dest: &MPlaceTy<'tcx>,
686) -> InterpResult<'tcx, ()> {
687    assert_eq!(left.layout, dest.layout);
688    assert_eq!(right.layout, dest.layout);
689
690    let (num_chunks, items_per_chunk, left) = split_simd_to_128bit_chunks(ecx, left)?;
691    let (_, _, right) = split_simd_to_128bit_chunks(ecx, right)?;
692    let (_, _, dest) = split_simd_to_128bit_chunks(ecx, dest)?;
693
694    let middle = items_per_chunk / 2;
695    for i in 0..num_chunks {
696        let left = ecx.project_index(&left, i)?;
697        let right = ecx.project_index(&right, i)?;
698        let dest = ecx.project_index(&dest, i)?;
699
700        for j in 0..items_per_chunk {
701            // `j` is the index in `dest`
702            // `k` is the index of the 2-item chunk in `src`
703            let (k, src) = if j < middle { (j, &left) } else { (j.strict_sub(middle), &right) };
704            // `base_i` is the index of the first item of the 2-item chunk in `src`
705            let base_i = k.strict_mul(2);
706            let lhs = ecx.read_immediate(&ecx.project_index(src, base_i)?)?;
707            let rhs = ecx.read_immediate(&ecx.project_index(src, base_i.strict_add(1))?)?;
708
709            let res = if saturating {
710                Immediate::from(ecx.saturating_arith(which, &lhs, &rhs)?)
711            } else {
712                *ecx.binary_op(which, &lhs, &rhs)?
713            };
714
715            ecx.write_immediate(res, &ecx.project_index(&dest, j)?)?;
716        }
717    }
718
719    interp_ok(())
720}
721
722/// Conditionally multiplies the packed floating-point elements in
723/// `left` and `right` using the high 4 bits in `imm`, sums the calculated
724/// products (up to 4), and conditionally stores the sum in `dest` using
725/// the low 4 bits of `imm`.
726///
727/// Each 128-bit chunk is treated independently (i.e., the value for
728/// the is i-th 128-bit chunk of `dest` is calculated with the i-th
729/// 128-bit blocks of `left` and `right`).
730fn conditional_dot_product<'tcx>(
731    ecx: &mut crate::MiriInterpCx<'tcx>,
732    left: &OpTy<'tcx>,
733    right: &OpTy<'tcx>,
734    imm: &OpTy<'tcx>,
735    dest: &MPlaceTy<'tcx>,
736) -> InterpResult<'tcx, ()> {
737    assert_eq!(left.layout, dest.layout);
738    assert_eq!(right.layout, dest.layout);
739
740    let (num_chunks, items_per_chunk, left) = split_simd_to_128bit_chunks(ecx, left)?;
741    let (_, _, right) = split_simd_to_128bit_chunks(ecx, right)?;
742    let (_, _, dest) = split_simd_to_128bit_chunks(ecx, dest)?;
743
744    let element_layout = left.layout.field(ecx, 0).field(ecx, 0);
745    assert!(items_per_chunk <= 4);
746
747    // `imm` is a `u8` for SSE4.1 or an `i32` for AVX :/
748    let imm = ecx.read_scalar(imm)?.to_uint(imm.layout.size)?;
749
750    for i in 0..num_chunks {
751        let left = ecx.project_index(&left, i)?;
752        let right = ecx.project_index(&right, i)?;
753        let dest = ecx.project_index(&dest, i)?;
754
755        // Calculate dot product
756        // Elements are floating point numbers, but we can use `from_int`
757        // for the initial value because the representation of 0.0 is all zero bits.
758        let mut sum = ImmTy::from_int(0u8, element_layout);
759        for j in 0..items_per_chunk {
760            if imm & (1 << j.strict_add(4)) != 0 {
761                let left = ecx.read_immediate(&ecx.project_index(&left, j)?)?;
762                let right = ecx.read_immediate(&ecx.project_index(&right, j)?)?;
763
764                let mul = ecx.binary_op(mir::BinOp::Mul, &left, &right)?;
765                sum = ecx.binary_op(mir::BinOp::Add, &sum, &mul)?;
766            }
767        }
768
769        // Write to destination (conditioned to imm)
770        for j in 0..items_per_chunk {
771            let dest = ecx.project_index(&dest, j)?;
772
773            if imm & (1 << j) != 0 {
774                ecx.write_immediate(*sum, &dest)?;
775            } else {
776                ecx.write_scalar(Scalar::from_int(0u8, element_layout.size), &dest)?;
777            }
778        }
779    }
780
781    interp_ok(())
782}
783
784/// Calculates two booleans.
785///
786/// The first is true when all the bits of `op & mask` are zero.
787/// The second is true when `(op & mask) == mask`
788fn test_bits_masked<'tcx>(
789    ecx: &crate::MiriInterpCx<'tcx>,
790    op: &OpTy<'tcx>,
791    mask: &OpTy<'tcx>,
792) -> InterpResult<'tcx, (bool, bool)> {
793    assert_eq!(op.layout, mask.layout);
794
795    let (op, op_len) = ecx.project_to_simd(op)?;
796    let (mask, mask_len) = ecx.project_to_simd(mask)?;
797
798    assert_eq!(op_len, mask_len);
799
800    let mut all_zero = true;
801    let mut masked_set = true;
802    for i in 0..op_len {
803        let op = ecx.project_index(&op, i)?;
804        let mask = ecx.project_index(&mask, i)?;
805
806        let op = ecx.read_scalar(&op)?.to_uint(op.layout.size)?;
807        let mask = ecx.read_scalar(&mask)?.to_uint(mask.layout.size)?;
808        all_zero &= (op & mask) == 0;
809        masked_set &= (op & mask) == mask;
810    }
811
812    interp_ok((all_zero, masked_set))
813}
814
815/// Calculates two booleans.
816///
817/// The first is true when the highest bit of each element of `op & mask` is zero.
818/// The second is true when the highest bit of each element of `!op & mask` is zero.
819fn test_high_bits_masked<'tcx>(
820    ecx: &crate::MiriInterpCx<'tcx>,
821    op: &OpTy<'tcx>,
822    mask: &OpTy<'tcx>,
823) -> InterpResult<'tcx, (bool, bool)> {
824    assert_eq!(op.layout, mask.layout);
825
826    let (op, op_len) = ecx.project_to_simd(op)?;
827    let (mask, mask_len) = ecx.project_to_simd(mask)?;
828
829    assert_eq!(op_len, mask_len);
830
831    let high_bit_offset = op.layout.field(ecx, 0).size.bits().strict_sub(1);
832
833    let mut direct = true;
834    let mut negated = true;
835    for i in 0..op_len {
836        let op = ecx.project_index(&op, i)?;
837        let mask = ecx.project_index(&mask, i)?;
838
839        let op = ecx.read_scalar(&op)?.to_uint(op.layout.size)?;
840        let mask = ecx.read_scalar(&mask)?.to_uint(mask.layout.size)?;
841        direct &= (op & mask) >> high_bit_offset == 0;
842        negated &= (!op & mask) >> high_bit_offset == 0;
843    }
844
845    interp_ok((direct, negated))
846}
847
848/// Compute the sum of absolute differences of quadruplets of unsigned
849/// 8-bit integers in `left` and `right`, and store the 16-bit results
850/// in `right`. Quadruplets are selected from `left` and `right` with
851/// offsets specified in `imm`.
852///
853/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_maddubs_epi16>
854/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_mpsadbw_epu8>
855///
856/// Each 128-bit chunk is treated independently (i.e., the value for
857/// the is i-th 128-bit chunk of `dest` is calculated with the i-th
858/// 128-bit chunks of `left` and `right`).
859fn mpsadbw<'tcx>(
860    ecx: &mut crate::MiriInterpCx<'tcx>,
861    left: &OpTy<'tcx>,
862    right: &OpTy<'tcx>,
863    imm: &OpTy<'tcx>,
864    dest: &MPlaceTy<'tcx>,
865) -> InterpResult<'tcx, ()> {
866    assert_eq!(left.layout, right.layout);
867    assert_eq!(left.layout.size, dest.layout.size);
868
869    let (num_chunks, op_items_per_chunk, left) = split_simd_to_128bit_chunks(ecx, left)?;
870    assert!(num_chunks <= 2);
871
872    let (_, _, right) = split_simd_to_128bit_chunks(ecx, right)?;
873    let (_, dest_items_per_chunk, dest) = split_simd_to_128bit_chunks(ecx, dest)?;
874
875    assert_eq!(op_items_per_chunk, dest_items_per_chunk.strict_mul(2));
876
877    let imm = ecx.read_scalar(imm)?.to_uint(imm.layout.size)?;
878
879    for i in 0..num_chunks {
880        let left = ecx.project_index(&left, i)?;
881        let right = ecx.project_index(&right, i)?;
882        let dest = ecx.project_index(&dest, i)?;
883
884        // The first 128-bit chunk uses the low 3 bits of IMM, the second chunk uses bits 3..6.
885        let lane_imm = imm.strict_shr(i.strict_mul(3).try_into().unwrap());
886
887        // Bit 2 of `lane_imm` specifies the offset for indices of `left`.
888        // The offset is 0 when the bit is 0 or 4 when the bit is 1.
889        let left_base = u64::try_from((lane_imm >> 2) & 1).unwrap().strict_mul(4);
890        // Bits 0..=1 of `lane_imm` specify the offset for indices of
891        // `right` in blocks of 4 elements.
892        let right_base = u64::try_from(lane_imm & 0b11).unwrap().strict_mul(4);
893
894        for j in 0..dest_items_per_chunk {
895            let left_offset = left_base.strict_add(j);
896            let mut res: u16 = 0;
897            for k in 0..4 {
898                let left = ecx
899                    .read_scalar(&ecx.project_index(&left, left_offset.strict_add(k))?)?
900                    .to_u8()?;
901                let right = ecx
902                    .read_scalar(&ecx.project_index(&right, right_base.strict_add(k))?)?
903                    .to_u8()?;
904                res = res.strict_add(left.abs_diff(right).into());
905            }
906            ecx.write_scalar(Scalar::from_u16(res), &ecx.project_index(&dest, j)?)?;
907        }
908    }
909
910    interp_ok(())
911}
912
913/// Compute the absolute differences of packed unsigned 8-bit integers
914/// in `left` and `right`, then horizontally sum each consecutive 8
915/// differences to produce unsigned 16-bit integers, and pack
916/// these unsigned 16-bit integers in the low 16 bits of 64-bit elements
917/// in `dest`.
918///
919/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sad_epu8>
920/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_sad_epu8>
921/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm512_sad_epu8>
922fn psadbw<'tcx>(
923    ecx: &mut crate::MiriInterpCx<'tcx>,
924    left: &OpTy<'tcx>,
925    right: &OpTy<'tcx>,
926    dest: &MPlaceTy<'tcx>,
927) -> InterpResult<'tcx, ()> {
928    let (left, left_len) = ecx.project_to_simd(left)?;
929    let (right, right_len) = ecx.project_to_simd(right)?;
930    let (dest, dest_len) = ecx.project_to_simd(dest)?;
931
932    // fn psadbw(a: u8x16, b: u8x16) -> u64x2;
933    // fn psadbw(a: u8x32, b: u8x32) -> u64x4;
934    // fn vpsadbw(a: u8x64, b: u8x64) -> u64x8;
935    assert_eq!(left_len, right_len);
936    assert_eq!(left_len, left.layout.layout.size().bytes());
937    assert_eq!(dest_len, left_len.strict_div(8));
938
939    for i in 0..dest_len {
940        let dest = ecx.project_index(&dest, i)?;
941
942        let mut acc: u16 = 0;
943        for j in 0..8 {
944            let src_index = i.strict_mul(8).strict_add(j);
945
946            let left = ecx.project_index(&left, src_index)?;
947            let left = ecx.read_scalar(&left)?.to_u8()?;
948
949            let right = ecx.project_index(&right, src_index)?;
950            let right = ecx.read_scalar(&right)?.to_u8()?;
951
952            acc = acc.strict_add(left.abs_diff(right).into());
953        }
954
955        ecx.write_scalar(Scalar::from_u64(acc.into()), &dest)?;
956    }
957
958    interp_ok(())
959}
960
961/// Multiply packed signed 16-bit integers in `left` and `right`, producing intermediate signed 32-bit integers.
962/// Horizontally add adjacent pairs of intermediate 32-bit integers, and pack the results in `dest`.
963///
964/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_madd_epi16>
965/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_madd_epi16>
966/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm512_madd_epi16>
967fn pmaddwd<'tcx>(
968    ecx: &mut crate::MiriInterpCx<'tcx>,
969    left: &OpTy<'tcx>,
970    right: &OpTy<'tcx>,
971    dest: &MPlaceTy<'tcx>,
972) -> InterpResult<'tcx, ()> {
973    let (left, left_len) = ecx.project_to_simd(left)?;
974    let (right, right_len) = ecx.project_to_simd(right)?;
975    let (dest, dest_len) = ecx.project_to_simd(dest)?;
976
977    // fn  pmaddwd(a: i16x8,  b: i16x8)  -> i32x4;
978    // fn  pmaddwd(a: i16x16, b: i16x16) -> i32x8;
979    // fn vpmaddwd(a: i16x32, b: i16x32) -> i32x16;
980    assert_eq!(left_len, right_len);
981    assert_eq!(dest_len.strict_mul(2), left_len);
982
983    for i in 0..dest_len {
984        let j1 = i.strict_mul(2);
985        let left1 = ecx.read_scalar(&ecx.project_index(&left, j1)?)?.to_i16()?;
986        let right1 = ecx.read_scalar(&ecx.project_index(&right, j1)?)?.to_i16()?;
987
988        let j2 = j1.strict_add(1);
989        let left2 = ecx.read_scalar(&ecx.project_index(&left, j2)?)?.to_i16()?;
990        let right2 = ecx.read_scalar(&ecx.project_index(&right, j2)?)?.to_i16()?;
991
992        let dest = ecx.project_index(&dest, i)?;
993
994        // Multiplications are i16*i16->i32, which will not overflow.
995        let mul1 = i32::from(left1).strict_mul(right1.into());
996        let mul2 = i32::from(left2).strict_mul(right2.into());
997        // However, this addition can overflow in the most extreme case
998        // (-0x8000)*(-0x8000)+(-0x8000)*(-0x8000) = 0x80000000
999        let res = mul1.wrapping_add(mul2);
1000
1001        ecx.write_scalar(Scalar::from_i32(res), &dest)?;
1002    }
1003
1004    interp_ok(())
1005}
1006
1007/// Multiplies packed 8-bit unsigned integers from `left` and packed
1008/// signed 8-bit integers from `right` into 16-bit signed integers. Then,
1009/// the saturating sum of the products with indices `2*i` and `2*i+1`
1010/// produces the output at index `i`.
1011///
1012/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_maddubs_epi16>
1013/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_maddubs_epi16>
1014/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm512_maddubs_epi16>
1015fn pmaddbw<'tcx>(
1016    ecx: &mut crate::MiriInterpCx<'tcx>,
1017    left: &OpTy<'tcx>,
1018    right: &OpTy<'tcx>,
1019    dest: &MPlaceTy<'tcx>,
1020) -> InterpResult<'tcx, ()> {
1021    let (left, left_len) = ecx.project_to_simd(left)?;
1022    let (right, right_len) = ecx.project_to_simd(right)?;
1023    let (dest, dest_len) = ecx.project_to_simd(dest)?;
1024
1025    // fn pmaddubsw128(a: u8x16, b: i8x16) -> i16x8;
1026    // fn pmaddubsw(   a: u8x32, b: i8x32) -> i16x16;
1027    // fn vpmaddubsw(  a: u8x64, b: i8x64) -> i16x32;
1028    assert_eq!(left_len, right_len);
1029    assert_eq!(dest_len.strict_mul(2), left_len);
1030
1031    for i in 0..dest_len {
1032        let j1 = i.strict_mul(2);
1033        let left1 = ecx.read_scalar(&ecx.project_index(&left, j1)?)?.to_u8()?;
1034        let right1 = ecx.read_scalar(&ecx.project_index(&right, j1)?)?.to_i8()?;
1035
1036        let j2 = j1.strict_add(1);
1037        let left2 = ecx.read_scalar(&ecx.project_index(&left, j2)?)?.to_u8()?;
1038        let right2 = ecx.read_scalar(&ecx.project_index(&right, j2)?)?.to_i8()?;
1039
1040        let dest = ecx.project_index(&dest, i)?;
1041
1042        // Multiplication of a u8 and an i8 into an i16 cannot overflow.
1043        let mul1 = i16::from(left1).strict_mul(right1.into());
1044        let mul2 = i16::from(left2).strict_mul(right2.into());
1045        let res = mul1.saturating_add(mul2);
1046
1047        ecx.write_scalar(Scalar::from_i16(res), &dest)?;
1048    }
1049
1050    interp_ok(())
1051}
1052
1053/// Shuffle elements in `values` across lanes using the corresponding index in
1054/// `indices`, and store the results in `dest`.
1055///
1056/// This helper is shared by both the 32-bit-lane and 64-bit-lane AVX
1057/// permute-by-index intrinsics. The element type is taken from `values` and
1058/// `dest`, while the index lanes are interpreted at their full width (`i32` or
1059/// `i64`, depending on the intrinsic).
1060///
1061/// For a vector with `N` lanes, only the low `log2(N)` bits of each index are
1062/// used. Equivalently, lane `i` of the result is copied from
1063/// `values[indices[i] & (N - 1)]`.
1064///
1065/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_permutevar8x32_epi32>
1066/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_permutevar8x32_ps>
1067/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm512_permutexvar_epi32>
1068/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm512_permutexvar_epi64>
1069fn permute<'tcx>(
1070    ecx: &mut crate::MiriInterpCx<'tcx>,
1071    values: &OpTy<'tcx>,
1072    indices: &OpTy<'tcx>,
1073    dest: &MPlaceTy<'tcx>,
1074) -> InterpResult<'tcx, ()> {
1075    let (values, values_len) = ecx.project_to_simd(values)?;
1076    let (indices, indices_len) = ecx.project_to_simd(indices)?;
1077    let (dest, dest_len) = ecx.project_to_simd(dest)?;
1078
1079    // fn permd(a: u32x8, b: u32x8) -> u32x8;
1080    // fn permps(a: __m256, b: i32x8) -> __m256;
1081    // fn vpermd(a: i32x16, idx: i32x16) -> i32x16;
1082    // fn vpermq(a: i64x8, b: i64x8) -> i64x8;
1083    assert_eq!(dest_len, values_len);
1084    assert_eq!(dest_len, indices_len);
1085
1086    // Only use the lower 3 bits to index into a vector with 8 lanes,
1087    // or the lower 4 bits when indexing into a 16-lane vector.
1088    assert!(dest_len.is_power_of_two());
1089    let mask = u128::from(dest_len).strict_sub(1);
1090
1091    for i in 0..dest_len {
1092        let dest = ecx.project_index(&dest, i)?;
1093        let index_place = ecx.project_index(&indices, i)?;
1094        let index = ecx.read_scalar(&index_place)?.to_uint(index_place.layout.size)?;
1095        // `mask` is at most `dest_len - 1` which fits in a `u64`, so this cannot fail.
1096        let element = ecx.project_index(&values, u64::try_from(index & mask).unwrap())?;
1097
1098        ecx.copy_op(&element, &dest)?;
1099    }
1100
1101    interp_ok(())
1102}
1103
1104/// Shuffle elements from *two* source registers (`left` and `right`) using
1105/// the corresponding index in `indices`, and store the results in `dest`.
1106///
1107/// For indexing, we basically concatenate `left` and `right`, and index into the concatenation.
1108/// More precisely: For a vector with `N` lanes, the low `log2(N)` bits of each index select a
1109/// lane within a source vector. Bit `log2(N)` selects the source vector (`0` =>
1110/// `left`, `1` => `right`), and all higher bits are ignored.
1111/// Equivalently, lane `i` of the result is copied from
1112/// `src[indices[i] & (N - 1)]` where
1113/// `src = if indices[i] & N == 0 { left } else { right }`.
1114///
1115/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm512_permutex2var_epi64>
1116/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm512_permutex2var_epi8>
1117fn permute2<'tcx>(
1118    ecx: &mut crate::MiriInterpCx<'tcx>,
1119    left: &OpTy<'tcx>,
1120    indices: &OpTy<'tcx>,
1121    right: &OpTy<'tcx>,
1122    dest: &MPlaceTy<'tcx>,
1123) -> InterpResult<'tcx, ()> {
1124    let (left, left_len) = ecx.project_to_simd(left)?;
1125    let (indices, indices_len) = ecx.project_to_simd(indices)?;
1126    let (right, right_len) = ecx.project_to_simd(right)?;
1127    let (dest, dest_len) = ecx.project_to_simd(dest)?;
1128
1129    assert_eq!(dest_len, left_len);
1130    assert_eq!(dest_len, indices_len);
1131    assert_eq!(dest_len, right_len);
1132
1133    // Use the low bits to select a lane within either input vector, and the next bit to
1134    // choose between the two vectors.
1135    assert!(dest_len.is_power_of_two());
1136    let lane_mask = u128::from(dest_len).strict_sub(1);
1137    let vector_select_bit = u128::from(dest_len);
1138
1139    for i in 0..dest_len {
1140        let dest = ecx.project_index(&dest, i)?;
1141        let index_place = ecx.project_index(&indices, i)?;
1142        let index = ecx.read_scalar(&index_place)?.to_uint(index_place.layout.size)?;
1143        // `lane_mask` is at most `dest_len - 1` which fits in a `u64`, so this cannot fail.
1144        let lane = u64::try_from(index & lane_mask).unwrap();
1145        let src = if index & vector_select_bit == 0 { &left } else { &right };
1146        let element = ecx.project_index(src, lane)?;
1147
1148        ecx.copy_op(&element, &dest)?;
1149    }
1150
1151    interp_ok(())
1152}
1153
1154/// Multiplies packed 16-bit signed integer values, truncates the 32-bit
1155/// product to the 18 most significant bits by right-shifting, and then
1156/// divides the 18-bit value by 2 (rounding to nearest) by first adding
1157/// 1 and then taking the bits `1..=16`.
1158///
1159/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mulhrs_epi16>
1160/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_mulhrs_epi16>
1161fn pmulhrsw<'tcx>(
1162    ecx: &mut crate::MiriInterpCx<'tcx>,
1163    left: &OpTy<'tcx>,
1164    right: &OpTy<'tcx>,
1165    dest: &MPlaceTy<'tcx>,
1166) -> InterpResult<'tcx, ()> {
1167    let (left, left_len) = ecx.project_to_simd(left)?;
1168    let (right, right_len) = ecx.project_to_simd(right)?;
1169    let (dest, dest_len) = ecx.project_to_simd(dest)?;
1170
1171    assert_eq!(dest_len, left_len);
1172    assert_eq!(dest_len, right_len);
1173
1174    for i in 0..dest_len {
1175        let left = ecx.read_scalar(&ecx.project_index(&left, i)?)?.to_i16()?;
1176        let right = ecx.read_scalar(&ecx.project_index(&right, i)?)?.to_i16()?;
1177        let dest = ecx.project_index(&dest, i)?;
1178
1179        let res = (i32::from(left).strict_mul(right.into()) >> 14).strict_add(1) >> 1;
1180
1181        // The result of this operation can overflow a signed 16-bit integer.
1182        // When `left` and `right` are -0x8000, the result is 0x8000.
1183        #[expect(clippy::as_conversions)]
1184        let res = res as i16;
1185
1186        ecx.write_scalar(Scalar::from_i16(res), &dest)?;
1187    }
1188
1189    interp_ok(())
1190}
1191
1192/// Perform a carry-less multiplication of two 64-bit integers, selected from `left` and `right` according to `imm8`,
1193/// and store the results in `dst`.
1194///
1195/// `left` and `right` are both vectors of type `len` x i64. Only bits 0 and 4 of `imm8` matter;
1196/// they select the element of `left` and `right`, respectively.
1197///
1198/// `len` is the SIMD vector length (in counts of `i64` values). It is expected to be one of
1199/// `2`, `4`, or `8`.
1200///
1201/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_clmulepi64_si128>
1202fn pclmulqdq<'tcx>(
1203    ecx: &mut MiriInterpCx<'tcx>,
1204    left: &OpTy<'tcx>,
1205    right: &OpTy<'tcx>,
1206    imm8: &OpTy<'tcx>,
1207    dest: &MPlaceTy<'tcx>,
1208    len: u64,
1209) -> InterpResult<'tcx, ()> {
1210    assert_eq!(left.layout, right.layout);
1211    assert_eq!(left.layout.size, dest.layout.size);
1212    assert!([2u64, 4, 8].contains(&len));
1213
1214    // Transmute the input into arrays of `[u64; len]`.
1215    // Transmute the output into an array of `[u128, len / 2]`.
1216
1217    let src_layout = ecx.layout_of(Ty::new_array(ecx.tcx.tcx, ecx.tcx.types.u64, len))?;
1218    let dest_layout = ecx.layout_of(Ty::new_array(ecx.tcx.tcx, ecx.tcx.types.u128, len / 2))?;
1219
1220    let left = left.transmute(src_layout, ecx)?;
1221    let right = right.transmute(src_layout, ecx)?;
1222    let dest = dest.transmute(dest_layout, ecx)?;
1223
1224    let imm8 = ecx.read_scalar(imm8)?.to_u8()?;
1225
1226    for i in 0..(len / 2) {
1227        let lo = i.strict_mul(2);
1228        let hi = i.strict_mul(2).strict_add(1);
1229
1230        // select the 64-bit integer from left that the user specified (low or high)
1231        let index = if (imm8 & 0x01) == 0 { lo } else { hi };
1232        let left = ecx.read_scalar(&ecx.project_index(&left, index)?)?.to_u64()?;
1233
1234        // select the 64-bit integer from right that the user specified (low or high)
1235        let index = if (imm8 & 0x10) == 0 { lo } else { hi };
1236        let right = ecx.read_scalar(&ecx.project_index(&right, index)?)?.to_u64()?;
1237
1238        let result = left.widening_carryless_mul(right);
1239
1240        let dest = ecx.project_index(&dest, i)?;
1241        ecx.write_scalar(Scalar::from_u128(result), &dest)?;
1242    }
1243
1244    interp_ok(())
1245}
1246
1247/// Shuffles bytes from `left` using `right` as pattern. Each 16-byte block is shuffled independently.
1248///
1249/// `left` and `right` are both vectors of type `len` x i8.
1250///
1251/// If the highest bit of a byte in `right` is not set, the corresponding byte in `dest` is taken
1252/// from the current 16-byte block of `left` at the position indicated by the lowest 4 bits of this
1253/// byte in `right`. If the highest bit of a byte in `right` is set, the corresponding byte in
1254/// `dest` is set to `0`.
1255///
1256/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shuffle_epi8>
1257/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_shuffle_epi8>
1258/// <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm512_shuffle_epi8>
1259fn pshufb<'tcx>(
1260    ecx: &mut crate::MiriInterpCx<'tcx>,
1261    left: &OpTy<'tcx>,
1262    right: &OpTy<'tcx>,
1263    dest: &MPlaceTy<'tcx>,
1264) -> InterpResult<'tcx, ()> {
1265    let (left, left_len) = ecx.project_to_simd(left)?;
1266    let (right, right_len) = ecx.project_to_simd(right)?;
1267    let (dest, dest_len) = ecx.project_to_simd(dest)?;
1268
1269    assert_eq!(dest_len, left_len);
1270    assert_eq!(dest_len, right_len);
1271
1272    for i in 0..dest_len {
1273        let right = ecx.read_scalar(&ecx.project_index(&right, i)?)?.to_u8()?;
1274        let dest = ecx.project_index(&dest, i)?;
1275
1276        let res = if right & 0x80 == 0 {
1277            // Shuffle each 128-bit (16-byte) block independently.
1278            let block_offset = i & !15; // round down to previous multiple of 16
1279            let j = block_offset.strict_add((right % 16).into());
1280            ecx.read_scalar(&ecx.project_index(&left, j)?)?
1281        } else {
1282            // If the highest bit in `right` is 1, write zero.
1283            Scalar::from_u8(0)
1284        };
1285
1286        ecx.write_scalar(res, &dest)?;
1287    }
1288
1289    interp_ok(())
1290}
1291
1292/// Packs two N-bit integer vectors to a single N/2-bit integers.
1293///
1294/// The conversion from N-bit to N/2-bit should be provided by `f`.
1295///
1296/// Each 128-bit chunk is treated independently (i.e., the value for
1297/// the is i-th 128-bit chunk of `dest` is calculated with the i-th
1298/// 128-bit chunks of `left` and `right`).
1299fn pack_generic<'tcx>(
1300    ecx: &mut crate::MiriInterpCx<'tcx>,
1301    left: &OpTy<'tcx>,
1302    right: &OpTy<'tcx>,
1303    dest: &MPlaceTy<'tcx>,
1304    f: impl Fn(Scalar) -> InterpResult<'tcx, Scalar>,
1305) -> InterpResult<'tcx, ()> {
1306    assert_eq!(left.layout, right.layout);
1307    assert_eq!(left.layout.size, dest.layout.size);
1308
1309    let (num_chunks, op_items_per_chunk, left) = split_simd_to_128bit_chunks(ecx, left)?;
1310    let (_, _, right) = split_simd_to_128bit_chunks(ecx, right)?;
1311    let (_, dest_items_per_chunk, dest) = split_simd_to_128bit_chunks(ecx, dest)?;
1312
1313    assert_eq!(dest_items_per_chunk, op_items_per_chunk.strict_mul(2));
1314
1315    for i in 0..num_chunks {
1316        let left = ecx.project_index(&left, i)?;
1317        let right = ecx.project_index(&right, i)?;
1318        let dest = ecx.project_index(&dest, i)?;
1319
1320        for j in 0..op_items_per_chunk {
1321            let left = ecx.read_scalar(&ecx.project_index(&left, j)?)?;
1322            let right = ecx.read_scalar(&ecx.project_index(&right, j)?)?;
1323            let left_dest = ecx.project_index(&dest, j)?;
1324            let right_dest = ecx.project_index(&dest, j.strict_add(op_items_per_chunk))?;
1325
1326            let left_res = f(left)?;
1327            let right_res = f(right)?;
1328
1329            ecx.write_scalar(left_res, &left_dest)?;
1330            ecx.write_scalar(right_res, &right_dest)?;
1331        }
1332    }
1333
1334    interp_ok(())
1335}
1336
1337/// Converts two 16-bit integer vectors to a single 8-bit integer
1338/// vector with signed saturation.
1339///
1340/// Each 128-bit chunk is treated independently (i.e., the value for
1341/// the is i-th 128-bit chunk of `dest` is calculated with the i-th
1342/// 128-bit chunks of `left` and `right`).
1343fn packsswb<'tcx>(
1344    ecx: &mut crate::MiriInterpCx<'tcx>,
1345    left: &OpTy<'tcx>,
1346    right: &OpTy<'tcx>,
1347    dest: &MPlaceTy<'tcx>,
1348) -> InterpResult<'tcx, ()> {
1349    pack_generic(ecx, left, right, dest, |op| {
1350        let op = op.to_i16()?;
1351        let res = i8::try_from(op).unwrap_or(if op < 0 { i8::MIN } else { i8::MAX });
1352        interp_ok(Scalar::from_i8(res))
1353    })
1354}
1355
1356/// Converts two 16-bit signed integer vectors to a single 8-bit
1357/// unsigned integer vector with saturation.
1358///
1359/// Each 128-bit chunk is treated independently (i.e., the value for
1360/// the is i-th 128-bit chunk of `dest` is calculated with the i-th
1361/// 128-bit chunks of `left` and `right`).
1362fn packuswb<'tcx>(
1363    ecx: &mut crate::MiriInterpCx<'tcx>,
1364    left: &OpTy<'tcx>,
1365    right: &OpTy<'tcx>,
1366    dest: &MPlaceTy<'tcx>,
1367) -> InterpResult<'tcx, ()> {
1368    pack_generic(ecx, left, right, dest, |op| {
1369        let op = op.to_i16()?;
1370        let res = u8::try_from(op).unwrap_or(if op < 0 { 0 } else { u8::MAX });
1371        interp_ok(Scalar::from_u8(res))
1372    })
1373}
1374
1375/// Converts two 32-bit integer vectors to a single 16-bit integer
1376/// vector with signed saturation.
1377///
1378/// Each 128-bit chunk is treated independently (i.e., the value for
1379/// the is i-th 128-bit chunk of `dest` is calculated with the i-th
1380/// 128-bit chunks of `left` and `right`).
1381fn packssdw<'tcx>(
1382    ecx: &mut crate::MiriInterpCx<'tcx>,
1383    left: &OpTy<'tcx>,
1384    right: &OpTy<'tcx>,
1385    dest: &MPlaceTy<'tcx>,
1386) -> InterpResult<'tcx, ()> {
1387    pack_generic(ecx, left, right, dest, |op| {
1388        let op = op.to_i32()?;
1389        let res = i16::try_from(op).unwrap_or(if op < 0 { i16::MIN } else { i16::MAX });
1390        interp_ok(Scalar::from_i16(res))
1391    })
1392}
1393
1394/// Converts two 32-bit integer vectors to a single 16-bit integer
1395/// vector with unsigned saturation.
1396///
1397/// Each 128-bit chunk is treated independently (i.e., the value for
1398/// the is i-th 128-bit chunk of `dest` is calculated with the i-th
1399/// 128-bit chunks of `left` and `right`).
1400fn packusdw<'tcx>(
1401    ecx: &mut crate::MiriInterpCx<'tcx>,
1402    left: &OpTy<'tcx>,
1403    right: &OpTy<'tcx>,
1404    dest: &MPlaceTy<'tcx>,
1405) -> InterpResult<'tcx, ()> {
1406    pack_generic(ecx, left, right, dest, |op| {
1407        let op = op.to_i32()?;
1408        let res = u16::try_from(op).unwrap_or(if op < 0 { 0 } else { u16::MAX });
1409        interp_ok(Scalar::from_u16(res))
1410    })
1411}
1412
1413/// Negates elements from `left` when the corresponding element in
1414/// `right` is negative. If an element from `right` is zero, zero
1415/// is written to the corresponding output element.
1416/// In other words, multiplies `left` with `right.signum()`.
1417fn psign<'tcx>(
1418    ecx: &mut crate::MiriInterpCx<'tcx>,
1419    left: &OpTy<'tcx>,
1420    right: &OpTy<'tcx>,
1421    dest: &MPlaceTy<'tcx>,
1422) -> InterpResult<'tcx, ()> {
1423    let (left, left_len) = ecx.project_to_simd(left)?;
1424    let (right, right_len) = ecx.project_to_simd(right)?;
1425    let (dest, dest_len) = ecx.project_to_simd(dest)?;
1426
1427    assert_eq!(dest_len, left_len);
1428    assert_eq!(dest_len, right_len);
1429
1430    for i in 0..dest_len {
1431        let dest = ecx.project_index(&dest, i)?;
1432        let left = ecx.read_immediate(&ecx.project_index(&left, i)?)?;
1433        let right = ecx.read_scalar(&ecx.project_index(&right, i)?)?.to_int(dest.layout.size)?;
1434
1435        let res =
1436            ecx.binary_op(mir::BinOp::Mul, &left, &ImmTy::from_int(right.signum(), dest.layout))?;
1437
1438        ecx.write_immediate(*res, &dest)?;
1439    }
1440
1441    interp_ok(())
1442}
1443
1444/// Calcultates either `a + b + cb_in` or `a - b - cb_in` depending on the value
1445/// of `op` and returns both the sum and the overflow bit. `op` is expected to be
1446/// either one of `mir::BinOp::AddWithOverflow` and `mir::BinOp::SubWithOverflow`.
1447fn carrying_add<'tcx>(
1448    ecx: &mut crate::MiriInterpCx<'tcx>,
1449    cb_in: &OpTy<'tcx>,
1450    a: &OpTy<'tcx>,
1451    b: &OpTy<'tcx>,
1452    op: mir::BinOp,
1453) -> InterpResult<'tcx, (ImmTy<'tcx>, Scalar)> {
1454    assert!(op == mir::BinOp::AddWithOverflow || op == mir::BinOp::SubWithOverflow);
1455
1456    let cb_in = ecx.read_scalar(cb_in)?.to_u8()? != 0;
1457    let a = ecx.read_immediate(a)?;
1458    let b = ecx.read_immediate(b)?;
1459
1460    let (sum, overflow1) = ecx.binary_op(op, &a, &b)?.to_pair(ecx);
1461    let (sum, overflow2) =
1462        ecx.binary_op(op, &sum, &ImmTy::from_uint(cb_in, a.layout))?.to_pair(ecx);
1463    let cb_out = overflow1.to_scalar().to_bool()? | overflow2.to_scalar().to_bool()?;
1464
1465    interp_ok((sum, Scalar::from_u8(cb_out.into())))
1466}