]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/step.rs
interpret: get rid of run() function
[rust.git] / compiler / rustc_const_eval / src / interpret / step.rs
1 //! This module contains the `InterpCx` methods for executing a single step of the interpreter.
2 //!
3 //! The main entry point is the `step` method.
4
5 use either::Either;
6
7 use rustc_middle::mir;
8 use rustc_middle::mir::interpret::{InterpResult, Scalar};
9 use rustc_middle::ty::layout::LayoutOf;
10
11 use super::{InterpCx, Machine};
12
13 /// Classify whether an operator is "left-homogeneous", i.e., the LHS has the
14 /// same type as the result.
15 #[inline]
16 fn binop_left_homogeneous(op: mir::BinOp) -> bool {
17     use rustc_middle::mir::BinOp::*;
18     match op {
19         Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Offset | Shl | Shr => true,
20         Eq | Ne | Lt | Le | Gt | Ge => false,
21     }
22 }
23 /// Classify whether an operator is "right-homogeneous", i.e., the RHS has the
24 /// same type as the LHS.
25 #[inline]
26 fn binop_right_homogeneous(op: mir::BinOp) -> bool {
27     use rustc_middle::mir::BinOp::*;
28     match op {
29         Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Eq | Ne | Lt | Le | Gt | Ge => true,
30         Offset | Shl | Shr => false,
31     }
32 }
33
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.
36     ///
37     /// This is used by [priroda](https://github.com/oli-obk/priroda)
38     ///
39     /// This is marked `#inline(always)` to work around adversarial codegen when `opt-level = 3`
40     #[inline(always)]
41     pub fn step(&mut self) -> InterpResult<'tcx, bool> {
42         if self.stack().is_empty() {
43             return Ok(false);
44         }
45
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)?;
51             return Ok(true);
52         };
53         let basic_block = &self.body().basic_blocks[loc.block];
54
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;
62             return Ok(true);
63         }
64
65         M::before_terminator(self)?;
66
67         let terminator = basic_block.terminator();
68         self.terminator(terminator)?;
69         Ok(true)
70     }
71
72     /// Runs the interpretation logic for the given `mir::Statement` at the current frame and
73     /// statement counter.
74     ///
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> {
77         info!("{:?}", stmt);
78
79         use rustc_middle::mir::StatementKind::*;
80
81         match &stmt.kind {
82             Assign(box (place, rvalue)) => self.eval_rvalue_into_place(rvalue, *place)?,
83
84             SetDiscriminant { place, variant_index } => {
85                 let dest = self.eval_place(**place)?;
86                 self.write_discriminant(*variant_index, &dest)?;
87             }
88
89             Deinit(place) => {
90                 let dest = self.eval_place(**place)?;
91                 self.write_uninit(&dest)?;
92             }
93
94             // Mark locals as alive
95             StorageLive(local) => {
96                 self.storage_live(*local)?;
97             }
98
99             // Mark locals as dead
100             StorageDead(local) => {
101                 self.storage_dead(*local)?;
102             }
103
104             // No dynamic semantics attached to `FakeRead`; MIR
105             // interpreter is solely intended for borrowck'ed code.
106             FakeRead(..) => {}
107
108             // Stacked Borrows.
109             Retag(kind, place) => {
110                 let dest = self.eval_place(**place)?;
111                 M::retag(self, *kind, &dest)?;
112             }
113
114             Intrinsic(box ref intrinsic) => self.emulate_nondiverging_intrinsic(intrinsic)?,
115
116             // Statements we do not track.
117             AscribeUserType(..) => {}
118
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.
123             //
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
127             // following issue:
128             //
129             // FIXME(#73156): Handle source code coverage in const eval
130             Coverage(..) => {}
131
132             // Defined to do nothing. These are added by optimization passes, to avoid changing the
133             // size of MIR constantly.
134             Nop => {}
135         }
136
137         Ok(())
138     }
139
140     /// Evaluate an assignment statement.
141     ///
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(
145         &mut self,
146         rvalue: &mir::Rvalue<'tcx>,
147         place: mir::Place<'tcx>,
148     ) -> InterpResult<'tcx> {
149         let dest = self.eval_place(place)?;
150         // FIXME: ensure some kind of non-aliasing between LHS and RHS?
151         // Also see https://github.com/rust-lang/rust/issues/68364.
152
153         use rustc_middle::mir::Rvalue::*;
154         match *rvalue {
155             ThreadLocalRef(did) => {
156                 let ptr = M::thread_local_static_base_pointer(self, did)?;
157                 self.write_pointer(ptr, &dest)?;
158             }
159
160             Use(ref operand) => {
161                 // Avoid recomputing the layout
162                 let op = self.eval_operand(operand, Some(dest.layout))?;
163                 self.copy_op(&op, &dest, /*allow_transmute*/ false)?;
164             }
165
166             CopyForDeref(ref place) => {
167                 let op = self.eval_place_to_op(*place, Some(dest.layout))?;
168                 self.copy_op(&op, &dest, /* allow_transmute*/ false)?;
169             }
170
171             BinaryOp(bin_op, box (ref left, ref right)) => {
172                 let layout = binop_left_homogeneous(bin_op).then_some(dest.layout);
173                 let left = self.read_immediate(&self.eval_operand(left, layout)?)?;
174                 let layout = binop_right_homogeneous(bin_op).then_some(left.layout);
175                 let right = self.read_immediate(&self.eval_operand(right, layout)?)?;
176                 self.binop_ignore_overflow(bin_op, &left, &right, &dest)?;
177             }
178
179             CheckedBinaryOp(bin_op, box (ref left, ref right)) => {
180                 // Due to the extra boolean in the result, we can never reuse the `dest.layout`.
181                 let left = self.read_immediate(&self.eval_operand(left, None)?)?;
182                 let layout = binop_right_homogeneous(bin_op).then_some(left.layout);
183                 let right = self.read_immediate(&self.eval_operand(right, layout)?)?;
184                 self.binop_with_overflow(
185                     bin_op, /*force_overflow_checks*/ false, &left, &right, &dest,
186                 )?;
187             }
188
189             UnaryOp(un_op, ref operand) => {
190                 // The operand always has the same type as the result.
191                 let val = self.read_immediate(&self.eval_operand(operand, Some(dest.layout))?)?;
192                 let val = self.unary_op(un_op, &val)?;
193                 assert_eq!(val.layout, dest.layout, "layout mismatch for result of {:?}", un_op);
194                 self.write_immediate(*val, &dest)?;
195             }
196
197             Aggregate(box ref kind, ref operands) => {
198                 assert!(matches!(kind, mir::AggregateKind::Array(..)));
199
200                 for (field_index, operand) in operands.iter().enumerate() {
201                     let op = self.eval_operand(operand, None)?;
202                     let field_dest = self.place_field(&dest, field_index)?;
203                     self.copy_op(&op, &field_dest, /*allow_transmute*/ false)?;
204                 }
205             }
206
207             Repeat(ref operand, _) => {
208                 let src = self.eval_operand(operand, None)?;
209                 assert!(src.layout.is_sized());
210                 let dest = self.force_allocation(&dest)?;
211                 let length = dest.len(self)?;
212
213                 if length == 0 {
214                     // Nothing to copy... but let's still make sure that `dest` as a place is valid.
215                     self.get_place_alloc_mut(&dest)?;
216                 } else {
217                     // Write the src to the first element.
218                     let first = self.mplace_field(&dest, 0)?;
219                     self.copy_op(&src, &first.into(), /*allow_transmute*/ false)?;
220
221                     // This is performance-sensitive code for big static/const arrays! So we
222                     // avoid writing each operand individually and instead just make many copies
223                     // of the first element.
224                     let elem_size = first.layout.size;
225                     let first_ptr = first.ptr;
226                     let rest_ptr = first_ptr.offset(elem_size, self)?;
227                     // For the alignment of `rest_ptr`, we crucially do *not* use `first.align` as
228                     // that place might be more aligned than its type mandates (a `u8` array could
229                     // be 4-aligned if it sits at the right spot in a struct). Instead we use
230                     // `first.layout.align`, i.e., the alignment given by the type.
231                     self.mem_copy_repeatedly(
232                         first_ptr,
233                         first.align,
234                         rest_ptr,
235                         first.layout.align.abi,
236                         elem_size,
237                         length - 1,
238                         /*nonoverlapping:*/ true,
239                     )?;
240                 }
241             }
242
243             Len(place) => {
244                 let src = self.eval_place(place)?;
245                 let op = self.place_to_op(&src)?;
246                 let len = op.len(self)?;
247                 self.write_scalar(Scalar::from_machine_usize(len, self), &dest)?;
248             }
249
250             AddressOf(_, place) | Ref(_, _, place) => {
251                 let src = self.eval_place(place)?;
252                 let place = self.force_allocation(&src)?;
253                 self.write_immediate(place.to_ref(self), &dest)?;
254             }
255
256             NullaryOp(null_op, ty) => {
257                 let ty = self.subst_from_current_frame_and_normalize_erasing_regions(ty)?;
258                 let layout = self.layout_of(ty)?;
259                 if layout.is_unsized() {
260                     // FIXME: This should be a span_bug (#80742)
261                     self.tcx.sess.delay_span_bug(
262                         self.frame().current_span(),
263                         &format!("Nullary MIR operator called for unsized type {}", ty),
264                     );
265                     throw_inval!(SizeOfUnsizedType(ty));
266                 }
267                 let val = match null_op {
268                     mir::NullOp::SizeOf => layout.size.bytes(),
269                     mir::NullOp::AlignOf => layout.align.abi.bytes(),
270                 };
271                 self.write_scalar(Scalar::from_machine_usize(val, self), &dest)?;
272             }
273
274             ShallowInitBox(ref operand, _) => {
275                 let src = self.eval_operand(operand, None)?;
276                 let v = self.read_immediate(&src)?;
277                 self.write_immediate(*v, &dest)?;
278             }
279
280             Cast(cast_kind, ref operand, cast_ty) => {
281                 let src = self.eval_operand(operand, None)?;
282                 let cast_ty =
283                     self.subst_from_current_frame_and_normalize_erasing_regions(cast_ty)?;
284                 self.cast(&src, cast_kind, cast_ty, &dest)?;
285             }
286
287             Discriminant(place) => {
288                 let op = self.eval_place_to_op(place, None)?;
289                 let discr_val = self.read_discriminant(&op)?.0;
290                 self.write_scalar(discr_val, &dest)?;
291             }
292         }
293
294         trace!("{:?}", self.dump_place(*dest));
295
296         Ok(())
297     }
298
299     /// Evaluate the given terminator. Will also adjust the stack frame and statement position accordingly.
300     fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> InterpResult<'tcx> {
301         info!("{:?}", terminator.kind);
302
303         self.eval_terminator(terminator)?;
304         if !self.stack().is_empty() {
305             if let Either::Left(loc) = self.frame().loc {
306                 info!("// executing {:?}", loc.block);
307             }
308         }
309         Ok(())
310     }
311 }