]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/terminator.rs
Treat RETURN_PLACE as a normal Local
[rust.git] / src / librustc_mir / interpret / terminator.rs
1 use std::borrow::Cow;
2 use std::convert::TryFrom;
3
4 use rustc_middle::ty::layout::TyAndLayout;
5 use rustc_middle::ty::Instance;
6 use rustc_middle::{mir, ty};
7 use rustc_target::abi::{self, LayoutOf as _};
8 use rustc_target::spec::abi::Abi;
9
10 use super::{
11     FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, StackPopCleanup,
12 };
13
14 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
15     pub(super) fn eval_terminator(
16         &mut self,
17         terminator: &mir::Terminator<'tcx>,
18     ) -> InterpResult<'tcx> {
19         use rustc_middle::mir::TerminatorKind::*;
20         match terminator.kind {
21             Return => {
22                 self.pop_stack_frame(/* unwinding */ false)?
23             }
24
25             Goto { target } => self.go_to_block(target),
26
27             SwitchInt { ref discr, ref values, ref targets, .. } => {
28                 let discr = self.read_immediate(self.eval_operand(discr, None)?)?;
29                 trace!("SwitchInt({:?})", *discr);
30
31                 // Branch to the `otherwise` case by default, if no match is found.
32                 assert!(!targets.is_empty());
33                 let mut target_block = targets[targets.len() - 1];
34
35                 for (index, &const_int) in values.iter().enumerate() {
36                     // Compare using binary_op, to also support pointer values
37                     let res = self
38                         .overflowing_binary_op(
39                             mir::BinOp::Eq,
40                             discr,
41                             ImmTy::from_uint(const_int, discr.layout),
42                         )?
43                         .0;
44                     if res.to_bool()? {
45                         target_block = targets[index];
46                         break;
47                     }
48                 }
49
50                 self.go_to_block(target_block);
51             }
52
53             Call { ref func, ref args, destination, ref cleanup, .. } => {
54                 let old_stack = self.frame_idx();
55                 let old_bb = self.frame().block;
56                 let func = self.eval_operand(func, None)?;
57                 let (fn_val, abi) = match func.layout.ty.kind {
58                     ty::FnPtr(sig) => {
59                         let caller_abi = sig.abi();
60                         let fn_ptr = self.read_scalar(func)?.not_undef()?;
61                         let fn_val = self.memory.get_fn(fn_ptr)?;
62                         (fn_val, caller_abi)
63                     }
64                     ty::FnDef(def_id, substs) => {
65                         let sig = func.layout.ty.fn_sig(*self.tcx);
66                         (FnVal::Instance(self.resolve(def_id, substs)?), sig.abi())
67                     }
68                     _ => span_bug!(
69                         terminator.source_info.span,
70                         "invalid callee of type {:?}",
71                         func.layout.ty
72                     ),
73                 };
74                 let args = self.eval_operands(args)?;
75                 let ret = match destination {
76                     Some((dest, ret)) => Some((self.eval_place(dest)?, ret)),
77                     None => None,
78                 };
79                 self.eval_fn_call(fn_val, abi, &args[..], ret, *cleanup)?;
80                 // Sanity-check that `eval_fn_call` either pushed a new frame or
81                 // did a jump to another block.
82                 if self.frame_idx() == old_stack && self.frame().block == old_bb {
83                     span_bug!(terminator.source_info.span, "evaluating this call made no progress");
84                 }
85             }
86
87             Drop { location, target, unwind } => {
88                 let place = self.eval_place(location)?;
89                 let ty = place.layout.ty;
90                 trace!("TerminatorKind::drop: {:?}, type {}", location, ty);
91
92                 let instance = Instance::resolve_drop_in_place(*self.tcx, ty);
93                 self.drop_in_place(place, instance, target, unwind)?;
94             }
95
96             Assert { ref cond, expected, ref msg, target, cleanup } => {
97                 let cond_val =
98                     self.read_immediate(self.eval_operand(cond, None)?)?.to_scalar()?.to_bool()?;
99                 if expected == cond_val {
100                     self.go_to_block(target);
101                 } else {
102                     M::assert_panic(self, msg, cleanup)?;
103                 }
104             }
105
106             Abort => {
107                 M::abort(self)?;
108             }
109
110             // When we encounter Resume, we've finished unwinding
111             // cleanup for the current stack frame. We pop it in order
112             // to continue unwinding the next frame
113             Resume => {
114                 trace!("unwinding: resuming from cleanup");
115                 // By definition, a Resume terminator means
116                 // that we're unwinding
117                 self.pop_stack_frame(/* unwinding */ true)?;
118                 return Ok(());
119             }
120
121             // It is UB to ever encounter this.
122             Unreachable => throw_ub!(Unreachable),
123
124             // These should never occur for MIR we actually run.
125             DropAndReplace { .. }
126             | FalseEdges { .. }
127             | FalseUnwind { .. }
128             | Yield { .. }
129             | GeneratorDrop => span_bug!(
130                 terminator.source_info.span,
131                 "{:#?} should have been eliminated by MIR pass",
132                 terminator.kind
133             ),
134         }
135
136         Ok(())
137     }
138
139     fn check_argument_compat(
140         rust_abi: bool,
141         caller: TyAndLayout<'tcx>,
142         callee: TyAndLayout<'tcx>,
143     ) -> bool {
144         if caller.ty == callee.ty {
145             // No question
146             return true;
147         }
148         if !rust_abi {
149             // Don't risk anything
150             return false;
151         }
152         // Compare layout
153         match (&caller.abi, &callee.abi) {
154             // Different valid ranges are okay (once we enforce validity,
155             // that will take care to make it UB to leave the range, just
156             // like for transmute).
157             (abi::Abi::Scalar(ref caller), abi::Abi::Scalar(ref callee)) => {
158                 caller.value == callee.value
159             }
160             (
161                 abi::Abi::ScalarPair(ref caller1, ref caller2),
162                 abi::Abi::ScalarPair(ref callee1, ref callee2),
163             ) => caller1.value == callee1.value && caller2.value == callee2.value,
164             // Be conservative
165             _ => false,
166         }
167     }
168
169     /// Pass a single argument, checking the types for compatibility.
170     fn pass_argument(
171         &mut self,
172         rust_abi: bool,
173         caller_arg: &mut impl Iterator<Item = OpTy<'tcx, M::PointerTag>>,
174         callee_arg: PlaceTy<'tcx, M::PointerTag>,
175     ) -> InterpResult<'tcx> {
176         if rust_abi && callee_arg.layout.is_zst() {
177             // Nothing to do.
178             trace!("Skipping callee ZST");
179             return Ok(());
180         }
181         let caller_arg = caller_arg.next().ok_or_else(|| {
182             err_ub_format!("calling a function with fewer arguments than it requires")
183         })?;
184         if rust_abi {
185             assert!(!caller_arg.layout.is_zst(), "ZSTs must have been already filtered out");
186         }
187         // Now, check
188         if !Self::check_argument_compat(rust_abi, caller_arg.layout, callee_arg.layout) {
189             throw_ub_format!(
190                 "calling a function with argument of type {:?} passing data of type {:?}",
191                 callee_arg.layout.ty,
192                 caller_arg.layout.ty
193             )
194         }
195         // We allow some transmutes here
196         self.copy_op_transmute(caller_arg, callee_arg)
197     }
198
199     /// Call this function -- pushing the stack frame and initializing the arguments.
200     fn eval_fn_call(
201         &mut self,
202         fn_val: FnVal<'tcx, M::ExtraFnVal>,
203         caller_abi: Abi,
204         args: &[OpTy<'tcx, M::PointerTag>],
205         ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
206         unwind: Option<mir::BasicBlock>,
207     ) -> InterpResult<'tcx> {
208         trace!("eval_fn_call: {:#?}", fn_val);
209
210         let instance = match fn_val {
211             FnVal::Instance(instance) => instance,
212             FnVal::Other(extra) => {
213                 return M::call_extra_fn(self, extra, args, ret, unwind);
214             }
215         };
216
217         // ABI check
218         {
219             let callee_abi = {
220                 let instance_ty = instance.ty_env(*self.tcx, self.param_env);
221                 match instance_ty.kind {
222                     ty::FnDef(..) => instance_ty.fn_sig(*self.tcx).abi(),
223                     ty::Closure(..) => Abi::RustCall,
224                     ty::Generator(..) => Abi::Rust,
225                     _ => bug!("unexpected callee ty: {:?}", instance_ty),
226                 }
227             };
228             let normalize_abi = |abi| match abi {
229                 Abi::Rust | Abi::RustCall | Abi::RustIntrinsic | Abi::PlatformIntrinsic =>
230                 // These are all the same ABI, really.
231                 {
232                     Abi::Rust
233                 }
234                 abi => abi,
235             };
236             if normalize_abi(caller_abi) != normalize_abi(callee_abi) {
237                 throw_ub_format!(
238                     "calling a function with ABI {:?} using caller ABI {:?}",
239                     callee_abi,
240                     caller_abi
241                 )
242             }
243         }
244
245         match instance.def {
246             ty::InstanceDef::Intrinsic(..) => {
247                 assert!(caller_abi == Abi::RustIntrinsic || caller_abi == Abi::PlatformIntrinsic);
248                 M::call_intrinsic(self, instance, args, ret, unwind)
249             }
250             ty::InstanceDef::VtableShim(..)
251             | ty::InstanceDef::ReifyShim(..)
252             | ty::InstanceDef::ClosureOnceShim { .. }
253             | ty::InstanceDef::FnPtrShim(..)
254             | ty::InstanceDef::DropGlue(..)
255             | ty::InstanceDef::CloneShim(..)
256             | ty::InstanceDef::Item(_) => {
257                 // We need MIR for this fn
258                 let body = match M::find_mir_or_eval_fn(self, instance, args, ret, unwind)? {
259                     Some(body) => body,
260                     None => return Ok(()),
261                 };
262
263                 self.push_stack_frame(
264                     instance,
265                     body,
266                     ret.map(|p| p.0),
267                     StackPopCleanup::Goto { ret: ret.map(|p| p.1), unwind },
268                 )?;
269
270                 // If an error is raised here, pop the frame again to get an accurate backtrace.
271                 // To this end, we wrap it all in a `try` block.
272                 let res: InterpResult<'tcx> = try {
273                     trace!(
274                         "caller ABI: {:?}, args: {:#?}",
275                         caller_abi,
276                         args.iter()
277                             .map(|arg| (arg.layout.ty, format!("{:?}", **arg)))
278                             .collect::<Vec<_>>()
279                     );
280                     trace!(
281                         "spread_arg: {:?}, locals: {:#?}",
282                         body.spread_arg,
283                         body.args_iter()
284                             .map(|local| (
285                                 local,
286                                 self.layout_of_local(self.frame(), local, None).unwrap().ty
287                             ))
288                             .collect::<Vec<_>>()
289                     );
290
291                     // Figure out how to pass which arguments.
292                     // The Rust ABI is special: ZST get skipped.
293                     let rust_abi = match caller_abi {
294                         Abi::Rust | Abi::RustCall => true,
295                         _ => false,
296                     };
297                     // We have two iterators: Where the arguments come from,
298                     // and where they go to.
299
300                     // For where they come from: If the ABI is RustCall, we untuple the
301                     // last incoming argument.  These two iterators do not have the same type,
302                     // so to keep the code paths uniform we accept an allocation
303                     // (for RustCall ABI only).
304                     let caller_args: Cow<'_, [OpTy<'tcx, M::PointerTag>]> =
305                         if caller_abi == Abi::RustCall && !args.is_empty() {
306                             // Untuple
307                             let (&untuple_arg, args) = args.split_last().unwrap();
308                             trace!("eval_fn_call: Will pass last argument by untupling");
309                             Cow::from(
310                                 args.iter()
311                                     .map(|&a| Ok(a))
312                                     .chain(
313                                         (0..untuple_arg.layout.fields.count())
314                                             .map(|i| self.operand_field(untuple_arg, i)),
315                                     )
316                                     .collect::<InterpResult<'_, Vec<OpTy<'tcx, M::PointerTag>>>>(
317                                     )?,
318                             )
319                         } else {
320                             // Plain arg passing
321                             Cow::from(args)
322                         };
323                     // Skip ZSTs
324                     let mut caller_iter =
325                         caller_args.iter().filter(|op| !rust_abi || !op.layout.is_zst()).copied();
326
327                     // Now we have to spread them out across the callee's locals,
328                     // taking into account the `spread_arg`.  If we could write
329                     // this is a single iterator (that handles `spread_arg`), then
330                     // `pass_argument` would be the loop body. It takes care to
331                     // not advance `caller_iter` for ZSTs.
332                     for local in body.args_iter() {
333                         let dest = self.eval_place(mir::Place::from(local))?;
334                         if Some(local) == body.spread_arg {
335                             // Must be a tuple
336                             for i in 0..dest.layout.fields.count() {
337                                 let dest = self.place_field(dest, i)?;
338                                 self.pass_argument(rust_abi, &mut caller_iter, dest)?;
339                             }
340                         } else {
341                             // Normal argument
342                             self.pass_argument(rust_abi, &mut caller_iter, dest)?;
343                         }
344                     }
345                     // Now we should have no more caller args
346                     if caller_iter.next().is_some() {
347                         throw_ub_format!("calling a function with more arguments than it expected")
348                     }
349                     // Don't forget to check the return type!
350                     if let Some((caller_ret, _)) = ret {
351                         let callee_ret = self.eval_place(mir::Place::return_place())?;
352                         if !Self::check_argument_compat(
353                             rust_abi,
354                             caller_ret.layout,
355                             callee_ret.layout,
356                         ) {
357                             throw_ub_format!(
358                                 "calling a function with return type {:?} passing \
359                                      return place of type {:?}",
360                                 callee_ret.layout.ty,
361                                 caller_ret.layout.ty
362                             )
363                         }
364                     } else {
365                         let local = mir::RETURN_PLACE;
366                         let callee_layout = self.layout_of_local(self.frame(), local, None)?;
367                         if !callee_layout.abi.is_uninhabited() {
368                             throw_ub_format!("calling a returning function without a return place")
369                         }
370                     }
371                 };
372                 match res {
373                     Err(err) => {
374                         self.stack_mut().pop();
375                         Err(err)
376                     }
377                     Ok(()) => Ok(()),
378                 }
379             }
380             // cannot use the shim here, because that will only result in infinite recursion
381             ty::InstanceDef::Virtual(_, idx) => {
382                 let mut args = args.to_vec();
383                 // We have to implement all "object safe receivers".  Currently we
384                 // support built-in pointers (&, &mut, Box) as well as unsized-self.  We do
385                 // not yet support custom self types.
386                 // Also see librustc_codegen_llvm/abi.rs and librustc_codegen_llvm/mir/block.rs.
387                 let receiver_place = match args[0].layout.ty.builtin_deref(true) {
388                     Some(_) => {
389                         // Built-in pointer.
390                         self.deref_operand(args[0])?
391                     }
392                     None => {
393                         // Unsized self.
394                         args[0].assert_mem_place(self)
395                     }
396                 };
397                 // Find and consult vtable
398                 let vtable = receiver_place.vtable();
399                 let drop_fn = self.get_vtable_slot(vtable, u64::try_from(idx).unwrap())?;
400
401                 // `*mut receiver_place.layout.ty` is almost the layout that we
402                 // want for args[0]: We have to project to field 0 because we want
403                 // a thin pointer.
404                 assert!(receiver_place.layout.is_unsized());
405                 let receiver_ptr_ty = self.tcx.mk_mut_ptr(receiver_place.layout.ty);
406                 let this_receiver_ptr = self.layout_of(receiver_ptr_ty)?.field(self, 0)?;
407                 // Adjust receiver argument.
408                 args[0] =
409                     OpTy::from(ImmTy::from_immediate(receiver_place.ptr.into(), this_receiver_ptr));
410                 trace!("Patched self operand to {:#?}", args[0]);
411                 // recurse with concrete function
412                 self.eval_fn_call(drop_fn, caller_abi, &args, ret, unwind)
413             }
414         }
415     }
416
417     fn drop_in_place(
418         &mut self,
419         place: PlaceTy<'tcx, M::PointerTag>,
420         instance: ty::Instance<'tcx>,
421         target: mir::BasicBlock,
422         unwind: Option<mir::BasicBlock>,
423     ) -> InterpResult<'tcx> {
424         trace!("drop_in_place: {:?},\n  {:?}, {:?}", *place, place.layout.ty, instance);
425         // We take the address of the object.  This may well be unaligned, which is fine
426         // for us here.  However, unaligned accesses will probably make the actual drop
427         // implementation fail -- a problem shared by rustc.
428         let place = self.force_allocation(place)?;
429
430         let (instance, place) = match place.layout.ty.kind {
431             ty::Dynamic(..) => {
432                 // Dropping a trait object.
433                 self.unpack_dyn_trait(place)?
434             }
435             _ => (instance, place),
436         };
437
438         let arg = ImmTy::from_immediate(
439             place.to_ref(),
440             self.layout_of(self.tcx.mk_mut_ptr(place.layout.ty))?,
441         );
442
443         let ty = self.tcx.mk_unit(); // return type is ()
444         let dest = MPlaceTy::dangling(self.layout_of(ty)?, self);
445
446         self.eval_fn_call(
447             FnVal::Instance(instance),
448             Abi::Rust,
449             &[arg.into()],
450             Some((dest.into(), target)),
451             unwind,
452         )
453     }
454 }