]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/step.rs
Introduce write_aggregate.
[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::{ImmTy, 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_place_contents(self, *kind, &dest)?;
112             }
113
114             Intrinsic(box 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             ConstEvalCounter => {
133                 M::increment_const_eval_counter(self)?;
134             }
135
136             // Defined to do nothing. These are added by optimization passes, to avoid changing the
137             // size of MIR constantly.
138             Nop => {}
139         }
140
141         Ok(())
142     }
143
144     /// Evaluate an assignment statement.
145     ///
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(
149         &mut self,
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.
156
157         use rustc_middle::mir::Rvalue::*;
158         match *rvalue {
159             ThreadLocalRef(did) => {
160                 let ptr = M::thread_local_static_base_pointer(self, did)?;
161                 self.write_pointer(ptr, &dest)?;
162             }
163
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)?;
168             }
169
170             CopyForDeref(place) => {
171                 let op = self.eval_place_to_op(place, Some(dest.layout))?;
172                 self.copy_op(&op, &dest, /* allow_transmute*/ false)?;
173             }
174
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)?;
181             }
182
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,
190                 )?;
191             }
192
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)?;
199             }
200
201             Aggregate(box ref kind, ref operands) => {
202                 self.write_aggregate(kind, operands, &dest)?;
203             }
204
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)?;
210
211                 if length == 0 {
212                     // Nothing to copy... but let's still make sure that `dest` as a place is valid.
213                     self.get_place_alloc_mut(&dest)?;
214                 } else {
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)?;
218
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(
230                         first_ptr,
231                         first.align,
232                         rest_ptr,
233                         first.layout.align.abi,
234                         elem_size,
235                         length - 1,
236                         /*nonoverlapping:*/ true,
237                     )?;
238                 }
239             }
240
241             Len(place) => {
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)?;
246             }
247
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(
254                     self,
255                     if borrow_kind.allows_two_phase_borrow() {
256                         mir::RetagKind::TwoPhase
257                     } else {
258                         mir::RetagKind::Default
259                     },
260                     &val,
261                 )?;
262                 self.write_immediate(*val, &dest)?;
263             }
264
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;
269                     ty.is_unsafe_ptr()
270                 } else {
271                     // Not a deref, and thus not raw.
272                     false
273                 };
274
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);
278                 if !place_base_raw {
279                     // If this was not already raw, it needs retagging.
280                     val = M::retag_ptr_value(self, mir::RetagKind::Raw, &val)?;
281                 }
282                 self.write_immediate(*val, &dest)?;
283             }
284
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),
293                     );
294                     throw_inval!(SizeOfUnsizedType(ty));
295                 }
296                 let val = match null_op {
297                     mir::NullOp::SizeOf => layout.size.bytes(),
298                     mir::NullOp::AlignOf => layout.align.abi.bytes(),
299                 };
300                 self.write_scalar(Scalar::from_machine_usize(val, self), &dest)?;
301             }
302
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)?;
307             }
308
309             Cast(cast_kind, ref operand, cast_ty) => {
310                 let src = self.eval_operand(operand, None)?;
311                 let cast_ty =
312                     self.subst_from_current_frame_and_normalize_erasing_regions(cast_ty)?;
313                 self.cast(&src, cast_kind, cast_ty, &dest)?;
314             }
315
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)?;
320             }
321         }
322
323         trace!("{:?}", self.dump_place(*dest));
324
325         Ok(())
326     }
327
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);
331
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);
336             }
337         }
338         Ok(())
339     }
340 }