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