Skip to main content

miri/intrinsics/
mod.rs

1#![warn(clippy::arithmetic_side_effects)]
2
3mod aarch64;
4mod loongarch;
5mod math;
6mod simd;
7mod x86;
8
9#[rustfmt::skip] // prevent `use` reordering
10use rand::RngExt;
11use rustc_abi::{Endian, Size};
12use rustc_middle::{mir, ty};
13use rustc_span::{Symbol, sym};
14use rustc_target::spec::Arch;
15
16use self::math::EvalContextExt as _;
17use self::simd::EvalContextExt as _;
18use crate::*;
19
20/// Check that the number of args is what we expect.
21fn check_intrinsic_arg_count<'a, 'tcx, const N: usize>(
22    args: &'a [OpTy<'tcx>],
23) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]>
24where
25    &'a [OpTy<'tcx>; N]: TryFrom<&'a [OpTy<'tcx>]>,
26{
27    if let Ok(ops) = args.try_into() {
28        return interp_ok(ops);
29    }
30    throw_ub_format!(
31        "incorrect number of arguments for intrinsic: got {}, expected {}",
32        args.len(),
33        N
34    )
35}
36
37impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
38pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
39    fn call_intrinsic(
40        &mut self,
41        instance: ty::Instance<'tcx>,
42        args: &[OpTy<'tcx>],
43        dest: &PlaceTy<'tcx>,
44        ret: Option<mir::BasicBlock>,
45        unwind: mir::UnwindAction,
46    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
47        let this = self.eval_context_mut();
48
49        // See if the core engine can handle this intrinsic.
50        if this.eval_intrinsic(instance, args, dest, ret)? {
51            return interp_ok(None);
52        }
53        let intrinsic_name = this.tcx.item_name(instance.def_id());
54        let intrinsic_name = intrinsic_name.as_str();
55
56        let res = this.emulate_intrinsic_by_name(intrinsic_name, instance.args, args, dest, ret)?;
57        res.jump_to_next_block(this, dest, ret, Some(unwind), |this| {
58            // We haven't handled the intrinsic, let's see if we can use a fallback body.
59            if this.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
60                throw_unsup_format!("unimplemented intrinsic: `{intrinsic_name}`")
61            }
62            let intrinsic_fallback_is_spec = Symbol::intern("intrinsic_fallback_is_spec");
63            if this
64                .tcx
65                .get_attrs_by_path(instance.def_id(), &[sym::miri, intrinsic_fallback_is_spec])
66                .next()
67                .is_none()
68            {
69                throw_unsup_format!(
70                    "Miri can only use intrinsic fallback bodies that exactly reflect the specification: they fully check for UB and are as non-deterministic as possible. After verifying that `{intrinsic_name}` does so, add the `#[miri::intrinsic_fallback_is_spec]` attribute to it; also ping @rust-lang/miri when you do that"
71                );
72            }
73            interp_ok(Some(ty::Instance {
74                def: ty::InstanceKind::Item(instance.def_id()),
75                args: instance.args,
76            }))
77        })
78    }
79
80    /// Emulates a Miri-supported intrinsic (not supported by the core engine).
81    /// Returns `Ok(true)` if the intrinsic was handled.
82    fn emulate_intrinsic_by_name(
83        &mut self,
84        intrinsic_name: &str,
85        generic_args: ty::GenericArgsRef<'tcx>,
86        args: &[OpTy<'tcx>],
87        dest: &PlaceTy<'tcx>,
88        ret: Option<mir::BasicBlock>,
89    ) -> InterpResult<'tcx, EmulateItemResult> {
90        let this = self.eval_context_mut();
91
92        if let Some(name) = intrinsic_name.strip_prefix("simd_") {
93            return this.emulate_simd_intrinsic(name, args, dest);
94        }
95
96        match intrinsic_name {
97            // Basic control flow
98            "abort_immediate" => {
99                // Note that `abort_immediate` is also hooked separately in CTFE.
100                throw_machine_stop!(TerminationInfo::Abort(
101                    "the program aborted execution".to_owned()
102                ));
103            }
104            "catch_unwind" => {
105                let [try_fn, data, catch_fn] = check_intrinsic_arg_count(args)?;
106                this.handle_catch_unwind(try_fn, data, catch_fn, dest, ret)?;
107                // This pushed a stack frame, don't jump to `ret`.
108                return interp_ok(EmulateItemResult::AlreadyJumped);
109            }
110
111            // Memory model / provenance manipulation
112            "ptr_mask" => {
113                let [ptr, mask] = check_intrinsic_arg_count(args)?;
114
115                let ptr = this.read_pointer(ptr)?;
116                let mask = this.read_target_usize(mask)?;
117
118                let masked_addr = Size::from_bytes(ptr.addr().bytes() & mask);
119
120                this.write_pointer(Pointer::new(ptr.provenance, masked_addr), dest)?;
121            }
122
123            // We want to return either `true` or `false` at random, or else something like
124            // ```
125            // if !is_val_statically_known(0) { unreachable_unchecked(); }
126            // ```
127            // Would not be considered UB, or the other way around (`is_val_statically_known(0)`).
128            "is_val_statically_known" => {
129                let [_arg] = check_intrinsic_arg_count(args)?;
130                // FIXME: should we check for validity here? It's tricky because we do not have a
131                // place. Codegen does not seem to set any attributes like `noundef` for intrinsic
132                // calls, so we don't *have* to do anything.
133                let branch: bool = this.machine.rng.get_mut().random();
134                this.write_scalar(Scalar::from_bool(branch), dest)?;
135            }
136
137            // Other
138            "breakpoint" => {
139                let [] = check_intrinsic_arg_count(args)?;
140                // normally this would raise a SIGTRAP, which aborts if no debugger is connected
141                throw_machine_stop!(TerminationInfo::Abort(format!("trace/breakpoint trap")))
142            }
143
144            "assert_inhabited" | "assert_zero_valid" | "assert_mem_uninitialized_valid" => {
145                // Make these a NOP, so we get the better Miri-native error messages.
146            }
147
148            _ => return this.emulate_math_intrinsic(intrinsic_name, generic_args, args, dest),
149        }
150
151        interp_ok(EmulateItemResult::NeedsReturn)
152    }
153
154    fn call_llvm_intrinsic(
155        &mut self,
156        instance: ty::Instance<'tcx>,
157        args: &[OpTy<'tcx>],
158        dest: &PlaceTy<'tcx>,
159        ret: Option<mir::BasicBlock>,
160    ) -> InterpResult<'tcx> {
161        let this = self.eval_context_mut();
162
163        let link_name = this.tcx.codegen_fn_attrs(instance.def_id()).symbol_name.unwrap();
164
165        // These are anyway mostly vector intrinsics and vectors live in memory.
166        let dest = this.force_allocation(dest)?;
167
168        let res = 'handled: {
169            match link_name.as_str() {
170                // LLVM intrinsics
171                "llvm.prefetch.p0" => {
172                    let [p, rw, loc, ty] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
173
174                    let _ = this.read_pointer(p)?;
175                    let rw = this.read_scalar(rw)?.to_i32()?;
176                    let loc = this.read_scalar(loc)?.to_i32()?;
177                    let ty = this.read_scalar(ty)?.to_i32()?;
178
179                    if ty == 1 {
180                        // Data cache prefetch.
181                        // Notably, we do not have to check the pointer, this operation is never UB!
182
183                        if !matches!(rw, 0 | 1) {
184                            throw_unsup_format!(
185                                "invalid `rw` value passed to `llvm.prefetch`: {rw}"
186                            );
187                        }
188                        if !matches!(loc, 0..=3) {
189                            throw_unsup_format!(
190                                "invalid `loc` value passed to `llvm.prefetch`: {loc}"
191                            );
192                        }
193                    } else {
194                        throw_unsup_format!("unsupported `llvm.prefetch` type argument: {ty}");
195                    }
196                }
197                // Used to implement the x86 `_mm{,256,512}_popcnt_epi{8,16,32,64}` and wasm
198                // `{i,u}8x16_popcnt` functions.
199                name if name.starts_with("llvm.ctpop.v")
200                    && this.tcx.sess.target.endian == Endian::Little =>
201                {
202                    let [op] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
203
204                    let (op, op_len) = this.project_to_simd(op)?;
205                    let (dest, dest_len) = this.project_to_simd(&dest)?;
206
207                    assert_eq!(dest_len, op_len);
208
209                    for i in 0..dest_len {
210                        let op = this.read_immediate(&this.project_index(&op, i)?)?;
211                        // Use `to_uint` to get a zero-extended `u128`. Those
212                        // extra zeros will not affect `count_ones`.
213                        let res = op.to_scalar().to_uint(op.layout.size)?.count_ones();
214
215                        this.write_scalar(
216                            Scalar::from_uint(res, op.layout.size),
217                            &this.project_index(&dest, i)?,
218                        )?;
219                    }
220                }
221
222                // Target-specific shims
223                name if name.starts_with("llvm.x86.")
224                    && matches!(this.tcx.sess.target.arch, Arch::X86 | Arch::X86_64)
225                    && this.tcx.sess.target.endian == Endian::Little =>
226                    break 'handled x86::EvalContextExt::emulate_x86_intrinsic(
227                        this, link_name, args, &dest,
228                    )?,
229                name if name.starts_with("llvm.aarch64.")
230                    && this.tcx.sess.target.arch == Arch::AArch64
231                    && this.tcx.sess.target.endian == Endian::Little =>
232                    break 'handled aarch64::EvalContextExt::emulate_aarch64_intrinsic(
233                        this, link_name, args, &dest,
234                    )?,
235                name if name.starts_with("llvm.loongarch.")
236                    && matches!(
237                        this.tcx.sess.target.arch,
238                        Arch::LoongArch32 | Arch::LoongArch64
239                    )
240                    && this.tcx.sess.target.endian == Endian::Little =>
241                    break 'handled loongarch::EvalContextExt::emulate_loongarch_intrinsic(
242                        this, link_name, args, &dest,
243                    )?,
244                _ => break 'handled EmulateItemResult::NotSupported,
245            }
246            EmulateItemResult::NeedsReturn
247        };
248
249        // The rest either implements the logic, or falls back to `lookup_exported_symbol`.
250        res.jump_to_next_block(this, &dest.clone().into(), ret, None, |this| {
251            throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(format!(
252                "can't call LLVM intrinsic `{link_name}` on architecture `{arch}`",
253                arch = this.tcx.sess.target.arch,
254            )));
255        })
256    }
257}