2 use std::convert::TryFrom;
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;
11 FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, StackPopCleanup,
14 impl<'mir, 'tcx: 'mir, 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_middle::mir::TerminatorKind::*;
20 match terminator.kind {
22 self.pop_stack_frame(/* unwinding */ false)?
25 Goto { target } => self.go_to_block(target),
27 SwitchInt { ref discr, ref values, ref targets, .. } => {
28 let discr = self.read_immediate(self.eval_operand(discr, None)?)?;
29 trace!("SwitchInt({:?})", *discr);
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];
35 for (index, &const_int) in values.iter().enumerate() {
36 // Compare using binary_op, to also support pointer values
38 .overflowing_binary_op(
41 ImmTy::from_uint(const_int, discr.layout),
45 target_block = targets[index];
50 self.go_to_block(target_block);
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 {
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)?;
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())
69 terminator.source_info.span,
70 "invalid callee of type {:?}",
74 let args = self.eval_operands(args)?;
75 let ret = match destination {
76 Some((dest, ret)) => Some((self.eval_place(dest)?, ret)),
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");
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);
92 let instance = Instance::resolve_drop_in_place(*self.tcx, ty);
93 self.drop_in_place(place, instance, target, unwind)?;
96 Assert { ref cond, expected, ref msg, target, cleanup } => {
98 self.read_immediate(self.eval_operand(cond, None)?)?.to_scalar()?.to_bool()?;
99 if expected == cond_val {
100 self.go_to_block(target);
102 M::assert_panic(self, msg, cleanup)?;
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
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)?;
121 // It is UB to ever encounter this.
122 Unreachable => throw_ub!(Unreachable),
124 // These should never occur for MIR we actually run.
125 DropAndReplace { .. }
129 | GeneratorDrop => span_bug!(
130 terminator.source_info.span,
131 "{:#?} should have been eliminated by MIR pass",
139 fn check_argument_compat(
141 caller: TyAndLayout<'tcx>,
142 callee: TyAndLayout<'tcx>,
144 if caller.ty == callee.ty {
149 // Don't risk anything
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
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,
169 /// Pass a single argument, checking the types for compatibility.
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() {
178 trace!("Skipping callee ZST");
181 let caller_arg = caller_arg.next().ok_or_else(|| {
182 err_ub_format!("calling a function with fewer arguments than it requires")
185 assert!(!caller_arg.layout.is_zst(), "ZSTs must have been already filtered out");
188 if !Self::check_argument_compat(rust_abi, caller_arg.layout, callee_arg.layout) {
190 "calling a function with argument of type {:?} passing data of type {:?}",
191 callee_arg.layout.ty,
195 // We allow some transmutes here
196 self.copy_op_transmute(caller_arg, callee_arg)
199 /// Call this function -- pushing the stack frame and initializing the arguments.
202 fn_val: FnVal<'tcx, M::ExtraFnVal>,
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);
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);
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),
228 let normalize_abi = |abi| match abi {
229 Abi::Rust | Abi::RustCall | Abi::RustIntrinsic | Abi::PlatformIntrinsic =>
230 // These are all the same ABI, really.
236 if normalize_abi(caller_abi) != normalize_abi(callee_abi) {
238 "calling a function with ABI {:?} using caller ABI {:?}",
246 ty::InstanceDef::Intrinsic(..) => {
247 assert!(caller_abi == Abi::RustIntrinsic || caller_abi == Abi::PlatformIntrinsic);
248 M::call_intrinsic(self, instance, args, ret, unwind)
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)? {
260 None => return Ok(()),
263 self.push_stack_frame(
267 StackPopCleanup::Goto { ret: ret.map(|p| p.1), unwind },
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 {
274 "caller ABI: {:?}, args: {:#?}",
277 .map(|arg| (arg.layout.ty, format!("{:?}", **arg)))
281 "spread_arg: {:?}, locals: {:#?}",
286 self.layout_of_local(self.frame(), local, None).unwrap().ty
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,
297 // We have two iterators: Where the arguments come from,
298 // and where they go to.
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() {
307 let (&untuple_arg, args) = args.split_last().unwrap();
308 trace!("eval_fn_call: Will pass last argument by untupling");
313 (0..untuple_arg.layout.fields.count())
314 .map(|i| self.operand_field(untuple_arg, i)),
316 .collect::<InterpResult<'_, Vec<OpTy<'tcx, M::PointerTag>>>>(
324 let mut caller_iter =
325 caller_args.iter().filter(|op| !rust_abi || !op.layout.is_zst()).copied();
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 {
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)?;
342 self.pass_argument(rust_abi, &mut caller_iter, dest)?;
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")
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(
358 "calling a function with return type {:?} passing \
359 return place of type {:?}",
360 callee_ret.layout.ty,
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")
374 self.stack_mut().pop();
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) {
390 self.deref_operand(args[0])?
394 args[0].assert_mem_place(self)
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())?;
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
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.
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)
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)?;
430 let (instance, place) = match place.layout.ty.kind {
432 // Dropping a trait object.
433 self.unpack_dyn_trait(place)?
435 _ => (instance, place),
438 let arg = ImmTy::from_immediate(
440 self.layout_of(self.tcx.mk_mut_ptr(place.layout.ty))?,
443 let ty = self.tcx.mk_unit(); // return type is ()
444 let dest = MPlaceTy::dangling(self.layout_of(ty)?, self);
447 FnVal::Instance(instance),
450 Some((dest.into(), target)),