]> git.proxmox.com Git - rustc.git/blob - src/librustc_mir/interpret/terminator.rs
New upstream version 1.47.0+dfsg1
[rustc.git] / src / librustc_mir / interpret / terminator.rs
1 use std::borrow::Cow;
2 use std::convert::TryFrom;
3
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;
9
10 use super::{
11 FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, StackPopCleanup,
12 };
13
14 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
15 pub(super) fn eval_terminator(
16 &mut self,
17 terminator: &mir::Terminator<'tcx>,
18 ) -> InterpResult<'tcx> {
19 use rustc_middle::mir::TerminatorKind::*;
20 match terminator.kind {
21 Return => {
22 self.pop_stack_frame(/* unwinding */ false)?
23 }
24
25 Goto { target } => self.go_to_block(target),
26
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);
31
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];
35
36 for (index, &const_int) in values.iter().enumerate() {
37 // Compare using binary_op, to also support pointer values
38 let res = self
39 .overflowing_binary_op(
40 mir::BinOp::Eq,
41 discr,
42 ImmTy::from_uint(const_int, discr.layout),
43 )?
44 .0;
45 if res.to_bool()? {
46 target_block = targets[index];
47 break;
48 }
49 }
50
51 self.go_to_block(target_block);
52 }
53
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 {
59 ty::FnPtr(sig) => {
60 let caller_abi = sig.abi();
61 let fn_ptr = self.read_scalar(func)?.check_init()?;
62 let fn_val = self.memory.get_fn(fn_ptr)?;
63 (fn_val, caller_abi)
64 }
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())
68 }
69 _ => span_bug!(
70 terminator.source_info.span,
71 "invalid callee of type {:?}",
72 func.layout.ty
73 ),
74 };
75 let args = self.eval_operands(args)?;
76 let ret = match destination {
77 Some((dest, ret)) => Some((self.eval_place(dest)?, ret)),
78 None => None,
79 };
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");
85 }
86 }
87
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);
92
93 let instance = Instance::resolve_drop_in_place(*self.tcx, ty);
94 self.drop_in_place(place, instance, target, unwind)?;
95 }
96
97 Assert { ref cond, expected, ref msg, target, cleanup } => {
98 let cond_val =
99 self.read_immediate(self.eval_operand(cond, None)?)?.to_scalar()?.to_bool()?;
100 if expected == cond_val {
101 self.go_to_block(target);
102 } else {
103 M::assert_panic(self, msg, cleanup)?;
104 }
105 }
106
107 Abort => {
108 M::abort(self)?;
109 }
110
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
114 Resume => {
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)?;
119 return Ok(());
120 }
121
122 // It is UB to ever encounter this.
123 Unreachable => throw_ub!(Unreachable),
124
125 // These should never occur for MIR we actually run.
126 DropAndReplace { .. }
127 | FalseEdge { .. }
128 | FalseUnwind { .. }
129 | Yield { .. }
130 | GeneratorDrop => span_bug!(
131 terminator.source_info.span,
132 "{:#?} should have been eliminated by MIR pass",
133 terminator.kind
134 ),
135
136 // Inline assembly can't be interpreted.
137 InlineAsm { .. } => throw_unsup_format!("inline assembly is not supported"),
138 }
139
140 Ok(())
141 }
142
143 fn check_argument_compat(
144 rust_abi: bool,
145 caller: TyAndLayout<'tcx>,
146 callee: TyAndLayout<'tcx>,
147 ) -> bool {
148 if caller.ty == callee.ty {
149 // No question
150 return true;
151 }
152 if !rust_abi {
153 // Don't risk anything
154 return false;
155 }
156 // Compare layout
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
163 }
164 (
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,
168 // Be conservative
169 _ => false,
170 }
171 }
172
173 /// Pass a single argument, checking the types for compatibility.
174 fn pass_argument(
175 &mut self,
176 rust_abi: bool,
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() {
181 // Nothing to do.
182 trace!("Skipping callee ZST");
183 return Ok(());
184 }
185 let caller_arg = caller_arg.next().ok_or_else(|| {
186 err_ub_format!("calling a function with fewer arguments than it requires")
187 })?;
188 if rust_abi {
189 assert!(!caller_arg.layout.is_zst(), "ZSTs must have been already filtered out");
190 }
191 // Now, check
192 if !Self::check_argument_compat(rust_abi, caller_arg.layout, callee_arg.layout) {
193 throw_ub_format!(
194 "calling a function with argument of type {:?} passing data of type {:?}",
195 callee_arg.layout.ty,
196 caller_arg.layout.ty
197 )
198 }
199 // We allow some transmutes here
200 self.copy_op_transmute(caller_arg, callee_arg)
201 }
202
203 /// Call this function -- pushing the stack frame and initializing the arguments.
204 fn eval_fn_call(
205 &mut self,
206 fn_val: FnVal<'tcx, M::ExtraFnVal>,
207 caller_abi: Abi,
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);
213
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);
218 }
219 };
220
221 // ABI check
222 {
223 let callee_abi = {
224 let instance_ty = instance.ty(*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),
230 }
231 };
232 let normalize_abi = |abi| match abi {
233 Abi::Rust | Abi::RustCall | Abi::RustIntrinsic | Abi::PlatformIntrinsic =>
234 // These are all the same ABI, really.
235 {
236 Abi::Rust
237 }
238 abi => abi,
239 };
240 if normalize_abi(caller_abi) != normalize_abi(callee_abi) {
241 throw_ub_format!(
242 "calling a function with ABI {:?} using caller ABI {:?}",
243 callee_abi,
244 caller_abi
245 )
246 }
247 }
248
249 match instance.def {
250 ty::InstanceDef::Intrinsic(..) => {
251 assert!(caller_abi == Abi::RustIntrinsic || caller_abi == Abi::PlatformIntrinsic);
252 M::call_intrinsic(self, instance, args, ret, unwind)
253 }
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)? {
263 Some(body) => body,
264 None => return Ok(()),
265 };
266
267 self.push_stack_frame(
268 instance,
269 body,
270 ret.map(|p| p.0),
271 StackPopCleanup::Goto { ret: ret.map(|p| p.1), unwind },
272 )?;
273
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 {
277 trace!(
278 "caller ABI: {:?}, args: {:#?}",
279 caller_abi,
280 args.iter()
281 .map(|arg| (arg.layout.ty, format!("{:?}", **arg)))
282 .collect::<Vec<_>>()
283 );
284 trace!(
285 "spread_arg: {:?}, locals: {:#?}",
286 body.spread_arg,
287 body.args_iter()
288 .map(|local| (
289 local,
290 self.layout_of_local(self.frame(), local, None).unwrap().ty
291 ))
292 .collect::<Vec<_>>()
293 );
294
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,
299 _ => false,
300 };
301 // We have two iterators: Where the arguments come from,
302 // and where they go to.
303
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() {
310 // Untuple
311 let (&untuple_arg, args) = args.split_last().unwrap();
312 trace!("eval_fn_call: Will pass last argument by untupling");
313 Cow::from(
314 args.iter()
315 .map(|&a| Ok(a))
316 .chain(
317 (0..untuple_arg.layout.fields.count())
318 .map(|i| self.operand_field(untuple_arg, i)),
319 )
320 .collect::<InterpResult<'_, Vec<OpTy<'tcx, M::PointerTag>>>>(
321 )?,
322 )
323 } else {
324 // Plain arg passing
325 Cow::from(args)
326 };
327 // Skip ZSTs
328 let mut caller_iter =
329 caller_args.iter().filter(|op| !rust_abi || !op.layout.is_zst()).copied();
330
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 {
339 // Must be a tuple
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)?;
343 }
344 } else {
345 // Normal argument
346 self.pass_argument(rust_abi, &mut caller_iter, dest)?;
347 }
348 }
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")
352 }
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(
357 rust_abi,
358 caller_ret.layout,
359 callee_ret.layout,
360 ) {
361 throw_ub_format!(
362 "calling a function with return type {:?} passing \
363 return place of type {:?}",
364 callee_ret.layout.ty,
365 caller_ret.layout.ty
366 )
367 }
368 } else {
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")
373 }
374 }
375 };
376 match res {
377 Err(err) => {
378 self.stack_mut().pop();
379 Err(err)
380 }
381 Ok(()) => Ok(()),
382 }
383 }
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) {
392 Some(_) => {
393 // Built-in pointer.
394 self.deref_operand(args[0])?
395 }
396 None => {
397 // Unsized self.
398 args[0].assert_mem_place(self)
399 }
400 };
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())?;
404
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
407 // a thin pointer.
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.
412 args[0] =
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)
417 }
418 }
419 }
420
421 fn drop_in_place(
422 &mut self,
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)?;
433
434 let (instance, place) = match place.layout.ty.kind {
435 ty::Dynamic(..) => {
436 // Dropping a trait object.
437 self.unpack_dyn_trait(place)?
438 }
439 _ => (instance, place),
440 };
441
442 let arg = ImmTy::from_immediate(
443 place.to_ref(),
444 self.layout_of(self.tcx.mk_mut_ptr(place.layout.ty))?,
445 );
446
447 let ty = self.tcx.mk_unit(); // return type is ()
448 let dest = MPlaceTy::dangling(self.layout_of(ty)?, self);
449
450 self.eval_fn_call(
451 FnVal::Instance(instance),
452 Abi::Rust,
453 &[arg.into()],
454 Some((dest.into(), target)),
455 unwind,
456 )
457 }
458 }