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;
10 InterpResult, PointerArithmetic,
11 InterpCx, Machine, OpTy, ImmTy, PlaceTy, MPlaceTy, StackPopCleanup, FnVal,
14 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
15 pub(super) fn eval_terminator(
17 terminator: &mir::Terminator<'tcx>,
18 ) -> InterpResult<'tcx> {
19 use rustc::mir::TerminatorKind::*;
20 match terminator.kind {
22 self.frame().return_place.map(|r| self.dump_place(*r));
23 self.pop_stack_frame(/* unwinding */ false)?
26 Goto { target } => self.go_to_block(target),
34 let discr = self.read_immediate(self.eval_operand(discr, None)?)?;
35 trace!("SwitchInt({:?})", *discr);
37 // Branch to the `otherwise` case by default, if no match is found.
38 let mut target_block = targets[targets.len() - 1];
40 for (index, &const_int) in values.iter().enumerate() {
41 // Compare using binary_op, to also support pointer values
42 let res = self.overflowing_binary_op(mir::BinOp::Eq,
44 ImmTy::from_uint(const_int, discr.layout),
47 target_block = targets[index];
52 self.go_to_block(target_block);
62 let func = self.eval_operand(func, None)?;
63 let (fn_val, abi) = match func.layout.ty.kind {
65 let caller_abi = sig.abi();
66 let fn_ptr = self.read_scalar(func)?.not_undef()?;
67 let fn_val = self.memory.get_fn(fn_ptr)?;
70 ty::FnDef(def_id, substs) => {
71 let sig = func.layout.ty.fn_sig(*self.tcx);
72 (FnVal::Instance(self.resolve(def_id, substs)?), sig.abi())
75 bug!("invalid callee of type {:?}", func.layout.ty)
78 let args = self.eval_operands(args)?;
79 let ret = match destination {
80 Some((dest, ret)) => Some((self.eval_place(dest)?, *ret)),
85 terminator.source_info.span,
98 // FIXME(CTFE): forbid drop in const eval
99 let place = self.eval_place(location)?;
100 let ty = place.layout.ty;
101 trace!("TerminatorKind::drop: {:?}, type {}", location, ty);
103 let instance = Instance::resolve_drop_in_place(*self.tcx, ty);
107 terminator.source_info.span,
120 let cond_val = self.read_immediate(self.eval_operand(cond, None)?)?
121 .to_scalar()?.to_bool()?;
122 if expected == cond_val {
123 self.go_to_block(target);
125 // Compute error message
126 use rustc::mir::interpret::PanicInfo::*;
127 return Err(match msg {
128 BoundsCheck { ref len, ref index } => {
130 .read_immediate(self.eval_operand(len, None)?)
131 .expect("can't eval len")
133 .to_bits(self.memory.pointer_size())? as u64;
135 .read_immediate(self.eval_operand(index, None)?)
136 .expect("can't eval index")
138 .to_bits(self.memory.pointer_size())? as u64;
139 err_panic!(BoundsCheck { len, index })
141 Overflow(op) => err_panic!(Overflow(*op)),
142 OverflowNeg => err_panic!(OverflowNeg),
143 DivisionByZero => err_panic!(DivisionByZero),
144 RemainderByZero => err_panic!(RemainderByZero),
145 GeneratorResumedAfterReturn => err_panic!(GeneratorResumedAfterReturn),
146 GeneratorResumedAfterPanic => err_panic!(GeneratorResumedAfterPanic),
147 AsyncResumedAfterReturn => err_panic!(AsyncResumedAfterReturn),
148 AsyncResumedAfterPanic => err_panic!(AsyncResumedAfterPanic),
149 Panic { .. } => bug!("`Panic` variant cannot occur in MIR"),
156 // When we encounter Resume, we've finished unwinding
157 // cleanup for the current stack frame. We pop it in order
158 // to continue unwinding the next frame
160 trace!("unwinding: resuming from cleanup");
161 // By definition, a Resume terminator means
162 // that we're unwinding
163 self.pop_stack_frame(/* unwinding */ true)?;
169 DropAndReplace { .. } |
170 Abort => unimplemented!("{:#?}", terminator.kind),
171 FalseEdges { .. } => bug!("should have been eliminated by\
172 `simplify_branches` mir pass"),
173 FalseUnwind { .. } => bug!("should have been eliminated by\
174 `simplify_branches` mir pass"),
175 Unreachable => throw_ub!(Unreachable),
181 fn check_argument_compat(
183 caller: TyLayout<'tcx>,
184 callee: TyLayout<'tcx>,
186 if caller.ty == callee.ty {
191 // Don't risk anything
195 match (&caller.abi, &callee.abi) {
196 // Different valid ranges are okay (once we enforce validity,
197 // that will take care to make it UB to leave the range, just
198 // like for transmute).
199 (layout::Abi::Scalar(ref caller), layout::Abi::Scalar(ref callee)) =>
200 caller.value == callee.value,
201 (layout::Abi::ScalarPair(ref caller1, ref caller2),
202 layout::Abi::ScalarPair(ref callee1, ref callee2)) =>
203 caller1.value == callee1.value && caller2.value == callee2.value,
209 /// Pass a single argument, checking the types for compatibility.
213 caller_arg: &mut impl Iterator<Item=OpTy<'tcx, M::PointerTag>>,
214 callee_arg: PlaceTy<'tcx, M::PointerTag>,
215 ) -> InterpResult<'tcx> {
216 if rust_abi && callee_arg.layout.is_zst() {
218 trace!("Skipping callee ZST");
221 let caller_arg = caller_arg.next()
222 .ok_or_else(|| err_unsup!(FunctionArgCountMismatch)) ?;
224 debug_assert!(!caller_arg.layout.is_zst(), "ZSTs must have been already filtered out");
227 if !Self::check_argument_compat(rust_abi, caller_arg.layout, callee_arg.layout) {
228 throw_unsup!(FunctionArgMismatch(caller_arg.layout.ty, callee_arg.layout.ty))
230 // We allow some transmutes here
231 self.copy_op_transmute(caller_arg, callee_arg)
234 /// Call this function -- pushing the stack frame and initializing the arguments.
237 fn_val: FnVal<'tcx, M::ExtraFnVal>,
240 args: &[OpTy<'tcx, M::PointerTag>],
241 ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
242 unwind: Option<mir::BasicBlock>
243 ) -> InterpResult<'tcx> {
244 trace!("eval_fn_call: {:#?}", fn_val);
246 let instance = match fn_val {
247 FnVal::Instance(instance) => instance,
248 FnVal::Other(extra) => {
249 return M::call_extra_fn(self, extra, args, ret, unwind);
256 let instance_ty = instance.ty(*self.tcx);
257 match instance_ty.kind {
259 instance_ty.fn_sig(*self.tcx).abi(),
260 ty::Closure(..) => Abi::RustCall,
261 ty::Generator(..) => Abi::Rust,
262 _ => bug!("unexpected callee ty: {:?}", instance_ty),
265 let normalize_abi = |abi| match abi {
266 Abi::Rust | Abi::RustCall | Abi::RustIntrinsic | Abi::PlatformIntrinsic =>
267 // These are all the same ABI, really.
272 if normalize_abi(caller_abi) != normalize_abi(callee_abi) {
273 throw_unsup!(FunctionAbiMismatch(caller_abi, callee_abi))
278 ty::InstanceDef::Intrinsic(..) => {
279 assert!(caller_abi == Abi::RustIntrinsic || caller_abi == Abi::PlatformIntrinsic);
280 return M::call_intrinsic(self, span, instance, args, ret, unwind);
282 ty::InstanceDef::VtableShim(..) |
283 ty::InstanceDef::ReifyShim(..) |
284 ty::InstanceDef::ClosureOnceShim { .. } |
285 ty::InstanceDef::FnPtrShim(..) |
286 ty::InstanceDef::DropGlue(..) |
287 ty::InstanceDef::CloneShim(..) |
288 ty::InstanceDef::Item(_) => {
289 // We need MIR for this fn
290 let body = match M::find_fn(self, instance, args, ret, unwind)? {
292 None => return Ok(()),
295 self.push_stack_frame(
300 StackPopCleanup::Goto { ret: ret.map(|p| p.1), unwind }
303 // We want to pop this frame again in case there was an error, to put
304 // the blame in the right location. Until the 2018 edition is used in
305 // the compiler, we have to do this with an immediately invoked function.
308 "caller ABI: {:?}, args: {:#?}",
311 .map(|arg| (arg.layout.ty, format!("{:?}", **arg)))
315 "spread_arg: {:?}, locals: {:#?}",
319 (local, self.layout_of_local(self.frame(), local, None).unwrap().ty)
324 // Figure out how to pass which arguments.
325 // The Rust ABI is special: ZST get skipped.
326 let rust_abi = match caller_abi {
327 Abi::Rust | Abi::RustCall => true,
330 // We have two iterators: Where the arguments come from,
331 // and where they go to.
333 // For where they come from: If the ABI is RustCall, we untuple the
334 // last incoming argument. These two iterators do not have the same type,
335 // so to keep the code paths uniform we accept an allocation
336 // (for RustCall ABI only).
337 let caller_args : Cow<'_, [OpTy<'tcx, M::PointerTag>]> =
338 if caller_abi == Abi::RustCall && !args.is_empty() {
340 let (&untuple_arg, args) = args.split_last().unwrap();
341 trace!("eval_fn_call: Will pass last argument by untupling");
342 Cow::from(args.iter().map(|&a| Ok(a))
343 .chain((0..untuple_arg.layout.fields.count()).into_iter()
344 .map(|i| self.operand_field(untuple_arg, i as u64))
346 .collect::<InterpResult<'_, Vec<OpTy<'tcx, M::PointerTag>>>>()?)
352 let mut caller_iter = caller_args.iter()
353 .filter(|op| !rust_abi || !op.layout.is_zst())
356 // Now we have to spread them out across the callee's locals,
357 // taking into account the `spread_arg`. If we could write
358 // this is a single iterator (that handles `spread_arg`), then
359 // `pass_argument` would be the loop body. It takes care to
360 // not advance `caller_iter` for ZSTs.
361 let mut locals_iter = body.args_iter();
362 while let Some(local) = locals_iter.next() {
363 let dest = self.eval_place(
364 &mir::Place::from(local)
366 if Some(local) == body.spread_arg {
368 for i in 0..dest.layout.fields.count() {
369 let dest = self.place_field(dest, i as u64)?;
370 self.pass_argument(rust_abi, &mut caller_iter, dest)?;
374 self.pass_argument(rust_abi, &mut caller_iter, dest)?;
377 // Now we should have no more caller args
378 if caller_iter.next().is_some() {
379 trace!("Caller has passed too many args");
380 throw_unsup!(FunctionArgCountMismatch)
382 // Don't forget to check the return type!
383 if let Some((caller_ret, _)) = ret {
384 let callee_ret = self.eval_place(
385 &mir::Place::return_place()
387 if !Self::check_argument_compat(
393 FunctionRetMismatch(caller_ret.layout.ty, callee_ret.layout.ty)
397 let local = mir::RETURN_PLACE;
398 let callee_layout = self.layout_of_local(self.frame(), local, None)?;
399 if !callee_layout.abi.is_uninhabited() {
400 throw_unsup!(FunctionRetMismatch(
401 self.tcx.types.never, callee_layout.ty
415 // cannot use the shim here, because that will only result in infinite recursion
416 ty::InstanceDef::Virtual(_, idx) => {
417 let mut args = args.to_vec();
418 // We have to implement all "object safe receivers". Currently we
419 // support built-in pointers (&, &mut, Box) as well as unsized-self. We do
420 // not yet support custom self types.
421 // Also see librustc_codegen_llvm/abi.rs and librustc_codegen_llvm/mir/block.rs.
422 let receiver_place = match args[0].layout.ty.builtin_deref(true) {
425 self.deref_operand(args[0])?
429 args[0].assert_mem_place()
432 // Find and consult vtable
433 let vtable = receiver_place.vtable();
434 let drop_fn = self.get_vtable_slot(vtable, idx)?;
436 // `*mut receiver_place.layout.ty` is almost the layout that we
437 // want for args[0]: We have to project to field 0 because we want
439 assert!(receiver_place.layout.is_unsized());
440 let receiver_ptr_ty = self.tcx.mk_mut_ptr(receiver_place.layout.ty);
441 let this_receiver_ptr = self.layout_of(receiver_ptr_ty)?.field(self, 0)?;
442 // Adjust receiver argument.
443 args[0] = OpTy::from(ImmTy {
444 layout: this_receiver_ptr,
445 imm: receiver_place.ptr.into()
447 trace!("Patched self operand to {:#?}", args[0]);
448 // recurse with concrete function
449 self.eval_fn_call(drop_fn, span, caller_abi, &args, ret, unwind)
456 place: PlaceTy<'tcx, M::PointerTag>,
457 instance: ty::Instance<'tcx>,
459 target: mir::BasicBlock,
460 unwind: Option<mir::BasicBlock>
461 ) -> InterpResult<'tcx> {
462 trace!("drop_in_place: {:?},\n {:?}, {:?}", *place, place.layout.ty, instance);
463 // We take the address of the object. This may well be unaligned, which is fine
464 // for us here. However, unaligned accesses will probably make the actual drop
465 // implementation fail -- a problem shared by rustc.
466 let place = self.force_allocation(place)?;
468 let (instance, place) = match place.layout.ty.kind {
470 // Dropping a trait object.
471 self.unpack_dyn_trait(place)?
473 _ => (instance, place),
478 layout: self.layout_of(self.tcx.mk_mut_ptr(place.layout.ty))?,
481 let ty = self.tcx.mk_unit(); // return type is ()
482 let dest = MPlaceTy::dangling(self.layout_of(ty)?, self);
485 FnVal::Instance(instance),
489 Some((dest.into(), target)),