Skip to main content

miri/intrinsics/x86/
bmi.rs

1use rustc_span::Symbol;
2use rustc_target::spec::Arch;
3
4use crate::*;
5
6impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
7pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
8    fn emulate_x86_bmi_intrinsic(
9        &mut self,
10        link_name: Symbol,
11        args: &[OpTy<'tcx>],
12        dest: &MPlaceTy<'tcx>,
13    ) -> InterpResult<'tcx, EmulateItemResult> {
14        let this = self.eval_context_mut();
15
16        // Prefix should have already been checked.
17        let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.bmi.").unwrap();
18
19        // The intrinsics are suffixed with the bit size of their operands.
20        let (is_64_bit, unprefixed_name) = if unprefixed_name.ends_with("64") {
21            (true, unprefixed_name.strip_suffix(".64").unwrap_or(""))
22        } else {
23            (false, unprefixed_name.strip_suffix(".32").unwrap_or(""))
24        };
25
26        // All intrinsics of the "bmi" namespace belong to the "bmi2" ISA extension.
27        // The exception is "bextr", which belongs to "bmi1".
28        let target_feature = if unprefixed_name == "bextr" { "bmi1" } else { "bmi2" };
29        this.expect_target_feature_for_intrinsic(link_name, target_feature)?;
30
31        if is_64_bit && this.tcx.sess.target.arch != Arch::X86_64 {
32            return interp_ok(EmulateItemResult::NotSupported);
33        }
34
35        let [left, right] = this.check_shim_sig_unadjusted(link_name, args)?;
36        let left = this.read_scalar(left)?;
37        let right = this.read_scalar(right)?;
38
39        let left = if is_64_bit { left.to_u64()? } else { u64::from(left.to_u32()?) };
40        let right = if is_64_bit { right.to_u64()? } else { u64::from(right.to_u32()?) };
41
42        let result = match unprefixed_name {
43            // Extract a contiguous range of bits from an unsigned integer.
44            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_bextr_u32
45            "bextr" => {
46                let start = u32::try_from(right & 0xff).unwrap();
47                let len = u32::try_from((right >> 8) & 0xff).unwrap();
48                let shifted = left.checked_shr(start).unwrap_or(0);
49                // Keep the `len` lowest bits of `shifted`, or all bits if `len` is too big.
50                if len >= 64 { shifted } else { shifted & 1u64.wrapping_shl(len).wrapping_sub(1) }
51            }
52            // Create a copy of an unsigned integer with bits above a certain index cleared.
53            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_bzhi_u32
54            "bzhi" => {
55                let index = u32::try_from(right & 0xff).unwrap();
56                // Keep the `index` lowest bits of `left`, or all bits if `index` is too big.
57                if index >= 64 { left } else { left & 1u64.wrapping_shl(index).wrapping_sub(1) }
58            }
59            // Extract bit values of an unsigned integer at positions marked by a mask.
60            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_pext_u32
61            "pext" => {
62                let mut mask = right;
63                let mut i = 0u32;
64                let mut result = 0;
65                // Iterate over the mask one 1-bit at a time, from
66                // the least significant bit to the most significant bit.
67                while mask != 0 {
68                    // Extract the bit marked by the mask's least significant set bit
69                    // and put it at position `i` of the result.
70                    result |= u64::from(left & (1 << mask.trailing_zeros()) != 0) << i;
71                    i = i.wrapping_add(1);
72                    // Clear the least significant set bit.
73                    mask &= mask.wrapping_sub(1);
74                }
75                result
76            }
77            // Deposit bit values of an unsigned integer to positions marked by a mask.
78            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_pdep_u32
79            "pdep" => {
80                let mut mask = right;
81                let mut set = left;
82                let mut result = 0;
83                // Iterate over the mask one 1-bit at a time, from
84                // the least significant bit to the most significant bit.
85                while mask != 0 {
86                    // Put rightmost bit of `set` at the position of the current `mask` bit.
87                    result |= (set & 1) << mask.trailing_zeros();
88                    // Go to next bit of `set`.
89                    set >>= 1;
90                    // Clear the least significant set bit.
91                    mask &= mask.wrapping_sub(1);
92                }
93                result
94            }
95            _ => return interp_ok(EmulateItemResult::NotSupported),
96        };
97
98        let result = if is_64_bit {
99            Scalar::from_u64(result)
100        } else {
101            Scalar::from_u32(u32::try_from(result).unwrap())
102        };
103        this.write_scalar(result, dest)?;
104
105        interp_ok(EmulateItemResult::NeedsReturn)
106    }
107}