]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/eval_context.rs
45928d7b02e36d6d5dc517cd93e959c53995381b
[rust.git] / compiler / rustc_const_eval / src / interpret / eval_context.rs
1 use std::cell::Cell;
2 use std::fmt;
3 use std::mem;
4
5 use rustc_hir::{self as hir, def_id::DefId, definitions::DefPathData};
6 use rustc_index::vec::IndexVec;
7 use rustc_middle::mir;
8 use rustc_middle::mir::interpret::{InterpError, InvalidProgramInfo};
9 use rustc_middle::ty::layout::{
10     self, FnAbiError, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOf, LayoutOfHelpers,
11     TyAndLayout,
12 };
13 use rustc_middle::ty::{
14     self, query::TyCtxtAt, subst::SubstsRef, ParamEnv, Ty, TyCtxt, TypeFoldable,
15 };
16 use rustc_mir_dataflow::storage::always_storage_live_locals;
17 use rustc_session::Limit;
18 use rustc_span::{Pos, Span};
19 use rustc_target::abi::{call::FnAbi, Align, HasDataLayout, Size, TargetDataLayout};
20
21 use super::{
22     AllocId, GlobalId, Immediate, InterpErrorInfo, InterpResult, MPlaceTy, Machine, MemPlace,
23     MemPlaceMeta, Memory, MemoryKind, Operand, Place, PlaceTy, PointerArithmetic, Provenance,
24     Scalar, ScalarMaybeUninit, StackPopJump,
25 };
26 use crate::transform::validate::equal_up_to_regions;
27
28 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
29     /// Stores the `Machine` instance.
30     ///
31     /// Note: the stack is provided by the machine.
32     pub machine: M,
33
34     /// The results of the type checker, from rustc.
35     /// The span in this is the "root" of the evaluation, i.e., the const
36     /// we are evaluating (if this is CTFE).
37     pub tcx: TyCtxtAt<'tcx>,
38
39     /// Bounds in scope for polymorphic evaluations.
40     pub(crate) param_env: ty::ParamEnv<'tcx>,
41
42     /// The virtual memory system.
43     pub memory: Memory<'mir, 'tcx, M>,
44
45     /// The recursion limit (cached from `tcx.recursion_limit(())`)
46     pub recursion_limit: Limit,
47 }
48
49 // The Phantomdata exists to prevent this type from being `Send`. If it were sent across a thread
50 // boundary and dropped in the other thread, it would exit the span in the other thread.
51 struct SpanGuard(tracing::Span, std::marker::PhantomData<*const u8>);
52
53 impl SpanGuard {
54     /// By default a `SpanGuard` does nothing.
55     fn new() -> Self {
56         Self(tracing::Span::none(), std::marker::PhantomData)
57     }
58
59     /// If a span is entered, we exit the previous span (if any, normally none) and enter the
60     /// new span. This is mainly so we don't have to use `Option` for the `tracing_span` field of
61     /// `Frame` by creating a dummy span to being with and then entering it once the frame has
62     /// been pushed.
63     fn enter(&mut self, span: tracing::Span) {
64         // This executes the destructor on the previous instance of `SpanGuard`, ensuring that
65         // we never enter or exit more spans than vice versa. Unless you `mem::leak`, then we
66         // can't protect the tracing stack, but that'll just lead to weird logging, no actual
67         // problems.
68         *self = Self(span, std::marker::PhantomData);
69         self.0.with_subscriber(|(id, dispatch)| {
70             dispatch.enter(id);
71         });
72     }
73 }
74
75 impl Drop for SpanGuard {
76     fn drop(&mut self) {
77         self.0.with_subscriber(|(id, dispatch)| {
78             dispatch.exit(id);
79         });
80     }
81 }
82
83 /// A stack frame.
84 pub struct Frame<'mir, 'tcx, Prov: Provenance = AllocId, Extra = ()> {
85     ////////////////////////////////////////////////////////////////////////////////
86     // Function and callsite information
87     ////////////////////////////////////////////////////////////////////////////////
88     /// The MIR for the function called on this frame.
89     pub body: &'mir mir::Body<'tcx>,
90
91     /// The def_id and substs of the current function.
92     pub instance: ty::Instance<'tcx>,
93
94     /// Extra data for the machine.
95     pub extra: Extra,
96
97     ////////////////////////////////////////////////////////////////////////////////
98     // Return place and locals
99     ////////////////////////////////////////////////////////////////////////////////
100     /// Work to perform when returning from this function.
101     pub return_to_block: StackPopCleanup,
102
103     /// The location where the result of the current stack frame should be written to,
104     /// and its layout in the caller.
105     pub return_place: PlaceTy<'tcx, Prov>,
106
107     /// The list of locals for this stack frame, stored in order as
108     /// `[return_ptr, arguments..., variables..., temporaries...]`.
109     /// The locals are stored as `Option<Value>`s.
110     /// `None` represents a local that is currently dead, while a live local
111     /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
112     ///
113     /// Do *not* access this directly; always go through the machine hook!
114     pub locals: IndexVec<mir::Local, LocalState<'tcx, Prov>>,
115
116     /// The span of the `tracing` crate is stored here.
117     /// When the guard is dropped, the span is exited. This gives us
118     /// a full stack trace on all tracing statements.
119     tracing_span: SpanGuard,
120
121     ////////////////////////////////////////////////////////////////////////////////
122     // Current position within the function
123     ////////////////////////////////////////////////////////////////////////////////
124     /// If this is `Err`, we are not currently executing any particular statement in
125     /// this frame (can happen e.g. during frame initialization, and during unwinding on
126     /// frames without cleanup code).
127     /// We basically abuse `Result` as `Either`.
128     ///
129     /// Needs to be public because ConstProp does unspeakable things to it.
130     pub loc: Result<mir::Location, Span>,
131 }
132
133 /// What we store about a frame in an interpreter backtrace.
134 #[derive(Debug)]
135 pub struct FrameInfo<'tcx> {
136     pub instance: ty::Instance<'tcx>,
137     pub span: Span,
138     pub lint_root: Option<hir::HirId>,
139 }
140
141 /// Unwind information.
142 #[derive(Clone, Copy, Eq, PartialEq, Debug)]
143 pub enum StackPopUnwind {
144     /// The cleanup block.
145     Cleanup(mir::BasicBlock),
146     /// No cleanup needs to be done.
147     Skip,
148     /// Unwinding is not allowed (UB).
149     NotAllowed,
150 }
151
152 #[derive(Clone, Copy, Eq, PartialEq, Debug)] // Miri debug-prints these
153 pub enum StackPopCleanup {
154     /// Jump to the next block in the caller, or cause UB if None (that's a function
155     /// that may never return). Also store layout of return place so
156     /// we can validate it at that layout.
157     /// `ret` stores the block we jump to on a normal return, while `unwind`
158     /// stores the block used for cleanup during unwinding.
159     Goto { ret: Option<mir::BasicBlock>, unwind: StackPopUnwind },
160     /// The root frame of the stack: nowhere else to jump to.
161     /// `cleanup` says whether locals are deallocated. Static computation
162     /// wants them leaked to intern what they need (and just throw away
163     /// the entire `ecx` when it is done).
164     Root { cleanup: bool },
165 }
166
167 /// State of a local variable including a memoized layout
168 #[derive(Clone, Debug)]
169 pub struct LocalState<'tcx, Prov: Provenance = AllocId> {
170     pub value: LocalValue<Prov>,
171     /// Don't modify if `Some`, this is only used to prevent computing the layout twice
172     pub layout: Cell<Option<TyAndLayout<'tcx>>>,
173 }
174
175 /// Current value of a local variable
176 #[derive(Copy, Clone, Debug)] // Miri debug-prints these
177 pub enum LocalValue<Prov: Provenance = AllocId> {
178     /// This local is not currently alive, and cannot be used at all.
179     Dead,
180     /// A normal, live local.
181     /// Mostly for convenience, we re-use the `Operand` type here.
182     /// This is an optimization over just always having a pointer here;
183     /// we can thus avoid doing an allocation when the local just stores
184     /// immediate values *and* never has its address taken.
185     Live(Operand<Prov>),
186 }
187
188 impl<'tcx, Prov: Provenance + 'static> LocalState<'tcx, Prov> {
189     /// Read the local's value or error if the local is not yet live or not live anymore.
190     ///
191     /// Note: This may only be invoked from the `Machine::access_local` hook and not from
192     /// anywhere else. You may be invalidating machine invariants if you do!
193     #[inline]
194     pub fn access(&self) -> InterpResult<'tcx, &Operand<Prov>> {
195         match &self.value {
196             LocalValue::Dead => throw_ub!(DeadLocal), // could even be "invalid program"?
197             LocalValue::Live(val) => Ok(val),
198         }
199     }
200
201     /// Overwrite the local.  If the local can be overwritten in place, return a reference
202     /// to do so; otherwise return the `MemPlace` to consult instead.
203     ///
204     /// Note: This may only be invoked from the `Machine::access_local_mut` hook and not from
205     /// anywhere else. You may be invalidating machine invariants if you do!
206     #[inline]
207     pub fn access_mut(&mut self) -> InterpResult<'tcx, &mut Operand<Prov>> {
208         match &mut self.value {
209             LocalValue::Dead => throw_ub!(DeadLocal), // could even be "invalid program"?
210             LocalValue::Live(val) => Ok(val),
211         }
212     }
213 }
214
215 impl<'mir, 'tcx, Prov: Provenance> Frame<'mir, 'tcx, Prov> {
216     pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Prov, Extra> {
217         Frame {
218             body: self.body,
219             instance: self.instance,
220             return_to_block: self.return_to_block,
221             return_place: self.return_place,
222             locals: self.locals,
223             loc: self.loc,
224             extra,
225             tracing_span: self.tracing_span,
226         }
227     }
228 }
229
230 impl<'mir, 'tcx, Prov: Provenance, Extra> Frame<'mir, 'tcx, Prov, Extra> {
231     /// Get the current location within the Frame.
232     ///
233     /// If this is `Err`, we are not currently executing any particular statement in
234     /// this frame (can happen e.g. during frame initialization, and during unwinding on
235     /// frames without cleanup code).
236     /// We basically abuse `Result` as `Either`.
237     ///
238     /// Used by priroda.
239     pub fn current_loc(&self) -> Result<mir::Location, Span> {
240         self.loc
241     }
242
243     /// Return the `SourceInfo` of the current instruction.
244     pub fn current_source_info(&self) -> Option<&mir::SourceInfo> {
245         self.loc.ok().map(|loc| self.body.source_info(loc))
246     }
247
248     pub fn current_span(&self) -> Span {
249         match self.loc {
250             Ok(loc) => self.body.source_info(loc).span,
251             Err(span) => span,
252         }
253     }
254 }
255
256 impl<'tcx> fmt::Display for FrameInfo<'tcx> {
257     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258         ty::tls::with(|tcx| {
259             if tcx.def_key(self.instance.def_id()).disambiguated_data.data
260                 == DefPathData::ClosureExpr
261             {
262                 write!(f, "inside closure")?;
263             } else {
264                 write!(f, "inside `{}`", self.instance)?;
265             }
266             if !self.span.is_dummy() {
267                 let sm = tcx.sess.source_map();
268                 let lo = sm.lookup_char_pos(self.span.lo());
269                 write!(
270                     f,
271                     " at {}:{}:{}",
272                     sm.filename_for_diagnostics(&lo.file.name),
273                     lo.line,
274                     lo.col.to_usize() + 1
275                 )?;
276             }
277             Ok(())
278         })
279     }
280 }
281
282 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
283     #[inline]
284     fn data_layout(&self) -> &TargetDataLayout {
285         &self.tcx.data_layout
286     }
287 }
288
289 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
290 where
291     M: Machine<'mir, 'tcx>,
292 {
293     #[inline]
294     fn tcx(&self) -> TyCtxt<'tcx> {
295         *self.tcx
296     }
297 }
298
299 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
300 where
301     M: Machine<'mir, 'tcx>,
302 {
303     fn param_env(&self) -> ty::ParamEnv<'tcx> {
304         self.param_env
305     }
306 }
307
308 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> LayoutOfHelpers<'tcx> for InterpCx<'mir, 'tcx, M> {
309     type LayoutOfResult = InterpResult<'tcx, TyAndLayout<'tcx>>;
310
311     #[inline]
312     fn layout_tcx_at_span(&self) -> Span {
313         // Using the cheap root span for performance.
314         self.tcx.span
315     }
316
317     #[inline]
318     fn handle_layout_err(
319         &self,
320         err: LayoutError<'tcx>,
321         _: Span,
322         _: Ty<'tcx>,
323     ) -> InterpErrorInfo<'tcx> {
324         err_inval!(Layout(err)).into()
325     }
326 }
327
328 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> FnAbiOfHelpers<'tcx> for InterpCx<'mir, 'tcx, M> {
329     type FnAbiOfResult = InterpResult<'tcx, &'tcx FnAbi<'tcx, Ty<'tcx>>>;
330
331     fn handle_fn_abi_err(
332         &self,
333         err: FnAbiError<'tcx>,
334         _span: Span,
335         _fn_abi_request: FnAbiRequest<'tcx>,
336     ) -> InterpErrorInfo<'tcx> {
337         match err {
338             FnAbiError::Layout(err) => err_inval!(Layout(err)).into(),
339             FnAbiError::AdjustForForeignAbi(err) => {
340                 err_inval!(FnAbiAdjustForForeignAbi(err)).into()
341             }
342         }
343     }
344 }
345
346 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
347 /// This test should be symmetric, as it is primarily about layout compatibility.
348 pub(super) fn mir_assign_valid_types<'tcx>(
349     tcx: TyCtxt<'tcx>,
350     param_env: ParamEnv<'tcx>,
351     src: TyAndLayout<'tcx>,
352     dest: TyAndLayout<'tcx>,
353 ) -> bool {
354     // Type-changing assignments can happen when subtyping is used. While
355     // all normal lifetimes are erased, higher-ranked types with their
356     // late-bound lifetimes are still around and can lead to type
357     // differences. So we compare ignoring lifetimes.
358     if equal_up_to_regions(tcx, param_env, src.ty, dest.ty) {
359         // Make sure the layout is equal, too -- just to be safe. Miri really
360         // needs layout equality. For performance reason we skip this check when
361         // the types are equal. Equal types *can* have different layouts when
362         // enum downcast is involved (as enum variants carry the type of the
363         // enum), but those should never occur in assignments.
364         if cfg!(debug_assertions) || src.ty != dest.ty {
365             assert_eq!(src.layout, dest.layout);
366         }
367         true
368     } else {
369         false
370     }
371 }
372
373 /// Use the already known layout if given (but sanity check in debug mode),
374 /// or compute the layout.
375 #[cfg_attr(not(debug_assertions), inline(always))]
376 pub(super) fn from_known_layout<'tcx>(
377     tcx: TyCtxtAt<'tcx>,
378     param_env: ParamEnv<'tcx>,
379     known_layout: Option<TyAndLayout<'tcx>>,
380     compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
381 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
382     match known_layout {
383         None => compute(),
384         Some(known_layout) => {
385             if cfg!(debug_assertions) {
386                 let check_layout = compute()?;
387                 if !mir_assign_valid_types(tcx.tcx, param_env, check_layout, known_layout) {
388                     span_bug!(
389                         tcx.span,
390                         "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
391                         known_layout.ty,
392                         check_layout.ty,
393                     );
394                 }
395             }
396             Ok(known_layout)
397         }
398     }
399 }
400
401 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
402     pub fn new(
403         tcx: TyCtxt<'tcx>,
404         root_span: Span,
405         param_env: ty::ParamEnv<'tcx>,
406         machine: M,
407     ) -> Self {
408         InterpCx {
409             machine,
410             tcx: tcx.at(root_span),
411             param_env,
412             memory: Memory::new(),
413             recursion_limit: tcx.recursion_limit(),
414         }
415     }
416
417     #[inline(always)]
418     pub fn cur_span(&self) -> Span {
419         // This deliberately does *not* honor `requires_caller_location` since it is used for much
420         // more than just panics.
421         self.stack().last().map_or(self.tcx.span, |f| f.current_span())
422     }
423
424     #[inline(always)]
425     pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::Provenance, M::FrameExtra>] {
426         M::stack(self)
427     }
428
429     #[inline(always)]
430     pub(crate) fn stack_mut(
431         &mut self,
432     ) -> &mut Vec<Frame<'mir, 'tcx, M::Provenance, M::FrameExtra>> {
433         M::stack_mut(self)
434     }
435
436     #[inline(always)]
437     pub fn frame_idx(&self) -> usize {
438         let stack = self.stack();
439         assert!(!stack.is_empty());
440         stack.len() - 1
441     }
442
443     #[inline(always)]
444     pub fn frame(&self) -> &Frame<'mir, 'tcx, M::Provenance, M::FrameExtra> {
445         self.stack().last().expect("no call frames exist")
446     }
447
448     #[inline(always)]
449     pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::Provenance, M::FrameExtra> {
450         self.stack_mut().last_mut().expect("no call frames exist")
451     }
452
453     #[inline(always)]
454     pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
455         self.frame().body
456     }
457
458     #[inline(always)]
459     pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
460         assert!(ty.abi.is_signed());
461         ty.size.sign_extend(value)
462     }
463
464     #[inline(always)]
465     pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
466         ty.size.truncate(value)
467     }
468
469     #[inline]
470     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
471         ty.is_freeze(self.tcx, self.param_env)
472     }
473
474     pub fn load_mir(
475         &self,
476         instance: ty::InstanceDef<'tcx>,
477         promoted: Option<mir::Promoted>,
478     ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
479         let def = instance.with_opt_param();
480         trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
481         let body = if let Some(promoted) = promoted {
482             &self.tcx.promoted_mir_opt_const_arg(def)[promoted]
483         } else {
484             M::load_mir(self, instance)?
485         };
486         // do not continue if typeck errors occurred (can only occur in local crate)
487         if let Some(err) = body.tainted_by_errors {
488             throw_inval!(AlreadyReported(err));
489         }
490         Ok(body)
491     }
492
493     /// Call this on things you got out of the MIR (so it is as generic as the current
494     /// stack frame), to bring it into the proper environment for this interpreter.
495     pub(super) fn subst_from_current_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
496         &self,
497         value: T,
498     ) -> Result<T, InterpError<'tcx>> {
499         self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
500     }
501
502     /// Call this on things you got out of the MIR (so it is as generic as the provided
503     /// stack frame), to bring it into the proper environment for this interpreter.
504     pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
505         &self,
506         frame: &Frame<'mir, 'tcx, M::Provenance, M::FrameExtra>,
507         value: T,
508     ) -> Result<T, InterpError<'tcx>> {
509         frame
510             .instance
511             .try_subst_mir_and_normalize_erasing_regions(*self.tcx, self.param_env, value)
512             .map_err(|e| {
513                 self.tcx.sess.delay_span_bug(
514                     self.cur_span(),
515                     format!("failed to normalize {}", e.get_type_for_failure()).as_str(),
516                 );
517
518                 InterpError::InvalidProgram(InvalidProgramInfo::TooGeneric)
519             })
520     }
521
522     /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
523     pub(super) fn resolve(
524         &self,
525         def: ty::WithOptConstParam<DefId>,
526         substs: SubstsRef<'tcx>,
527     ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
528         trace!("resolve: {:?}, {:#?}", def, substs);
529         trace!("param_env: {:#?}", self.param_env);
530         trace!("substs: {:#?}", substs);
531         match ty::Instance::resolve_opt_const_arg(*self.tcx, self.param_env, def, substs) {
532             Ok(Some(instance)) => Ok(instance),
533             Ok(None) => throw_inval!(TooGeneric),
534
535             // FIXME(eddyb) this could be a bit more specific than `AlreadyReported`.
536             Err(error_reported) => throw_inval!(AlreadyReported(error_reported)),
537         }
538     }
539
540     #[inline(always)]
541     pub fn layout_of_local(
542         &self,
543         frame: &Frame<'mir, 'tcx, M::Provenance, M::FrameExtra>,
544         local: mir::Local,
545         layout: Option<TyAndLayout<'tcx>>,
546     ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
547         // `const_prop` runs into this with an invalid (empty) frame, so we
548         // have to support that case (mostly by skipping all caching).
549         match frame.locals.get(local).and_then(|state| state.layout.get()) {
550             None => {
551                 let layout = from_known_layout(self.tcx, self.param_env, layout, || {
552                     let local_ty = frame.body.local_decls[local].ty;
553                     let local_ty =
554                         self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty)?;
555                     self.layout_of(local_ty)
556                 })?;
557                 if let Some(state) = frame.locals.get(local) {
558                     // Layouts of locals are requested a lot, so we cache them.
559                     state.layout.set(Some(layout));
560                 }
561                 Ok(layout)
562             }
563             Some(layout) => Ok(layout),
564         }
565     }
566
567     /// Returns the actual dynamic size and alignment of the place at the given type.
568     /// Only the "meta" (metadata) part of the place matters.
569     /// This can fail to provide an answer for extern types.
570     pub(super) fn size_and_align_of(
571         &self,
572         metadata: &MemPlaceMeta<M::Provenance>,
573         layout: &TyAndLayout<'tcx>,
574     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
575         if !layout.is_unsized() {
576             return Ok(Some((layout.size, layout.align.abi)));
577         }
578         match layout.ty.kind() {
579             ty::Adt(..) | ty::Tuple(..) => {
580                 // First get the size of all statically known fields.
581                 // Don't use type_of::sizing_type_of because that expects t to be sized,
582                 // and it also rounds up to alignment, which we want to avoid,
583                 // as the unsized field's alignment could be smaller.
584                 assert!(!layout.ty.is_simd());
585                 assert!(layout.fields.count() > 0);
586                 trace!("DST layout: {:?}", layout);
587
588                 let sized_size = layout.fields.offset(layout.fields.count() - 1);
589                 let sized_align = layout.align.abi;
590                 trace!(
591                     "DST {} statically sized prefix size: {:?} align: {:?}",
592                     layout.ty,
593                     sized_size,
594                     sized_align
595                 );
596
597                 // Recurse to get the size of the dynamically sized field (must be
598                 // the last field).  Can't have foreign types here, how would we
599                 // adjust alignment and size for them?
600                 let field = layout.field(self, layout.fields.count() - 1);
601                 let Some((unsized_size, unsized_align)) = self.size_and_align_of(metadata, &field)? else {
602                     // A field with an extern type. We don't know the actual dynamic size
603                     // or the alignment.
604                     return Ok(None);
605                 };
606
607                 // FIXME (#26403, #27023): We should be adding padding
608                 // to `sized_size` (to accommodate the `unsized_align`
609                 // required of the unsized field that follows) before
610                 // summing it with `sized_size`. (Note that since #26403
611                 // is unfixed, we do not yet add the necessary padding
612                 // here. But this is where the add would go.)
613
614                 // Return the sum of sizes and max of aligns.
615                 let size = sized_size + unsized_size; // `Size` addition
616
617                 // Choose max of two known alignments (combined value must
618                 // be aligned according to more restrictive of the two).
619                 let align = sized_align.max(unsized_align);
620
621                 // Issue #27023: must add any necessary padding to `size`
622                 // (to make it a multiple of `align`) before returning it.
623                 let size = size.align_to(align);
624
625                 // Check if this brought us over the size limit.
626                 if size > self.max_size_of_val() {
627                     throw_ub!(InvalidMeta("total size is bigger than largest supported object"));
628                 }
629                 Ok(Some((size, align)))
630             }
631             ty::Dynamic(..) => {
632                 let vtable = self.scalar_to_ptr(metadata.unwrap_meta())?;
633                 // Read size and align from vtable (already checks size).
634                 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
635             }
636
637             ty::Slice(_) | ty::Str => {
638                 let len = metadata.unwrap_meta().to_machine_usize(self)?;
639                 let elem = layout.field(self, 0);
640
641                 // Make sure the slice is not too big.
642                 let size = elem.size.bytes().saturating_mul(len); // we rely on `max_size_of_val` being smaller than `u64::MAX`.
643                 let size = Size::from_bytes(size);
644                 if size > self.max_size_of_val() {
645                     throw_ub!(InvalidMeta("slice is bigger than largest supported object"));
646                 }
647                 Ok(Some((size, elem.align.abi)))
648             }
649
650             ty::Foreign(_) => Ok(None),
651
652             _ => span_bug!(self.cur_span(), "size_and_align_of::<{:?}> not supported", layout.ty),
653         }
654     }
655     #[inline]
656     pub fn size_and_align_of_mplace(
657         &self,
658         mplace: &MPlaceTy<'tcx, M::Provenance>,
659     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
660         self.size_and_align_of(&mplace.meta, &mplace.layout)
661     }
662
663     #[instrument(skip(self, body, return_place, return_to_block), level = "debug")]
664     pub fn push_stack_frame(
665         &mut self,
666         instance: ty::Instance<'tcx>,
667         body: &'mir mir::Body<'tcx>,
668         return_place: &PlaceTy<'tcx, M::Provenance>,
669         return_to_block: StackPopCleanup,
670     ) -> InterpResult<'tcx> {
671         trace!("body: {:#?}", body);
672         // first push a stack frame so we have access to the local substs
673         let pre_frame = Frame {
674             body,
675             loc: Err(body.span), // Span used for errors caused during preamble.
676             return_to_block,
677             return_place: return_place.clone(),
678             // empty local array, we fill it in below, after we are inside the stack frame and
679             // all methods actually know about the frame
680             locals: IndexVec::new(),
681             instance,
682             tracing_span: SpanGuard::new(),
683             extra: (),
684         };
685         let frame = M::init_frame_extra(self, pre_frame)?;
686         self.stack_mut().push(frame);
687
688         // Make sure all the constants required by this frame evaluate successfully (post-monomorphization check).
689         for const_ in &body.required_consts {
690             let span = const_.span;
691             let const_ =
692                 self.subst_from_current_frame_and_normalize_erasing_regions(const_.literal)?;
693             self.mir_const_to_op(&const_, None).map_err(|err| {
694                 // If there was an error, set the span of the current frame to this constant.
695                 // Avoiding doing this when evaluation succeeds.
696                 self.frame_mut().loc = Err(span);
697                 err
698             })?;
699         }
700
701         // Most locals are initially dead.
702         let dummy = LocalState { value: LocalValue::Dead, layout: Cell::new(None) };
703         let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
704
705         // Now mark those locals as live that have no `Storage*` annotations.
706         let always_live = always_storage_live_locals(self.body());
707         for local in locals.indices() {
708             if always_live.contains(local) {
709                 locals[local].value = LocalValue::Live(Operand::Immediate(Immediate::Uninit));
710             }
711         }
712         // done
713         self.frame_mut().locals = locals;
714         M::after_stack_push(self)?;
715         self.frame_mut().loc = Ok(mir::Location::START);
716
717         let span = info_span!("frame", "{}", instance);
718         self.frame_mut().tracing_span.enter(span);
719
720         Ok(())
721     }
722
723     /// Jump to the given block.
724     #[inline]
725     pub fn go_to_block(&mut self, target: mir::BasicBlock) {
726         self.frame_mut().loc = Ok(mir::Location { block: target, statement_index: 0 });
727     }
728
729     /// *Return* to the given `target` basic block.
730     /// Do *not* use for unwinding! Use `unwind_to_block` instead.
731     ///
732     /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
733     pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
734         if let Some(target) = target {
735             self.go_to_block(target);
736             Ok(())
737         } else {
738             throw_ub!(Unreachable)
739         }
740     }
741
742     /// *Unwind* to the given `target` basic block.
743     /// Do *not* use for returning! Use `return_to_block` instead.
744     ///
745     /// If `target` is `StackPopUnwind::Skip`, that indicates the function does not need cleanup
746     /// during unwinding, and we will just keep propagating that upwards.
747     ///
748     /// If `target` is `StackPopUnwind::NotAllowed`, that indicates the function does not allow
749     /// unwinding, and doing so is UB.
750     pub fn unwind_to_block(&mut self, target: StackPopUnwind) -> InterpResult<'tcx> {
751         self.frame_mut().loc = match target {
752             StackPopUnwind::Cleanup(block) => Ok(mir::Location { block, statement_index: 0 }),
753             StackPopUnwind::Skip => Err(self.frame_mut().body.span),
754             StackPopUnwind::NotAllowed => {
755                 throw_ub_format!("unwinding past a stack frame that does not allow unwinding")
756             }
757         };
758         Ok(())
759     }
760
761     /// Pops the current frame from the stack, deallocating the
762     /// memory for allocated locals.
763     ///
764     /// If `unwinding` is `false`, then we are performing a normal return
765     /// from a function. In this case, we jump back into the frame of the caller,
766     /// and continue execution as normal.
767     ///
768     /// If `unwinding` is `true`, then we are in the middle of a panic,
769     /// and need to unwind this frame. In this case, we jump to the
770     /// `cleanup` block for the function, which is responsible for running
771     /// `Drop` impls for any locals that have been initialized at this point.
772     /// The cleanup block ends with a special `Resume` terminator, which will
773     /// cause us to continue unwinding.
774     #[instrument(skip(self), level = "debug")]
775     pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
776         info!(
777             "popping stack frame ({})",
778             if unwinding { "during unwinding" } else { "returning from function" }
779         );
780
781         // Check `unwinding`.
782         assert_eq!(
783             unwinding,
784             match self.frame().loc {
785                 Ok(loc) => self.body().basic_blocks()[loc.block].is_cleanup,
786                 Err(_) => true,
787             }
788         );
789         if unwinding && self.frame_idx() == 0 {
790             throw_ub_format!("unwinding past the topmost frame of the stack");
791         }
792
793         // Copy return value. Must of course happen *before* we deallocate the locals.
794         let copy_ret_result = if !unwinding {
795             let op = self
796                 .local_to_op(self.frame(), mir::RETURN_PLACE, None)
797                 .expect("return place should always be live");
798             let dest = self.frame().return_place.clone();
799             let err = self.copy_op(&op, &dest, /*allow_transmute*/ true);
800             trace!("return value: {:?}", self.dump_place(*dest));
801             // We delay actually short-circuiting on this error until *after* the stack frame is
802             // popped, since we want this error to be attributed to the caller, whose type defines
803             // this transmute.
804             err
805         } else {
806             Ok(())
807         };
808
809         // Cleanup: deallocate locals.
810         // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
811         // We do this while the frame is still on the stack, so errors point to the callee.
812         let return_to_block = self.frame().return_to_block;
813         let cleanup = match return_to_block {
814             StackPopCleanup::Goto { .. } => true,
815             StackPopCleanup::Root { cleanup, .. } => cleanup,
816         };
817         if cleanup {
818             // We need to take the locals out, since we need to mutate while iterating.
819             let locals = mem::take(&mut self.frame_mut().locals);
820             for local in &locals {
821                 self.deallocate_local(local.value)?;
822             }
823         }
824
825         // All right, now it is time to actually pop the frame.
826         // Note that its locals are gone already, but that's fine.
827         let frame =
828             self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
829         // Report error from return value copy, if any.
830         copy_ret_result?;
831
832         // If we are not doing cleanup, also skip everything else.
833         if !cleanup {
834             assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
835             assert!(!unwinding, "tried to skip cleanup during unwinding");
836             // Skip machine hook.
837             return Ok(());
838         }
839         if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
840             // The hook already did everything.
841             return Ok(());
842         }
843
844         // Normal return, figure out where to jump.
845         if unwinding {
846             // Follow the unwind edge.
847             let unwind = match return_to_block {
848                 StackPopCleanup::Goto { unwind, .. } => unwind,
849                 StackPopCleanup::Root { .. } => {
850                     panic!("encountered StackPopCleanup::Root when unwinding!")
851                 }
852             };
853             self.unwind_to_block(unwind)
854         } else {
855             // Follow the normal return edge.
856             match return_to_block {
857                 StackPopCleanup::Goto { ret, .. } => self.return_to_block(ret),
858                 StackPopCleanup::Root { .. } => {
859                     assert!(
860                         self.stack().is_empty(),
861                         "only the topmost frame can have StackPopCleanup::Root"
862                     );
863                     Ok(())
864                 }
865             }
866         }
867     }
868
869     /// Mark a storage as live, killing the previous content.
870     pub fn storage_live(&mut self, local: mir::Local) -> InterpResult<'tcx> {
871         assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
872         trace!("{:?} is now live", local);
873
874         let local_val = LocalValue::Live(Operand::Immediate(Immediate::Uninit));
875         // StorageLive expects the local to be dead, and marks it live.
876         let old = mem::replace(&mut self.frame_mut().locals[local].value, local_val);
877         if !matches!(old, LocalValue::Dead) {
878             throw_ub_format!("StorageLive on a local that was already live");
879         }
880         Ok(())
881     }
882
883     pub fn storage_dead(&mut self, local: mir::Local) -> InterpResult<'tcx> {
884         assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
885         trace!("{:?} is now dead", local);
886
887         // It is entirely okay for this local to be already dead (at least that's how we currently generate MIR)
888         let old = mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead);
889         self.deallocate_local(old)?;
890         Ok(())
891     }
892
893     #[instrument(skip(self), level = "debug")]
894     fn deallocate_local(&mut self, local: LocalValue<M::Provenance>) -> InterpResult<'tcx> {
895         if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
896             // All locals have a backing allocation, even if the allocation is empty
897             // due to the local having ZST type. Hence we can `unwrap`.
898             trace!(
899                 "deallocating local {:?}: {:?}",
900                 local,
901                 // Locals always have a `alloc_id` (they are never the result of a int2ptr).
902                 self.dump_alloc(ptr.provenance.unwrap().get_alloc_id().unwrap())
903             );
904             self.deallocate_ptr(ptr, None, MemoryKind::Stack)?;
905         };
906         Ok(())
907     }
908
909     pub fn eval_to_allocation(
910         &self,
911         gid: GlobalId<'tcx>,
912     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
913         // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
914         // and thus don't care about the parameter environment. While we could just use
915         // `self.param_env`, that would mean we invoke the query to evaluate the static
916         // with different parameter environments, thus causing the static to be evaluated
917         // multiple times.
918         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
919             ty::ParamEnv::reveal_all()
920         } else {
921             self.param_env
922         };
923         let param_env = param_env.with_const();
924         // Use a precise span for better cycle errors.
925         let val = self.tcx.at(self.cur_span()).eval_to_allocation_raw(param_env.and(gid))?;
926         self.raw_const_to_mplace(val)
927     }
928
929     #[must_use]
930     pub fn dump_place(&self, place: Place<M::Provenance>) -> PlacePrinter<'_, 'mir, 'tcx, M> {
931         PlacePrinter { ecx: self, place }
932     }
933
934     #[must_use]
935     pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
936         let mut frames = Vec::new();
937         // This deliberately does *not* honor `requires_caller_location` since it is used for much
938         // more than just panics.
939         for frame in self.stack().iter().rev() {
940             let lint_root = frame.current_source_info().and_then(|source_info| {
941                 match &frame.body.source_scopes[source_info.scope].local_data {
942                     mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
943                     mir::ClearCrossCrate::Clear => None,
944                 }
945             });
946             let span = frame.current_span();
947
948             frames.push(FrameInfo { span, instance: frame.instance, lint_root });
949         }
950         trace!("generate stacktrace: {:#?}", frames);
951         frames
952     }
953 }
954
955 #[doc(hidden)]
956 /// Helper struct for the `dump_place` function.
957 pub struct PlacePrinter<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
958     ecx: &'a InterpCx<'mir, 'tcx, M>,
959     place: Place<M::Provenance>,
960 }
961
962 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
963     for PlacePrinter<'a, 'mir, 'tcx, M>
964 {
965     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
966         match self.place {
967             Place::Local { frame, local } => {
968                 let mut allocs = Vec::new();
969                 write!(fmt, "{:?}", local)?;
970                 if frame != self.ecx.frame_idx() {
971                     write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?;
972                 }
973                 write!(fmt, ":")?;
974
975                 match self.ecx.stack()[frame].locals[local].value {
976                     LocalValue::Dead => write!(fmt, " is dead")?,
977                     LocalValue::Live(Operand::Immediate(Immediate::Uninit)) => {
978                         write!(fmt, " is uninitialized")?
979                     }
980                     LocalValue::Live(Operand::Indirect(mplace)) => {
981                         write!(
982                             fmt,
983                             " by {} ref {:?}:",
984                             match mplace.meta {
985                                 MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
986                                 MemPlaceMeta::None => String::new(),
987                             },
988                             mplace.ptr,
989                         )?;
990                         allocs.extend(mplace.ptr.provenance.map(Provenance::get_alloc_id));
991                     }
992                     LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
993                         write!(fmt, " {:?}", val)?;
994                         if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val {
995                             allocs.push(ptr.provenance.get_alloc_id());
996                         }
997                     }
998                     LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
999                         write!(fmt, " ({:?}, {:?})", val1, val2)?;
1000                         if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val1 {
1001                             allocs.push(ptr.provenance.get_alloc_id());
1002                         }
1003                         if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val2 {
1004                             allocs.push(ptr.provenance.get_alloc_id());
1005                         }
1006                     }
1007                 }
1008
1009                 write!(fmt, ": {:?}", self.ecx.dump_allocs(allocs.into_iter().flatten().collect()))
1010             }
1011             Place::Ptr(mplace) => match mplace.ptr.provenance.and_then(Provenance::get_alloc_id) {
1012                 Some(alloc_id) => {
1013                     write!(fmt, "by ref {:?}: {:?}", mplace.ptr, self.ecx.dump_alloc(alloc_id))
1014                 }
1015                 ptr => write!(fmt, " integral by ref: {:?}", ptr),
1016             },
1017         }
1018     }
1019 }