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