]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/step.rs
Add comment about step being used by priroda
[rust.git] / src / librustc_mir / interpret / step.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This module contains the `EvalContext` methods for executing a single step of the interpreter.
12 //!
13 //! The main entry point is the `step` method.
14
15 use rustc::mir;
16 use rustc::ty::layout::LayoutOf;
17 use rustc::mir::interpret::{EvalResult, Scalar, PointerArithmetic};
18
19 use super::{EvalContext, Machine};
20
21 /// Classify whether an operator is "left-homogeneous", i.e. the LHS has the
22 /// same type as the result.
23 #[inline]
24 fn binop_left_homogeneous(op: mir::BinOp) -> bool {
25     use rustc::mir::BinOp::*;
26     match op {
27         Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr |
28         Offset | Shl | Shr =>
29             true,
30         Eq | Ne | Lt | Le | Gt | Ge =>
31             false,
32     }
33 }
34 /// Classify whether an operator is "right-homogeneous", i.e. the RHS has the
35 /// same type as the LHS.
36 #[inline]
37 fn binop_right_homogeneous(op: mir::BinOp) -> bool {
38     use rustc::mir::BinOp::*;
39     match op {
40         Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr |
41         Eq | Ne | Lt | Le | Gt | Ge =>
42             true,
43         Offset | Shl | Shr =>
44             false,
45     }
46 }
47
48 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
49     pub fn run(&mut self) -> EvalResult<'tcx> {
50         while self.step()? {}
51         Ok(())
52     }
53
54     /// Returns true as long as there are more things to do.
55     ///
56     /// This is used by [priroda](https://github.com/oli-obk/priroda)
57     pub fn step(&mut self) -> EvalResult<'tcx, bool> {
58         if self.stack.is_empty() {
59             return Ok(false);
60         }
61
62         let block = self.frame().block;
63         let stmt_id = self.frame().stmt;
64         let mir = self.mir();
65         let basic_block = &mir.basic_blocks()[block];
66
67         let old_frames = self.cur_frame();
68
69         if let Some(stmt) = basic_block.statements.get(stmt_id) {
70             assert_eq!(old_frames, self.cur_frame());
71             self.statement(stmt)?;
72             return Ok(true);
73         }
74
75         M::before_terminator(self)?;
76
77         let terminator = basic_block.terminator();
78         assert_eq!(old_frames, self.cur_frame());
79         self.terminator(terminator)?;
80         Ok(true)
81     }
82
83     fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> EvalResult<'tcx> {
84         debug!("{:?}", stmt);
85
86         use rustc::mir::StatementKind::*;
87
88         // Some statements (e.g. box) push new stack frames.
89         // We have to record the stack frame number *before* executing the statement.
90         let frame_idx = self.cur_frame();
91         self.tcx.span = stmt.source_info.span;
92         self.memory.tcx.span = stmt.source_info.span;
93
94         match stmt.kind {
95             Assign(ref place, ref rvalue) => self.eval_rvalue_into_place(rvalue, place)?,
96
97             SetDiscriminant {
98                 ref place,
99                 variant_index,
100             } => {
101                 let dest = self.eval_place(place)?;
102                 self.write_discriminant_index(variant_index, dest)?;
103             }
104
105             // Mark locals as alive
106             StorageLive(local) => {
107                 let old_val = self.storage_live(local)?;
108                 self.deallocate_local(old_val)?;
109             }
110
111             // Mark locals as dead
112             StorageDead(local) => {
113                 let old_val = self.storage_dead(local);
114                 self.deallocate_local(old_val)?;
115             }
116
117             // No dynamic semantics attached to `FakeRead`; MIR
118             // interpreter is solely intended for borrowck'ed code.
119             FakeRead(..) => {}
120
121             // Validity checks.
122             Validate(op, ref places) => {
123                 for operand in places {
124                     M::validation_op(self, op, operand)?;
125                 }
126             }
127
128             EndRegion(..) => {}
129             AscribeUserType(..) => {}
130
131             // Defined to do nothing. These are added by optimization passes, to avoid changing the
132             // size of MIR constantly.
133             Nop => {}
134
135             InlineAsm { .. } => return err!(InlineAsm),
136         }
137
138         self.stack[frame_idx].stmt += 1;
139         Ok(())
140     }
141
142     /// Evaluate an assignment statement.
143     ///
144     /// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
145     /// type writes its results directly into the memory specified by the place.
146     fn eval_rvalue_into_place(
147         &mut self,
148         rvalue: &mir::Rvalue<'tcx>,
149         place: &mir::Place<'tcx>,
150     ) -> EvalResult<'tcx> {
151         let dest = self.eval_place(place)?;
152
153         use rustc::mir::Rvalue::*;
154         match *rvalue {
155             Use(ref operand) => {
156                 // Avoid recomputing the layout
157                 let op = self.eval_operand(operand, Some(dest.layout))?;
158                 self.copy_op(op, dest)?;
159             }
160
161             BinaryOp(bin_op, ref left, ref right) => {
162                 let layout = if binop_left_homogeneous(bin_op) { Some(dest.layout) } else { None };
163                 let left = self.read_value(self.eval_operand(left, layout)?)?;
164                 let layout = if binop_right_homogeneous(bin_op) { Some(left.layout) } else { None };
165                 let right = self.read_value(self.eval_operand(right, layout)?)?;
166                 self.binop_ignore_overflow(
167                     bin_op,
168                     left,
169                     right,
170                     dest,
171                 )?;
172             }
173
174             CheckedBinaryOp(bin_op, ref left, ref right) => {
175                 // Due to the extra boolean in the result, we can never reuse the `dest.layout`.
176                 let left = self.read_value(self.eval_operand(left, None)?)?;
177                 let layout = if binop_right_homogeneous(bin_op) { Some(left.layout) } else { None };
178                 let right = self.read_value(self.eval_operand(right, layout)?)?;
179                 self.binop_with_overflow(
180                     bin_op,
181                     left,
182                     right,
183                     dest,
184                 )?;
185             }
186
187             UnaryOp(un_op, ref operand) => {
188                 // The operand always has the same type as the result.
189                 let val = self.read_value(self.eval_operand(operand, Some(dest.layout))?)?;
190                 let val = self.unary_op(un_op, val.to_scalar()?, dest.layout)?;
191                 self.write_scalar(val, dest)?;
192             }
193
194             Aggregate(ref kind, ref operands) => {
195                 let (dest, active_field_index) = match **kind {
196                     mir::AggregateKind::Adt(adt_def, variant_index, _, _, active_field_index) => {
197                         self.write_discriminant_index(variant_index, dest)?;
198                         if adt_def.is_enum() {
199                             (self.place_downcast(dest, variant_index)?, active_field_index)
200                         } else {
201                             (dest, active_field_index)
202                         }
203                     }
204                     _ => (dest, None)
205                 };
206
207                 for (i, operand) in operands.iter().enumerate() {
208                     let op = self.eval_operand(operand, None)?;
209                     // Ignore zero-sized fields.
210                     if !op.layout.is_zst() {
211                         let field_index = active_field_index.unwrap_or(i);
212                         let field_dest = self.place_field(dest, field_index as u64)?;
213                         self.copy_op(op, field_dest)?;
214                     }
215                 }
216             }
217
218             Repeat(ref operand, _) => {
219                 let op = self.eval_operand(operand, None)?;
220                 let dest = self.force_allocation(dest)?;
221                 let length = dest.len(&self)?;
222
223                 if length > 0 {
224                     // write the first
225                     let first = self.mplace_field(dest, 0)?;
226                     self.copy_op(op, first.into())?;
227
228                     if length > 1 {
229                         // copy the rest
230                         let (dest, dest_align) = first.to_scalar_ptr_align();
231                         let rest = dest.ptr_offset(first.layout.size, &self)?;
232                         self.memory.copy_repeatedly(
233                             dest, dest_align, rest, dest_align, first.layout.size, length - 1, true
234                         )?;
235                     }
236                 }
237             }
238
239             Len(ref place) => {
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();
245                 self.write_scalar(
246                     Scalar::from_uint(len, size),
247                     dest,
248                 )?;
249             }
250
251             Ref(_, _, ref place) => {
252                 let src = self.eval_place(place)?;
253                 let val = self.force_allocation(src)?.to_ref();
254                 self.write_value(val, dest)?;
255             }
256
257             NullaryOp(mir::NullOp::Box, _) => {
258                 M::box_alloc(self, dest)?;
259             }
260
261             NullaryOp(mir::NullOp::SizeOf, ty) => {
262                 let ty = self.monomorphize(ty, self.substs());
263                 let layout = self.layout_of(ty)?;
264                 assert!(!layout.is_unsized(),
265                         "SizeOf nullary MIR operator called for unsized type");
266                 let size = self.pointer_size();
267                 self.write_scalar(
268                     Scalar::from_uint(layout.size.bytes(), size),
269                     dest,
270                 )?;
271             }
272
273             Cast(kind, ref operand, cast_ty) => {
274                 debug_assert_eq!(self.monomorphize(cast_ty, self.substs()), dest.layout.ty);
275                 let src = self.eval_operand(operand, None)?;
276                 self.cast(src, kind, dest)?;
277             }
278
279             Discriminant(ref place) => {
280                 let place = self.eval_place(place)?;
281                 let discr_val = self.read_discriminant(self.place_to_op(place)?)?.0;
282                 let size = dest.layout.size;
283                 self.write_scalar(Scalar::from_uint(discr_val, size), dest)?;
284             }
285         }
286
287         self.dump_place(*dest);
288
289         Ok(())
290     }
291
292     fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> EvalResult<'tcx> {
293         debug!("{:?}", terminator.kind);
294         self.tcx.span = terminator.source_info.span;
295         self.memory.tcx.span = terminator.source_info.span;
296
297         let old_stack = self.cur_frame();
298         let old_bb = self.frame().block;
299         self.eval_terminator(terminator)?;
300         if !self.stack.is_empty() {
301             // This should change *something*
302             debug_assert!(self.cur_frame() != old_stack || self.frame().block != old_bb);
303             debug!("// {:?}", self.frame().block);
304         }
305         Ok(())
306     }
307 }