3 use rustc::ty::layout::{self, LayoutOf, TyLayout};
4 use rustc::ty::Instance;
6 use rustc_span::source_map::Span;
7 use rustc_target::spec::abi::Abi;
10 FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, StackPopCleanup,
13 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
14 pub(super) fn eval_terminator(
16 terminator: &mir::Terminator<'tcx>,
17 ) -> InterpResult<'tcx> {
18 use rustc::mir::TerminatorKind::*;
19 match terminator.kind {
21 self.frame().return_place.map(|r| self.dump_place(*r));
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 let mut target_block = targets[targets.len() - 1];
34 for (index, &const_int) in values.iter().enumerate() {
35 // Compare using binary_op, to also support pointer values
37 .overflowing_binary_op(
40 ImmTy::from_uint(const_int, discr.layout),
44 target_block = targets[index];
49 self.go_to_block(target_block);
52 Call { ref func, ref args, ref destination, ref cleanup, .. } => {
53 let func = self.eval_operand(func, None)?;
54 let (fn_val, abi) = match func.layout.ty.kind {
56 let caller_abi = sig.abi();
57 let fn_ptr = self.read_scalar(func)?.not_undef()?;
58 let fn_val = self.memory.get_fn(fn_ptr)?;
61 ty::FnDef(def_id, substs) => {
62 let sig = func.layout.ty.fn_sig(*self.tcx);
63 (FnVal::Instance(self.resolve(def_id, substs)?), sig.abi())
65 _ => bug!("invalid callee of type {:?}", func.layout.ty),
67 let args = self.eval_operands(args)?;
68 let ret = match destination {
69 Some((dest, ret)) => Some((self.eval_place(dest)?, *ret)),
74 terminator.source_info.span,
82 Drop { ref location, target, unwind } => {
83 // FIXME(CTFE): forbid drop in const eval
84 let place = self.eval_place(location)?;
85 let ty = place.layout.ty;
86 trace!("TerminatorKind::drop: {:?}, type {}", location, ty);
88 let instance = Instance::resolve_drop_in_place(*self.tcx, ty);
89 self.drop_in_place(place, instance, terminator.source_info.span, target, unwind)?;
92 Assert { ref cond, expected, ref msg, target, cleanup } => {
94 self.read_immediate(self.eval_operand(cond, None)?)?.to_scalar()?.to_bool()?;
95 if expected == cond_val {
96 self.go_to_block(target);
98 M::assert_panic(self, msg, cleanup)?;
106 // When we encounter Resume, we've finished unwinding
107 // cleanup for the current stack frame. We pop it in order
108 // to continue unwinding the next frame
110 trace!("unwinding: resuming from cleanup");
111 // By definition, a Resume terminator means
112 // that we're unwinding
113 self.pop_stack_frame(/* unwinding */ true)?;
117 // It is UB to ever encounter this.
118 Unreachable => throw_ub!(Unreachable),
120 // These should never occur for MIR we actually run.
121 DropAndReplace { .. }
126 bug!("{:#?} should have been eliminated by MIR pass", terminator.kind)
133 fn check_argument_compat(
135 caller: TyLayout<'tcx>,
136 callee: TyLayout<'tcx>,
138 if caller.ty == callee.ty {
143 // Don't risk anything
147 match (&caller.abi, &callee.abi) {
148 // Different valid ranges are okay (once we enforce validity,
149 // that will take care to make it UB to leave the range, just
150 // like for transmute).
151 (layout::Abi::Scalar(ref caller), layout::Abi::Scalar(ref callee)) => {
152 caller.value == callee.value
155 layout::Abi::ScalarPair(ref caller1, ref caller2),
156 layout::Abi::ScalarPair(ref callee1, ref callee2),
157 ) => caller1.value == callee1.value && caller2.value == callee2.value,
163 /// Pass a single argument, checking the types for compatibility.
167 caller_arg: &mut impl Iterator<Item = OpTy<'tcx, M::PointerTag>>,
168 callee_arg: PlaceTy<'tcx, M::PointerTag>,
169 ) -> InterpResult<'tcx> {
170 if rust_abi && callee_arg.layout.is_zst() {
172 trace!("Skipping callee ZST");
175 let caller_arg = caller_arg.next().ok_or_else(|| {
176 err_ub_format!("calling a function with fewer arguments than it requires")
179 assert!(!caller_arg.layout.is_zst(), "ZSTs must have been already filtered out");
182 if !Self::check_argument_compat(rust_abi, caller_arg.layout, callee_arg.layout) {
184 "calling a function with argument of type {:?} passing data of type {:?}",
185 callee_arg.layout.ty,
189 // We allow some transmutes here
190 self.copy_op_transmute(caller_arg, callee_arg)
193 /// Call this function -- pushing the stack frame and initializing the arguments.
196 fn_val: FnVal<'tcx, M::ExtraFnVal>,
199 args: &[OpTy<'tcx, M::PointerTag>],
200 ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
201 unwind: Option<mir::BasicBlock>,
202 ) -> InterpResult<'tcx> {
203 trace!("eval_fn_call: {:#?}", fn_val);
205 let instance = match fn_val {
206 FnVal::Instance(instance) => instance,
207 FnVal::Other(extra) => {
208 return M::call_extra_fn(self, extra, args, ret, unwind);
215 let instance_ty = instance.ty_env(*self.tcx, self.param_env);
216 match instance_ty.kind {
217 ty::FnDef(..) => instance_ty.fn_sig(*self.tcx).abi(),
218 ty::Closure(..) => Abi::RustCall,
219 ty::Generator(..) => Abi::Rust,
220 _ => bug!("unexpected callee ty: {:?}", instance_ty),
223 let normalize_abi = |abi| match abi {
224 Abi::Rust | Abi::RustCall | Abi::RustIntrinsic | Abi::PlatformIntrinsic =>
225 // These are all the same ABI, really.
231 if normalize_abi(caller_abi) != normalize_abi(callee_abi) {
233 "calling a function with ABI {:?} using caller ABI {:?}",
241 ty::InstanceDef::Intrinsic(..) => {
242 assert!(caller_abi == Abi::RustIntrinsic || caller_abi == Abi::PlatformIntrinsic);
243 return M::call_intrinsic(self, span, instance, args, ret, unwind);
245 ty::InstanceDef::VtableShim(..)
246 | ty::InstanceDef::ReifyShim(..)
247 | ty::InstanceDef::ClosureOnceShim { .. }
248 | ty::InstanceDef::FnPtrShim(..)
249 | ty::InstanceDef::DropGlue(..)
250 | ty::InstanceDef::CloneShim(..)
251 | ty::InstanceDef::Item(_) => {
252 // We need MIR for this fn
253 let body = match M::find_mir_or_eval_fn(self, span, instance, args, ret, unwind)? {
255 None => return Ok(()),
258 self.push_stack_frame(
263 StackPopCleanup::Goto { ret: ret.map(|p| p.1), unwind },
266 // If an error is raised here, pop the frame again to get an accurate backtrace.
267 // To this end, we wrap it all in a `try` block.
268 let res: InterpResult<'tcx> = try {
270 "caller ABI: {:?}, args: {:#?}",
273 .map(|arg| (arg.layout.ty, format!("{:?}", **arg)))
277 "spread_arg: {:?}, locals: {:#?}",
282 self.layout_of_local(self.frame(), local, None).unwrap().ty
287 // Figure out how to pass which arguments.
288 // The Rust ABI is special: ZST get skipped.
289 let rust_abi = match caller_abi {
290 Abi::Rust | Abi::RustCall => true,
293 // We have two iterators: Where the arguments come from,
294 // and where they go to.
296 // For where they come from: If the ABI is RustCall, we untuple the
297 // last incoming argument. These two iterators do not have the same type,
298 // so to keep the code paths uniform we accept an allocation
299 // (for RustCall ABI only).
300 let caller_args: Cow<'_, [OpTy<'tcx, M::PointerTag>]> =
301 if caller_abi == Abi::RustCall && !args.is_empty() {
303 let (&untuple_arg, args) = args.split_last().unwrap();
304 trace!("eval_fn_call: Will pass last argument by untupling");
309 (0..untuple_arg.layout.fields.count())
310 .map(|i| self.operand_field(untuple_arg, i as u64)),
312 .collect::<InterpResult<'_, Vec<OpTy<'tcx, M::PointerTag>>>>(
320 let mut caller_iter =
321 caller_args.iter().filter(|op| !rust_abi || !op.layout.is_zst()).copied();
323 // Now we have to spread them out across the callee's locals,
324 // taking into account the `spread_arg`. If we could write
325 // this is a single iterator (that handles `spread_arg`), then
326 // `pass_argument` would be the loop body. It takes care to
327 // not advance `caller_iter` for ZSTs.
328 for local in body.args_iter() {
329 let dest = self.eval_place(&mir::Place::from(local))?;
330 if Some(local) == body.spread_arg {
332 for i in 0..dest.layout.fields.count() {
333 let dest = self.place_field(dest, i as u64)?;
334 self.pass_argument(rust_abi, &mut caller_iter, dest)?;
338 self.pass_argument(rust_abi, &mut caller_iter, dest)?;
341 // Now we should have no more caller args
342 if caller_iter.next().is_some() {
343 throw_ub_format!("calling a function with more arguments than it expected")
345 // Don't forget to check the return type!
346 if let Some((caller_ret, _)) = ret {
347 let callee_ret = self.eval_place(&mir::Place::return_place())?;
348 if !Self::check_argument_compat(
354 "calling a function with return type {:?} passing \
355 return place of type {:?}",
356 callee_ret.layout.ty,
361 let local = mir::RETURN_PLACE;
362 let callee_layout = self.layout_of_local(self.frame(), local, None)?;
363 if !callee_layout.abi.is_uninhabited() {
364 throw_ub_format!("calling a returning function without a return place")
376 // cannot use the shim here, because that will only result in infinite recursion
377 ty::InstanceDef::Virtual(_, idx) => {
378 let mut args = args.to_vec();
379 // We have to implement all "object safe receivers". Currently we
380 // support built-in pointers (&, &mut, Box) as well as unsized-self. We do
381 // not yet support custom self types.
382 // Also see librustc_codegen_llvm/abi.rs and librustc_codegen_llvm/mir/block.rs.
383 let receiver_place = match args[0].layout.ty.builtin_deref(true) {
386 self.deref_operand(args[0])?
390 args[0].assert_mem_place(self)
393 // Find and consult vtable
394 let vtable = receiver_place.vtable();
395 let drop_fn = self.get_vtable_slot(vtable, idx)?;
397 // `*mut receiver_place.layout.ty` is almost the layout that we
398 // want for args[0]: We have to project to field 0 because we want
400 assert!(receiver_place.layout.is_unsized());
401 let receiver_ptr_ty = self.tcx.mk_mut_ptr(receiver_place.layout.ty);
402 let this_receiver_ptr = self.layout_of(receiver_ptr_ty)?.field(self, 0)?;
403 // Adjust receiver argument.
405 OpTy::from(ImmTy { layout: this_receiver_ptr, imm: receiver_place.ptr.into() });
406 trace!("Patched self operand to {:#?}", args[0]);
407 // recurse with concrete function
408 self.eval_fn_call(drop_fn, span, caller_abi, &args, ret, unwind)
415 place: PlaceTy<'tcx, M::PointerTag>,
416 instance: ty::Instance<'tcx>,
418 target: mir::BasicBlock,
419 unwind: Option<mir::BasicBlock>,
420 ) -> InterpResult<'tcx> {
421 trace!("drop_in_place: {:?},\n {:?}, {:?}", *place, place.layout.ty, instance);
422 // We take the address of the object. This may well be unaligned, which is fine
423 // for us here. However, unaligned accesses will probably make the actual drop
424 // implementation fail -- a problem shared by rustc.
425 let place = self.force_allocation(place)?;
427 let (instance, place) = match place.layout.ty.kind {
429 // Dropping a trait object.
430 self.unpack_dyn_trait(place)?
432 _ => (instance, place),
437 layout: self.layout_of(self.tcx.mk_mut_ptr(place.layout.ty))?,
440 let ty = self.tcx.mk_unit(); // return type is ()
441 let dest = MPlaceTy::dangling(self.layout_of(ty)?, self);
444 FnVal::Instance(instance),
448 Some((dest.into(), target)),