1 //! This module contains the `InterpCx` methods for executing a single step of the interpreter.
3 //! The main entry point is the `step` method.
6 use rustc::ty::layout::LayoutOf;
7 use rustc::mir::interpret::{InterpResult, Scalar, PointerArithmetic};
9 use super::{InterpCx, Machine};
11 /// Classify whether an operator is "left-homogeneous", i.e., the LHS has the
12 /// same type as the result.
14 fn binop_left_homogeneous(op: mir::BinOp) -> bool {
15 use rustc::mir::BinOp::*;
17 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr |
20 Eq | Ne | Lt | Le | Gt | Ge =>
24 /// Classify whether an operator is "right-homogeneous", i.e., the RHS has the
25 /// same type as the LHS.
27 fn binop_right_homogeneous(op: mir::BinOp) -> bool {
28 use rustc::mir::BinOp::*;
30 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr |
31 Eq | Ne | Lt | Le | Gt | Ge =>
38 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
39 pub fn run(&mut self) -> InterpResult<'tcx> {
44 /// Returns `true` as long as there are more things to do.
46 /// This is used by [priroda](https://github.com/oli-obk/priroda)
47 pub fn step(&mut self) -> InterpResult<'tcx, bool> {
48 if self.stack.is_empty() {
52 let block = match self.frame().block {
55 // We are unwinding and this fn has no cleanup code.
56 // Just go on unwinding.
57 trace!("unwinding: skipping frame");
58 self.pop_stack_frame(/* unwinding */ true)?;
62 let stmt_id = self.frame().stmt;
63 let body = self.body();
64 let basic_block = &body.basic_blocks()[block];
66 let old_frames = self.cur_frame();
68 if let Some(stmt) = basic_block.statements.get(stmt_id) {
69 assert_eq!(old_frames, self.cur_frame());
70 self.statement(stmt)?;
74 M::before_terminator(self)?;
76 let terminator = basic_block.terminator();
77 assert_eq!(old_frames, self.cur_frame());
78 self.terminator(terminator)?;
82 fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> {
85 use rustc::mir::StatementKind::*;
87 // Some statements (e.g., box) push new stack frames.
88 // We have to record the stack frame number *before* executing the statement.
89 let frame_idx = self.cur_frame();
90 self.tcx.span = stmt.source_info.span;
91 self.memory.tcx.span = stmt.source_info.span;
94 Assign(box(ref place, ref rvalue)) => self.eval_rvalue_into_place(rvalue, place)?,
100 let dest = self.eval_place(place)?;
101 self.write_discriminant_index(variant_index, dest)?;
104 // Mark locals as alive
105 StorageLive(local) => {
106 let old_val = self.storage_live(local)?;
107 self.deallocate_local(old_val)?;
110 // Mark locals as dead
111 StorageDead(local) => {
112 let old_val = self.storage_dead(local);
113 self.deallocate_local(old_val)?;
116 // No dynamic semantics attached to `FakeRead`; MIR
117 // interpreter is solely intended for borrowck'ed code.
121 Retag(kind, ref place) => {
122 let dest = self.eval_place(place)?;
123 M::retag(self, kind, dest)?;
126 // Statements we do not track.
127 AscribeUserType(..) => {}
129 // Defined to do nothing. These are added by optimization passes, to avoid changing the
130 // size of MIR constantly.
133 InlineAsm { .. } => throw_unsup_format!("inline assembly is not supported"),
136 self.stack[frame_idx].stmt += 1;
140 /// Evaluate an assignment statement.
142 /// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
143 /// type writes its results directly into the memory specified by the place.
144 pub fn eval_rvalue_into_place(
146 rvalue: &mir::Rvalue<'tcx>,
147 place: &mir::Place<'tcx>,
148 ) -> InterpResult<'tcx> {
149 let dest = self.eval_place(place)?;
151 use rustc::mir::Rvalue::*;
153 Use(ref operand) => {
154 // Avoid recomputing the layout
155 let op = self.eval_operand(operand, Some(dest.layout))?;
156 self.copy_op(op, dest)?;
159 BinaryOp(bin_op, ref left, ref right) => {
160 let layout = binop_left_homogeneous(bin_op).then_some(dest.layout);
161 let left = self.read_immediate(self.eval_operand(left, layout)?)?;
162 let layout = binop_right_homogeneous(bin_op).then_some(left.layout);
163 let right = self.read_immediate(self.eval_operand(right, layout)?)?;
164 self.binop_ignore_overflow(
172 CheckedBinaryOp(bin_op, ref left, ref right) => {
173 // Due to the extra boolean in the result, we can never reuse the `dest.layout`.
174 let left = self.read_immediate(self.eval_operand(left, None)?)?;
175 let layout = binop_right_homogeneous(bin_op).then_some(left.layout);
176 let right = self.read_immediate(self.eval_operand(right, layout)?)?;
177 self.binop_with_overflow(
185 UnaryOp(un_op, ref operand) => {
186 // The operand always has the same type as the result.
187 let val = self.read_immediate(self.eval_operand(operand, Some(dest.layout))?)?;
188 let val = self.unary_op(un_op, val)?;
189 assert_eq!(val.layout, dest.layout, "layout mismatch for result of {:?}", un_op);
190 self.write_immediate(*val, dest)?;
193 Aggregate(ref kind, ref operands) => {
194 let (dest, active_field_index) = match **kind {
195 mir::AggregateKind::Adt(adt_def, variant_index, _, _, active_field_index) => {
196 self.write_discriminant_index(variant_index, dest)?;
197 if adt_def.is_enum() {
198 (self.place_downcast(dest, variant_index)?, active_field_index)
200 (dest, active_field_index)
206 for (i, operand) in operands.iter().enumerate() {
207 let op = self.eval_operand(operand, None)?;
208 // Ignore zero-sized fields.
209 if !op.layout.is_zst() {
210 let field_index = active_field_index.unwrap_or(i);
211 let field_dest = self.place_field(dest, field_index as u64)?;
212 self.copy_op(op, field_dest)?;
217 Repeat(ref operand, _) => {
218 let op = self.eval_operand(operand, None)?;
219 let dest = self.force_allocation(dest)?;
220 let length = dest.len(self)?;
222 if let Some(first_ptr) = self.check_mplace_access(dest, None)? {
224 let first = self.mplace_field(dest, 0)?;
225 self.copy_op(op, first.into())?;
228 let elem_size = first.layout.size;
229 // Copy the rest. This is performance-sensitive code
230 // for big static/const arrays!
231 let rest_ptr = first_ptr.offset(elem_size, self)?;
232 self.memory.copy_repeatedly(
233 first_ptr, rest_ptr, elem_size, length - 1, /*nonoverlapping:*/true
240 // FIXME(CTFE): don't allow computing the length of arrays in const eval
241 let src = self.eval_place(place)?;
242 let mplace = self.force_allocation(src)?;
243 let len = mplace.len(self)?;
244 let size = self.pointer_size();
246 Scalar::from_uint(len, size),
251 AddressOf(_, ref place) | Ref(_, _, ref place) => {
252 let src = self.eval_place(place)?;
253 let place = self.force_allocation(src)?;
254 if place.layout.size.bytes() > 0 {
255 // definitely not a ZST
256 assert!(place.ptr.is_ptr(), "non-ZST places should be normalized to `Pointer`");
258 self.write_immediate(place.to_ref(), dest)?;
261 NullaryOp(mir::NullOp::Box, _) => {
262 M::box_alloc(self, dest)?;
265 NullaryOp(mir::NullOp::SizeOf, ty) => {
266 let ty = self.subst_from_frame_and_normalize_erasing_regions(ty);
267 let layout = self.layout_of(ty)?;
268 assert!(!layout.is_unsized(),
269 "SizeOf nullary MIR operator called for unsized type");
270 let size = self.pointer_size();
272 Scalar::from_uint(layout.size.bytes(), size),
277 Cast(kind, ref operand, _) => {
278 let src = self.eval_operand(operand, None)?;
279 self.cast(src, kind, dest)?;
282 Discriminant(ref place) => {
283 let op = self.eval_place_to_op(place, None)?;
284 let discr_val = self.read_discriminant(op)?.0;
285 let size = dest.layout.size;
286 self.write_scalar(Scalar::from_uint(discr_val, size), dest)?;
290 self.dump_place(*dest);
295 fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> InterpResult<'tcx> {
296 info!("{:?}", terminator.kind);
297 self.tcx.span = terminator.source_info.span;
298 self.memory.tcx.span = terminator.source_info.span;
300 let old_stack = self.cur_frame();
301 let old_bb = self.frame().block;
303 self.eval_terminator(terminator)?;
304 if !self.stack.is_empty() {
305 // This should change *something*
306 debug_assert!(self.cur_frame() != old_stack || self.frame().block != old_bb);
307 if let Some(block) = self.frame().block {
308 info!("// executing {:?}", block);