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, switch_ty }
=> {
28 let discr
= self.read_immediate(self.eval_operand(discr
, None
)?
)?
;
29 trace
!("SwitchInt({:?})", *discr
);
30 assert_eq
!(discr
.layout
.ty
, switch_ty
);
32 // Branch to the `otherwise` case by default, if no match is found.
33 assert
!(!targets
.is_empty());
34 let mut target_block
= targets
[targets
.len() - 1];
36 for (index
, &const_int
) in values
.iter().enumerate() {
37 // Compare using binary_op, to also support pointer values
39 .overflowing_binary_op(
42 ImmTy
::from_uint(const_int
, discr
.layout
),
46 target_block
= targets
[index
];
51 self.go_to_block(target_block
);
54 Call { ref func, ref args, destination, ref cleanup, from_hir_call: _, fn_span: _ }
=> {
55 let old_stack
= self.frame_idx();
56 let old_loc
= self.frame().loc
;
57 let func
= self.eval_operand(func
, None
)?
;
58 let (fn_val
, abi
) = match func
.layout
.ty
.kind
{
60 let caller_abi
= sig
.abi();
61 let fn_ptr
= self.read_scalar(func
)?
.not_undef()?
;
62 let fn_val
= self.memory
.get_fn(fn_ptr
)?
;
65 ty
::FnDef(def_id
, substs
) => {
66 let sig
= func
.layout
.ty
.fn_sig(*self.tcx
);
67 (FnVal
::Instance(self.resolve(def_id
, substs
)?
), sig
.abi())
70 terminator
.source_info
.span
,
71 "invalid callee of type {:?}",
75 let args
= self.eval_operands(args
)?
;
76 let ret
= match destination
{
77 Some((dest
, ret
)) => Some((self.eval_place(dest
)?
, ret
)),
80 self.eval_fn_call(fn_val
, abi
, &args
[..], ret
, *cleanup
)?
;
81 // Sanity-check that `eval_fn_call` either pushed a new frame or
82 // did a jump to another block.
83 if self.frame_idx() == old_stack
&& self.frame().loc
== old_loc
{
84 span_bug
!(terminator
.source_info
.span
, "evaluating this call made no progress");
88 Drop { place, target, unwind }
=> {
89 let place
= self.eval_place(place
)?
;
90 let ty
= place
.layout
.ty
;
91 trace
!("TerminatorKind::drop: {:?}, type {}", place
, ty
);
93 let instance
= Instance
::resolve_drop_in_place(*self.tcx
, ty
);
94 self.drop_in_place(place
, instance
, target
, unwind
)?
;
97 Assert { ref cond, expected, ref msg, target, cleanup }
=> {
99 self.read_immediate(self.eval_operand(cond
, None
)?
)?
.to_scalar()?
.to_bool()?
;
100 if expected
== cond_val
{
101 self.go_to_block(target
);
103 M
::assert_panic(self, msg
, cleanup
)?
;
111 // When we encounter Resume, we've finished unwinding
112 // cleanup for the current stack frame. We pop it in order
113 // to continue unwinding the next frame
115 trace
!("unwinding: resuming from cleanup");
116 // By definition, a Resume terminator means
117 // that we're unwinding
118 self.pop_stack_frame(/* unwinding */ true)?
;
122 // It is UB to ever encounter this.
123 Unreachable
=> throw_ub
!(Unreachable
),
125 // These should never occur for MIR we actually run.
126 DropAndReplace { .. }
130 | GeneratorDrop
=> span_bug
!(
131 terminator
.source_info
.span
,
132 "{:#?} should have been eliminated by MIR pass",
136 // Inline assembly can't be interpreted.
137 InlineAsm { .. }
=> throw_unsup_format
!("inline assembly is not supported"),
143 fn check_argument_compat(
145 caller
: TyAndLayout
<'tcx
>,
146 callee
: TyAndLayout
<'tcx
>,
148 if caller
.ty
== callee
.ty
{
153 // Don't risk anything
157 match (&caller
.abi
, &callee
.abi
) {
158 // Different valid ranges are okay (once we enforce validity,
159 // that will take care to make it UB to leave the range, just
160 // like for transmute).
161 (abi
::Abi
::Scalar(ref caller
), abi
::Abi
::Scalar(ref callee
)) => {
162 caller
.value
== callee
.value
165 abi
::Abi
::ScalarPair(ref caller1
, ref caller2
),
166 abi
::Abi
::ScalarPair(ref callee1
, ref callee2
),
167 ) => caller1
.value
== callee1
.value
&& caller2
.value
== callee2
.value
,
173 /// Pass a single argument, checking the types for compatibility.
177 caller_arg
: &mut impl Iterator
<Item
= OpTy
<'tcx
, M
::PointerTag
>>,
178 callee_arg
: PlaceTy
<'tcx
, M
::PointerTag
>,
179 ) -> InterpResult
<'tcx
> {
180 if rust_abi
&& callee_arg
.layout
.is_zst() {
182 trace
!("Skipping callee ZST");
185 let caller_arg
= caller_arg
.next().ok_or_else(|| {
186 err_ub_format
!("calling a function with fewer arguments than it requires")
189 assert
!(!caller_arg
.layout
.is_zst(), "ZSTs must have been already filtered out");
192 if !Self::check_argument_compat(rust_abi
, caller_arg
.layout
, callee_arg
.layout
) {
194 "calling a function with argument of type {:?} passing data of type {:?}",
195 callee_arg
.layout
.ty
,
199 // We allow some transmutes here
200 self.copy_op_transmute(caller_arg
, callee_arg
)
203 /// Call this function -- pushing the stack frame and initializing the arguments.
206 fn_val
: FnVal
<'tcx
, M
::ExtraFnVal
>,
208 args
: &[OpTy
<'tcx
, M
::PointerTag
>],
209 ret
: Option
<(PlaceTy
<'tcx
, M
::PointerTag
>, mir
::BasicBlock
)>,
210 unwind
: Option
<mir
::BasicBlock
>,
211 ) -> InterpResult
<'tcx
> {
212 trace
!("eval_fn_call: {:#?}", fn_val
);
214 let instance
= match fn_val
{
215 FnVal
::Instance(instance
) => instance
,
216 FnVal
::Other(extra
) => {
217 return M
::call_extra_fn(self, extra
, args
, ret
, unwind
);
224 let instance_ty
= instance
.ty_env(*self.tcx
, self.param_env
);
225 match instance_ty
.kind
{
226 ty
::FnDef(..) => instance_ty
.fn_sig(*self.tcx
).abi(),
227 ty
::Closure(..) => Abi
::RustCall
,
228 ty
::Generator(..) => Abi
::Rust
,
229 _
=> span_bug
!(self.cur_span(), "unexpected callee ty: {:?}", instance_ty
),
232 let normalize_abi
= |abi
| match abi
{
233 Abi
::Rust
| Abi
::RustCall
| Abi
::RustIntrinsic
| Abi
::PlatformIntrinsic
=>
234 // These are all the same ABI, really.
240 if normalize_abi(caller_abi
) != normalize_abi(callee_abi
) {
242 "calling a function with ABI {:?} using caller ABI {:?}",
250 ty
::InstanceDef
::Intrinsic(..) => {
251 assert
!(caller_abi
== Abi
::RustIntrinsic
|| caller_abi
== Abi
::PlatformIntrinsic
);
252 M
::call_intrinsic(self, instance
, args
, ret
, unwind
)
254 ty
::InstanceDef
::VtableShim(..)
255 | ty
::InstanceDef
::ReifyShim(..)
256 | ty
::InstanceDef
::ClosureOnceShim { .. }
257 | ty
::InstanceDef
::FnPtrShim(..)
258 | ty
::InstanceDef
::DropGlue(..)
259 | ty
::InstanceDef
::CloneShim(..)
260 | ty
::InstanceDef
::Item(_
) => {
261 // We need MIR for this fn
262 let body
= match M
::find_mir_or_eval_fn(self, instance
, args
, ret
, unwind
)?
{
264 None
=> return Ok(()),
267 self.push_stack_frame(
271 StackPopCleanup
::Goto { ret: ret.map(|p| p.1), unwind }
,
274 // If an error is raised here, pop the frame again to get an accurate backtrace.
275 // To this end, we wrap it all in a `try` block.
276 let res
: InterpResult
<'tcx
> = try
{
278 "caller ABI: {:?}, args: {:#?}",
281 .map(|arg
| (arg
.layout
.ty
, format
!("{:?}", **arg
)))
285 "spread_arg: {:?}, locals: {:#?}",
290 self.layout_of_local(self.frame(), local
, None
).unwrap().ty
295 // Figure out how to pass which arguments.
296 // The Rust ABI is special: ZST get skipped.
297 let rust_abi
= match caller_abi
{
298 Abi
::Rust
| Abi
::RustCall
=> true,
301 // We have two iterators: Where the arguments come from,
302 // and where they go to.
304 // For where they come from: If the ABI is RustCall, we untuple the
305 // last incoming argument. These two iterators do not have the same type,
306 // so to keep the code paths uniform we accept an allocation
307 // (for RustCall ABI only).
308 let caller_args
: Cow
<'_
, [OpTy
<'tcx
, M
::PointerTag
>]> =
309 if caller_abi
== Abi
::RustCall
&& !args
.is_empty() {
311 let (&untuple_arg
, args
) = args
.split_last().unwrap();
312 trace
!("eval_fn_call: Will pass last argument by untupling");
317 (0..untuple_arg
.layout
.fields
.count())
318 .map(|i
| self.operand_field(untuple_arg
, i
)),
320 .collect
::<InterpResult
<'_
, Vec
<OpTy
<'tcx
, M
::PointerTag
>>>>(
328 let mut caller_iter
=
329 caller_args
.iter().filter(|op
| !rust_abi
|| !op
.layout
.is_zst()).copied();
331 // Now we have to spread them out across the callee's locals,
332 // taking into account the `spread_arg`. If we could write
333 // this is a single iterator (that handles `spread_arg`), then
334 // `pass_argument` would be the loop body. It takes care to
335 // not advance `caller_iter` for ZSTs.
336 for local
in body
.args_iter() {
337 let dest
= self.eval_place(mir
::Place
::from(local
))?
;
338 if Some(local
) == body
.spread_arg
{
340 for i
in 0..dest
.layout
.fields
.count() {
341 let dest
= self.place_field(dest
, i
)?
;
342 self.pass_argument(rust_abi
, &mut caller_iter
, dest
)?
;
346 self.pass_argument(rust_abi
, &mut caller_iter
, dest
)?
;
349 // Now we should have no more caller args
350 if caller_iter
.next().is_some() {
351 throw_ub_format
!("calling a function with more arguments than it expected")
353 // Don't forget to check the return type!
354 if let Some((caller_ret
, _
)) = ret
{
355 let callee_ret
= self.eval_place(mir
::Place
::return_place())?
;
356 if !Self::check_argument_compat(
362 "calling a function with return type {:?} passing \
363 return place of type {:?}",
364 callee_ret
.layout
.ty
,
369 let local
= mir
::RETURN_PLACE
;
370 let callee_layout
= self.layout_of_local(self.frame(), local
, None
)?
;
371 if !callee_layout
.abi
.is_uninhabited() {
372 throw_ub_format
!("calling a returning function without a return place")
378 self.stack_mut().pop();
384 // cannot use the shim here, because that will only result in infinite recursion
385 ty
::InstanceDef
::Virtual(_
, idx
) => {
386 let mut args
= args
.to_vec();
387 // We have to implement all "object safe receivers". Currently we
388 // support built-in pointers (&, &mut, Box) as well as unsized-self. We do
389 // not yet support custom self types.
390 // Also see librustc_codegen_llvm/abi.rs and librustc_codegen_llvm/mir/block.rs.
391 let receiver_place
= match args
[0].layout
.ty
.builtin_deref(true) {
394 self.deref_operand(args
[0])?
398 args
[0].assert_mem_place(self)
401 // Find and consult vtable
402 let vtable
= receiver_place
.vtable();
403 let drop_fn
= self.get_vtable_slot(vtable
, u64::try_from(idx
).unwrap())?
;
405 // `*mut receiver_place.layout.ty` is almost the layout that we
406 // want for args[0]: We have to project to field 0 because we want
408 assert
!(receiver_place
.layout
.is_unsized());
409 let receiver_ptr_ty
= self.tcx
.mk_mut_ptr(receiver_place
.layout
.ty
);
410 let this_receiver_ptr
= self.layout_of(receiver_ptr_ty
)?
.field(self, 0)?
;
411 // Adjust receiver argument.
413 OpTy
::from(ImmTy
::from_immediate(receiver_place
.ptr
.into(), this_receiver_ptr
));
414 trace
!("Patched self operand to {:#?}", args
[0]);
415 // recurse with concrete function
416 self.eval_fn_call(drop_fn
, caller_abi
, &args
, ret
, unwind
)
423 place
: PlaceTy
<'tcx
, M
::PointerTag
>,
424 instance
: ty
::Instance
<'tcx
>,
425 target
: mir
::BasicBlock
,
426 unwind
: Option
<mir
::BasicBlock
>,
427 ) -> InterpResult
<'tcx
> {
428 trace
!("drop_in_place: {:?},\n {:?}, {:?}", *place
, place
.layout
.ty
, instance
);
429 // We take the address of the object. This may well be unaligned, which is fine
430 // for us here. However, unaligned accesses will probably make the actual drop
431 // implementation fail -- a problem shared by rustc.
432 let place
= self.force_allocation(place
)?
;
434 let (instance
, place
) = match place
.layout
.ty
.kind
{
436 // Dropping a trait object.
437 self.unpack_dyn_trait(place
)?
439 _
=> (instance
, place
),
442 let arg
= ImmTy
::from_immediate(
444 self.layout_of(self.tcx
.mk_mut_ptr(place
.layout
.ty
))?
,
447 let ty
= self.tcx
.mk_unit(); // return type is ()
448 let dest
= MPlaceTy
::dangling(self.layout_of(ty
)?
, self);
451 FnVal
::Instance(instance
),
454 Some((dest
.into(), target
)),