1 //! This module contains the `InterpCx` methods for executing a single step of the interpreter.
3 //! The main entry point is the `step` method.
8 use rustc_middle::mir::interpret::{InterpResult, Scalar};
9 use rustc_middle::ty::layout::LayoutOf;
11 use super::{ImmTy, InterpCx, Machine};
13 /// Classify whether an operator is "left-homogeneous", i.e., the LHS has the
14 /// same type as the result.
16 fn binop_left_homogeneous(op: mir::BinOp) -> bool {
17 use rustc_middle::mir::BinOp::*;
19 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Offset | Shl | Shr => true,
20 Eq | Ne | Lt | Le | Gt | Ge => false,
23 /// Classify whether an operator is "right-homogeneous", i.e., the RHS has the
24 /// same type as the LHS.
26 fn binop_right_homogeneous(op: mir::BinOp) -> bool {
27 use rustc_middle::mir::BinOp::*;
29 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Eq | Ne | Lt | Le | Gt | Ge => true,
30 Offset | Shl | Shr => false,
34 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
35 /// Returns `true` as long as there are more things to do.
37 /// This is used by [priroda](https://github.com/oli-obk/priroda)
39 /// This is marked `#inline(always)` to work around adversarial codegen when `opt-level = 3`
41 pub fn step(&mut self) -> InterpResult<'tcx, bool> {
42 if self.stack().is_empty() {
46 let Either::Left(loc) = self.frame().loc else {
47 // We are unwinding and this fn has no cleanup code.
48 // Just go on unwinding.
49 trace!("unwinding: skipping frame");
50 self.pop_stack_frame(/* unwinding */ true)?;
53 let basic_block = &self.body().basic_blocks[loc.block];
55 if let Some(stmt) = basic_block.statements.get(loc.statement_index) {
56 let old_frames = self.frame_idx();
57 self.statement(stmt)?;
58 // Make sure we are not updating `statement_index` of the wrong frame.
59 assert_eq!(old_frames, self.frame_idx());
60 // Advance the program counter.
61 self.frame_mut().loc.as_mut().left().unwrap().statement_index += 1;
65 M::before_terminator(self)?;
67 let terminator = basic_block.terminator();
68 self.terminator(terminator)?;
72 /// Runs the interpretation logic for the given `mir::Statement` at the current frame and
73 /// statement counter.
75 /// This does NOT move the statement counter forward, the caller has to do that!
76 pub fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> {
79 use rustc_middle::mir::StatementKind::*;
82 Assign(box (place, rvalue)) => self.eval_rvalue_into_place(rvalue, *place)?,
84 SetDiscriminant { place, variant_index } => {
85 let dest = self.eval_place(**place)?;
86 self.write_discriminant(*variant_index, &dest)?;
90 let dest = self.eval_place(**place)?;
91 self.write_uninit(&dest)?;
94 // Mark locals as alive
95 StorageLive(local) => {
96 self.storage_live(*local)?;
99 // Mark locals as dead
100 StorageDead(local) => {
101 self.storage_dead(*local)?;
104 // No dynamic semantics attached to `FakeRead`; MIR
105 // interpreter is solely intended for borrowck'ed code.
109 Retag(kind, place) => {
110 let dest = self.eval_place(**place)?;
111 M::retag_place_contents(self, *kind, &dest)?;
114 Intrinsic(box intrinsic) => self.emulate_nondiverging_intrinsic(intrinsic)?,
116 // Statements we do not track.
117 AscribeUserType(..) => {}
119 // Currently, Miri discards Coverage statements. Coverage statements are only injected
120 // via an optional compile time MIR pass and have no side effects. Since Coverage
121 // statements don't exist at the source level, it is safe for Miri to ignore them, even
122 // for undefined behavior (UB) checks.
124 // A coverage counter inside a const expression (for example, a counter injected in a
125 // const function) is discarded when the const is evaluated at compile time. Whether
126 // this should change, and/or how to implement a const eval counter, is a subject of the
129 // FIXME(#73156): Handle source code coverage in const eval
132 ConstEvalCounter => {
133 M::increment_const_eval_counter(self)?;
136 // Defined to do nothing. These are added by optimization passes, to avoid changing the
137 // size of MIR constantly.
144 /// Evaluate an assignment statement.
146 /// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
147 /// type writes its results directly into the memory specified by the place.
148 pub fn eval_rvalue_into_place(
150 rvalue: &mir::Rvalue<'tcx>,
151 place: mir::Place<'tcx>,
152 ) -> InterpResult<'tcx> {
153 let dest = self.eval_place(place)?;
154 // FIXME: ensure some kind of non-aliasing between LHS and RHS?
155 // Also see https://github.com/rust-lang/rust/issues/68364.
157 use rustc_middle::mir::Rvalue::*;
159 ThreadLocalRef(did) => {
160 let ptr = M::thread_local_static_base_pointer(self, did)?;
161 self.write_pointer(ptr, &dest)?;
164 Use(ref operand) => {
165 // Avoid recomputing the layout
166 let op = self.eval_operand(operand, Some(dest.layout))?;
167 self.copy_op(&op, &dest, /*allow_transmute*/ false)?;
170 CopyForDeref(place) => {
171 let op = self.eval_place_to_op(place, Some(dest.layout))?;
172 self.copy_op(&op, &dest, /* allow_transmute*/ false)?;
175 BinaryOp(bin_op, box (ref left, ref right)) => {
176 let layout = binop_left_homogeneous(bin_op).then_some(dest.layout);
177 let left = self.read_immediate(&self.eval_operand(left, layout)?)?;
178 let layout = binop_right_homogeneous(bin_op).then_some(left.layout);
179 let right = self.read_immediate(&self.eval_operand(right, layout)?)?;
180 self.binop_ignore_overflow(bin_op, &left, &right, &dest)?;
183 CheckedBinaryOp(bin_op, box (ref left, ref right)) => {
184 // Due to the extra boolean in the result, we can never reuse the `dest.layout`.
185 let left = self.read_immediate(&self.eval_operand(left, None)?)?;
186 let layout = binop_right_homogeneous(bin_op).then_some(left.layout);
187 let right = self.read_immediate(&self.eval_operand(right, layout)?)?;
188 self.binop_with_overflow(
189 bin_op, /*force_overflow_checks*/ false, &left, &right, &dest,
193 UnaryOp(un_op, ref operand) => {
194 // The operand always has the same type as the result.
195 let val = self.read_immediate(&self.eval_operand(operand, Some(dest.layout))?)?;
196 let val = self.unary_op(un_op, &val)?;
197 assert_eq!(val.layout, dest.layout, "layout mismatch for result of {:?}", un_op);
198 self.write_immediate(*val, &dest)?;
201 Aggregate(box ref kind, ref operands) => {
202 self.write_aggregate(kind, operands, &dest)?;
205 Repeat(ref operand, _) => {
206 let src = self.eval_operand(operand, None)?;
207 assert!(src.layout.is_sized());
208 let dest = self.force_allocation(&dest)?;
209 let length = dest.len(self)?;
212 // Nothing to copy... but let's still make sure that `dest` as a place is valid.
213 self.get_place_alloc_mut(&dest)?;
215 // Write the src to the first element.
216 let first = self.mplace_field(&dest, 0)?;
217 self.copy_op(&src, &first.into(), /*allow_transmute*/ false)?;
219 // This is performance-sensitive code for big static/const arrays! So we
220 // avoid writing each operand individually and instead just make many copies
221 // of the first element.
222 let elem_size = first.layout.size;
223 let first_ptr = first.ptr;
224 let rest_ptr = first_ptr.offset(elem_size, self)?;
225 // For the alignment of `rest_ptr`, we crucially do *not* use `first.align` as
226 // that place might be more aligned than its type mandates (a `u8` array could
227 // be 4-aligned if it sits at the right spot in a struct). Instead we use
228 // `first.layout.align`, i.e., the alignment given by the type.
229 self.mem_copy_repeatedly(
233 first.layout.align.abi,
236 /*nonoverlapping:*/ true,
242 let src = self.eval_place(place)?;
243 let op = self.place_to_op(&src)?;
244 let len = op.len(self)?;
245 self.write_scalar(Scalar::from_machine_usize(len, self), &dest)?;
248 Ref(_, borrow_kind, place) => {
249 let src = self.eval_place(place)?;
250 let place = self.force_allocation(&src)?;
251 let val = ImmTy::from_immediate(place.to_ref(self), dest.layout);
252 // A fresh reference was created, make sure it gets retagged.
253 let val = M::retag_ptr_value(
255 if borrow_kind.allows_two_phase_borrow() {
256 mir::RetagKind::TwoPhase
258 mir::RetagKind::Default
262 self.write_immediate(*val, &dest)?;
265 AddressOf(_, place) => {
266 // Figure out whether this is an addr_of of an already raw place.
267 let place_base_raw = if place.has_deref() {
268 let ty = self.frame().body.local_decls[place.local].ty;
271 // Not a deref, and thus not raw.
275 let src = self.eval_place(place)?;
276 let place = self.force_allocation(&src)?;
277 let mut val = ImmTy::from_immediate(place.to_ref(self), dest.layout);
279 // If this was not already raw, it needs retagging.
280 val = M::retag_ptr_value(self, mir::RetagKind::Raw, &val)?;
282 self.write_immediate(*val, &dest)?;
285 NullaryOp(null_op, ty) => {
286 let ty = self.subst_from_current_frame_and_normalize_erasing_regions(ty)?;
287 let layout = self.layout_of(ty)?;
288 if layout.is_unsized() {
289 // FIXME: This should be a span_bug (#80742)
290 self.tcx.sess.delay_span_bug(
291 self.frame().current_span(),
292 &format!("Nullary MIR operator called for unsized type {}", ty),
294 throw_inval!(SizeOfUnsizedType(ty));
296 let val = match null_op {
297 mir::NullOp::SizeOf => layout.size.bytes(),
298 mir::NullOp::AlignOf => layout.align.abi.bytes(),
300 self.write_scalar(Scalar::from_machine_usize(val, self), &dest)?;
303 ShallowInitBox(ref operand, _) => {
304 let src = self.eval_operand(operand, None)?;
305 let v = self.read_immediate(&src)?;
306 self.write_immediate(*v, &dest)?;
309 Cast(cast_kind, ref operand, cast_ty) => {
310 let src = self.eval_operand(operand, None)?;
312 self.subst_from_current_frame_and_normalize_erasing_regions(cast_ty)?;
313 self.cast(&src, cast_kind, cast_ty, &dest)?;
316 Discriminant(place) => {
317 let op = self.eval_place_to_op(place, None)?;
318 let discr_val = self.read_discriminant(&op)?.0;
319 self.write_scalar(discr_val, &dest)?;
323 trace!("{:?}", self.dump_place(*dest));
328 /// Evaluate the given terminator. Will also adjust the stack frame and statement position accordingly.
329 fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> InterpResult<'tcx> {
330 info!("{:?}", terminator.kind);
332 self.eval_terminator(terminator)?;
333 if !self.stack().is_empty() {
334 if let Either::Left(loc) = self.frame().loc {
335 info!("// executing {:?}", loc.block);