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