Skip to main content

rapx/vm/
state.rs

1//! Supporting symbolic VM state types and operations.
2//!
3//! Symbolic values, memory allocations, and operations on [`VmExecutor`] live
4//! here; the core state and its constructor are defined in the parent module.
5
6use crate::def_ids::type_ids;
7use crate::util::mir_utils;
8use rustc_abi::VariantIdx;
9use rustc_hir::def_id::DefId;
10#[cfg(rapx_const_ext)]
11use rustc_middle::ty::consts::ConstExt;
12use rustc_middle::{
13    mir::{Body, ConstValue, Local, Operand, Place, ProjectionElem},
14    ty::{Region, Ty, TyKind, TypingEnv},
15};
16use rustc_span::Span;
17use z3::{
18    SatResult, Solver,
19    ast::{Array, Ast, Bool, Dynamic, Int},
20};
21
22use crate::compat::{FxHashMap, FxHashSet};
23pub(crate) use super::VmExecutor;
24use crate::util::def_use::PlaceKey;
25
26pub(crate) const REPEATED_ARRAY_ELEMENT: usize = usize::MAX;
27
28/// Unique identifier for a heap or stack allocation.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub(crate) struct AllocId(pub usize);
31
32/// Memory operations observed while executing a MIR path.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub(crate) enum MemoryEventKind {
35    Drop,
36    Use,
37}
38
39#[derive(Clone, Copy, Debug)]
40pub(crate) struct MemoryEvent {
41    pub alloc_id: AllocId,
42    pub kind: MemoryEventKind,
43    /// Whether the allocation was already dead when this operation occurred.
44    pub was_dead: bool,
45    pub block: Option<usize>,
46    pub local: usize,
47    pub span: Span,
48}
49/// The structure of a pointer's byte offset, when it has one.
50///
51/// Each variant lets the verifier use a cheaper, more precise proof: `Field`
52/// carries the "field in-bounds" guarantee (`offset + size_of(field) <=
53/// size_of(container)`, e.g. `Option::as_slice`), and `Element(k)` tracks the
54/// element index so `InBound` checks `k + count <= slice_len` linearly instead
55/// of the non-linear byte form `(k+count)·S <= len·S` (undecidable in Z3 NIA
56/// for a generic `S`).
57#[derive(Clone, Debug)]
58pub(crate) enum OffsetKind<'z3> {
59    /// Compile-time field offset (`offset_of!`), including a first field at 0.
60    Field,
61    /// Element index and byte stride from pointer arithmetic. The byte offset
62    /// is `index · stride`.
63    Element { index: Int<'z3>, stride: Int<'z3> },
64    /// A byte-strided or otherwise unclassifiable offset (`byte_add`).
65    Byte,
66}
67
68/// Pointer provenance: which allocation, at what byte offset, and (when known)
69/// what structure that offset has.
70#[derive(Clone, Debug)]
71pub(crate) struct Provenance<'z3> {
72    /// The allocation this pointer derives from.
73    pub alloc_id: AllocId,
74    /// Byte offset from the allocation base; zero for a base pointer.
75    pub offset: Int<'z3>,
76    /// Known structure of the offset; `None` denotes an unclassified base offset.
77    pub offset_kind: Option<OffsetKind<'z3>>,
78}
79
80/// Value-level facts about a single symbolic value (nullness, alignment,
81/// bounds, and whether it has been written).  These travel *with* the value — a
82/// [`VmValue`] leaves its allocation when passed as an operand or stashed in
83/// `InlineCtx::deferred_field_writes` — so they live on the value, not the
84/// allocation.  The allocation-level counterpart to `init` is
85/// [`ContentFacts::initialized`], kept in sync by [`VmExecutor::mark_initialized`].
86///
87/// `PartialEq`/`Eq` are deliberately *not* derived: `align_n` is a Z3 AST
88/// whose equality is structural (`Z3_is_eq_ast`), not semantic, so comparing
89/// two `ValueFacts` would silently report semantically-equal values as
90/// unequal.
91#[derive(Clone, Debug, Default)]
92pub(crate) struct ValueFacts<'z3> {
93    pub non_null: bool,
94    pub dangling: bool,
95    pub init: bool,
96    pub in_bounds: bool,
97    /// Known divisor `n` for which `z3_term % n == 0`, possibly symbolic.
98    pub align_n: Option<Int<'z3>>,
99    /// Identity of an ownership transfer carried by this pointer and its copies.
100    pub ownership_transfer: Option<usize>,
101}
102
103/// A symbolic value tracked by the VM.
104///
105/// # Semantics of `z3_term`
106///
107/// - For pointer/reference types (`&T`, `*const T`, `*mut T`, `Box<T>`, etc.):
108///   `z3_term` represents the **address** in the VM's logical address space.
109/// - For scalar types (integers, `bool`, `char`): `z3_term` represents the **value**.
110/// - For aggregate types (struct, tuple, enum): `z3_term` is the base address of
111///   the stack allocation backing the aggregate.
112///
113/// When `provenance` is `Some`, the following relationship holds and is
114/// asserted into the solver at check time:
115///   `z3_term == alloc[provenance.alloc_id].base + provenance.offset`
116#[derive(Clone, Debug)]
117pub(crate) struct VmValue<'z3, 'tcx> {
118    /// Symbolic address or scalar value, according to `ty`.
119    pub z3_term: Int<'z3>,
120    pub ty: Ty<'tcx>,
121    /// Allocation origin and offset, when this is a pointer.
122    pub provenance: Option<Provenance<'z3>>,
123    pub facts: ValueFacts<'z3>,
124    /// Semantic origin used by guard and arithmetic reasoning.
125    pub source: ValueSource<'z3>,
126}
127
128impl<'z3, 'tcx> VmValue<'z3, 'tcx> {
129    pub(crate) fn new(term: Int<'z3>, ty: Ty<'tcx>) -> Self {
130        VmValue {
131            z3_term: term,
132            ty,
133            provenance: None,
134            facts: ValueFacts::default(),
135            source: ValueSource::None,
136        }
137    }
138
139    /// Convenience: extract the `AllocId` from provenance, if any.
140    pub(crate) fn provenance_alloc_id(&self) -> Option<AllocId> {
141        self.provenance.as_ref().map(|p| p.alloc_id)
142    }
143
144    /// Symbolic enum discriminant, if known.
145    pub(crate) fn discriminant(&self) -> Option<&Int<'z3>> {
146        match &self.source {
147            ValueSource::KnownDiscriminant(d) => Some(d),
148            _ => None,
149        }
150    }
151
152    /// Direct boolean condition of a comparison result, if any.
153    pub(crate) fn bool_cond(&self) -> Option<&Bool<'z3>> {
154        match &self.source {
155            ValueSource::Comparison { cond, .. } => Some(cond),
156            _ => None,
157        }
158    }
159
160    /// Whether this scalar is a compile-time `offset_of!` field offset.
161    pub(crate) fn is_field_offset(&self) -> bool {
162        matches!(self.source, ValueSource::FieldOffset)
163    }
164
165    /// Whether this value is a pointer (carries provenance).
166    pub(crate) fn is_pointer(&self) -> bool {
167        self.provenance.is_some()
168    }
169}
170
171/// The shape of an allocation: a single object, a slice/array buffer, or an
172/// external raw-pointer parameter.  `element_ty` (typed vs untyped) and the
173/// `parent` sub-view edge stay separate fields.
174#[derive(Clone, Debug)]
175pub(crate) enum AllocKind<'z3> {
176    /// A single object: a `Box<T>` heap object, a struct, a scalar, or an
177    /// untyped raw buffer.
178    Object,
179    /// A slice/array buffer with a known element count.
180    Slice {
181        len: Int<'z3>,
182    },
183    /// An external raw-pointer parameter. `size` is an unconstrained symbolic
184    /// term (the caller may pass any allocation); nullability is *not* stored
185    /// here — it is tracked via the pointer term (`term == 0`) path conditions.
186    External,
187    ExternalSlice {
188        len: Int<'z3>,
189    },
190}
191
192/// The element type of an allocation's contents, either a concrete [`Ty`] or
193/// symbolic (`Generic`).
194///
195/// `Typed` carries a concrete `Ty` — the element type of a slice, the object
196/// type of a `Box<T>`/struct, or `u8` for a raw byte buffer — while `Generic`
197/// marks a symbolic element type whose concrete `Ty` cannot be determined
198/// (e.g. `from_raw_parts::<T>`; its `size` uses the shared symbolic `sizeof_T`
199/// and its length must be materialized via `set_slice_len`).
200#[derive(Clone, Debug)]
201pub(crate) enum ElementTy<'tcx> {
202    Typed(Ty<'tcx>),
203    Generic,
204}
205
206impl<'tcx> ElementTy<'tcx> {
207    /// The concrete type, if known.
208    pub(crate) fn as_ty(&self) -> Option<Ty<'tcx>> {
209        match self {
210            ElementTy::Typed(t) => Some(*t),
211            ElementTy::Generic => None,
212        }
213    }
214
215    /// Whether the element type is symbolic/unknown (no concrete `Ty`).
216    pub(crate) fn is_generic(&self) -> bool {
217        matches!(self, ElementTy::Generic)
218    }
219}
220
221impl<'tcx> From<Option<Ty<'tcx>>> for ElementTy<'tcx> {
222    fn from(o: Option<Ty<'tcx>>) -> Self {
223        match o {
224            Some(t) => ElementTy::Typed(t),
225            None => ElementTy::Generic,
226        }
227    }
228}
229
230/// Uniform facts about the *pointer elements* of a container, established by
231/// `x.iter()` for_each invariants.
232///
233/// Each fact is a property every element pointer satisfies. The facts are
234/// anchored to the container allocation, separate from its storage layout.
235#[derive(Clone, Debug, Default)]
236pub(crate) struct ForEachFacts<'z3, 'tcx> {
237    /// `Typed(iter(), T)`: every element pointer points at a valid `T`.
238    pub target_ty: Option<Ty<'tcx>>,
239    /// `Align(iter(), T)`: every element pointer is aligned to `align_of(T)`.
240    pub aligned_ty: Option<Ty<'tcx>>,
241    /// `Allocated(iter(), T, n)`: every element pointer backs `>= n` `T`
242    /// elements (`n` may be symbolic).
243    pub allocated: Option<(Ty<'tcx>, Int<'z3>)>,
244    /// `Owning(iter())` is trusted; alias validation is handled separately.
245    pub owning: bool,
246}
247
248/// Per-allocation *lifecycle* facts (`dead`/`liveness`/`for_each`), kept apart
249/// from the allocation's shape metadata and `parent` edge so identity/layout
250/// and facts are separated at the type level.  The *content* facts
251/// (readability, C-string/UTF-8 trust) live on [`ContentFacts`] instead.
252#[derive(Clone, Debug, Default)]
253pub(crate) struct AllocFacts<'z3, 'tcx> {
254    /// Whether the allocation has been freed (StorageDead / Drop).
255    pub dead: bool,
256    /// Whether an unresolved `Fn*` call may have freed this allocation.
257    pub function_var_may_drop: bool,
258    /// A destructor may have freed this allocation.
259    pub drop_may_free: bool,
260    /// Pointer term licensed by an `Owning` precondition.
261    pub owning: Option<Int<'z3>>,
262    /// Whether this allocation was created in the analyzed function.
263    pub locally_allocated: bool,
264    /// Assumed live region for external allocations; `None` grants no lifetime.
265    pub liveness: Option<Region<'tcx>>,
266    /// Facts shared by all pointer elements of this allocation.
267    pub for_each: ForEachFacts<'z3, 'tcx>,
268    /// `(address, type, length)` spans licensed by `InBound` contracts. The
269    /// length is the pointer's length for a slice or `str`, whose size depends
270    /// on it, and `None` for other types.
271    pub bounded_spans: Vec<(Int<'z3>, Ty<'tcx>, Option<Int<'z3>>)>,
272    /// Byte ranges established by explicit allocation/bounds contracts.
273    /// Each entry is (start address, byte count), not a whole-allocation extent.
274    pub bounded_ranges: Vec<(Int<'z3>, Int<'z3>)>,
275}
276
277/// Per-allocation *content* facts: whether the allocation's contents are
278/// readable (initialized), whether they were asserted to be a valid C string /
279/// UTF-8, and whether they were licensed for `SplitTransmute` re-interpretation.
280/// These describe the stored bytes/values, so they live on [`MemoryContent`]
281/// next to that data, rather than on [`AllocFacts`] (lifecycle).
282#[derive(Clone, Debug, Default)]
283pub(crate) struct ContentFacts<'tcx> {
284    /// Whether the allocation contains a readable value.
285    pub initialized: bool,
286    /// Whether some explored branch may leave this allocation uninitialized.
287    pub may_be_uninit: bool,
288    /// Whether the inner `T` is still uninitialized after `MaybeUninit::uninit`.
289    pub inner_uninit: bool,
290    /// Type of a complete initialized write at offset zero; cleared by invalidating writes.
291    pub written_pointee_ty: Option<Ty<'tcx>>,
292    /// Trusted `ValidCStr` contract or invariant evidence.
293    pub cstr_trusted: bool,
294    /// Trusted `ValidString` contract evidence.
295    pub utf8_trusted: bool,
296    /// Destination element type licensed by `SplitTransmute`; `None` grants none.
297    pub split_transmute_to: Option<Ty<'tcx>>,
298}
299
300/// A memory allocation: a stack local, a heap object (`Box`/`Vec`), or an
301/// external raw-pointer placeholder.
302///
303/// The allocation is stored in a [`MemoryUnit`] at index `AllocId.0` (an
304/// `AllocId` is a monotonic counter that doubles as the vector index).
305#[derive(Clone, Debug)]
306pub(crate) struct Allocation<'z3, 'tcx> {
307    /// Symbolic base address.
308    pub base: Int<'z3>,
309    /// Size in bytes, possibly symbolic.
310    pub size: Int<'z3>,
311    /// Alignment in bytes, possibly symbolic for a generic type.
312    pub align: Int<'z3>,
313    /// Element type of the stored object or slice.
314    pub element_ty: ElementTy<'tcx>,
315    /// Object, slice, or external allocation shape.
316    pub kind: AllocKind<'z3>,
317    /// Allocation lifecycle and ownership facts.
318    pub facts: AllocFacts<'z3, 'tcx>,
319    /// Source allocation of a view; followed to find its aliasing root.
320    pub parent: Option<AllocId>,
321}
322
323impl<'z3, 'tcx> Allocation<'z3, 'tcx> {
324    /// Construct a fresh allocation with all live/dead/invariant flags in
325    /// their initial state.
326    pub(crate) fn new(
327        base: Int<'z3>,
328        size: Int<'z3>,
329        align: Int<'z3>,
330        element_ty: Option<Ty<'tcx>>,
331        kind: AllocKind<'z3>,
332    ) -> Self {
333        Allocation {
334            base,
335            size,
336            align,
337            element_ty: element_ty.into(),
338            kind,
339            facts: AllocFacts::default(),
340            parent: None,
341        }
342    }
343
344    /// Whether this allocation models an external raw-pointer parameter.
345    pub(crate) fn is_external(&self) -> bool {
346        matches!(
347            self.kind,
348            AllocKind::External | AllocKind::ExternalSlice { .. }
349        )
350    }
351
352    /// Legacy external-allocation placeholder, not evidence of a byte extent.
353    pub(crate) fn has_unbounded_size(&self) -> bool {
354        self.is_external() && self.size.simplify().as_u64() == Some(i64::MAX as u64)
355    }
356
357    /// The slice/array element count, if this allocation is slice data.
358    ///
359    /// Invariant: `size == len * sizeof(element_ty)` is maintained by the
360    /// callers that call [`Self::set_slice_len`] (they compute `size` from the
361    /// same `len` and push the equality as a path condition); it is *not*
362    /// enforced here. `slice_len_from_value` falls back to `size / elem_size`
363    /// when the length was never materialized.
364    pub(crate) fn slice_len(&self) -> Option<&Int<'z3>> {
365        match &self.kind {
366            AllocKind::Slice { len } | AllocKind::ExternalSlice { len } => Some(len),
367            _ => None,
368        }
369    }
370
371    /// Mark this allocation as slice data with the given element count.
372    /// Callers must keep `size == len * sizeof(element_ty)` consistent.
373    pub(crate) fn set_slice_len(&mut self, len: Int<'z3>) {
374        self.kind = if self.is_external() {
375            AllocKind::ExternalSlice { len }
376        } else {
377            AllocKind::Slice { len }
378        };
379    }
380}
381
382/// Scratch state shared by recursive inlining and path replay.
383/// Recursive inlining saves caller bindings on the Rust call stack; path replay
384/// saves them with the caller frame in [`SavedCallerFrame`].
385///
386/// # Deferring `&mut` writes across the inline frame
387///
388/// While the callee runs, the caller's `local_alloc` (the name → allocation
389/// binding) is parked in the saved [`FrameState`], so a write through a `&mut`
390/// argument cannot resolve the caller referent local by address and land in its
391/// field values immediately.  `arg_referents` pre-resolves (before `enter_frame`)
392/// which caller local each `&mut` argument points at, and `deferred_field_writes`
393/// collects the writes to replay once the caller is restored:
394///
395/// ```text
396/// struct Foo { field: i32 }
397/// fn bar(foo: &mut Foo) { foo.field = 1; }   // inlined callee
398/// fn main() {
399///     let mut x = Foo { field: 0 };
400///     bar(&mut x);                            // inline `bar`
401/// }
402/// ```
403///
404/// 1. Enter `bar`: `enter_frame` parks `main`'s local_alloc; `arg_referents[0] = x`.
405/// 2. Run `bar`: `foo.field = 1` (`(*foo).field`) can no longer resolve `x` by
406///    address (the caller's address map is gone), so it pushes `(x, [0], 1)`.
407/// 3. Exit `bar`: `restore_frame` brings `main`'s local_alloc back, then the deferred
408///    write is replayed, giving `x.field == 1`.
409#[derive(Default, Clone)]
410pub(crate) struct InlineCtx<'z3, 'tcx> {
411    /// Recursive inlining depth, bounded by `MAX_INLINE_DEPTH`.
412    pub inline_depth: usize,
413    pub symbolic_generic_const_inline: bool,
414    /// Terms from depth-limited calls; dependent checks become `Unknown`.
415    pub inline_truncated_terms: FxHashSet<Int<'z3>>,
416    pub inline_branch_terms: FxHashSet<Int<'z3>>,
417    pub pending_states: Vec<Box<VmExecutor<'z3, 'tcx>>>,
418    pub opaque_intrinsic_terms: FxHashSet<Int<'z3>>,
419    /// Caller referent local for each inlined callee argument.
420    pub arg_referents: Vec<Option<Local>>,
421    /// `(caller local, field path, value)` writes replayed after frame restoration.
422    pub deferred_field_writes: Vec<(Local, Vec<usize>, VmValue<'z3, 'tcx>)>,
423}
424
425/// The extra semantics attached to a value, beyond its term/type/provenance.
426///
427/// A single value carries at most one of these: it is either a plain value, an
428/// `offset_of!` field offset, an enum construction marker or discriminant, a comparison
429/// result, or a non-comparison binary-op result.  The operands/operator are
430/// used for guard inference (tracing a switch/assert guard back to the pointer
431/// it null-checks/alignment-checks) and division-axiom injection (following
432/// dataflow edges to reach `Div`/`Rem` results).
433#[derive(Clone, Debug)]
434pub(crate) enum ValueSource<'z3> {
435    /// No extra semantics.
436    None,
437    /// A literal bound to an inlined callee parameter at this call site.
438    CallsiteConst,
439    /// The stored scalar value of a shared primitive reference parameter.
440    SharedScalarReferent,
441    /// Bytes carried by a constant byte-array reference through generic calls.
442    ConstBytes(Vec<u8>),
443    /// Length metadata carried by a slice pointer or reference.
444    SliceLen(Int<'z3>),
445    /// A compile-time `offset_of!` field offset.
446    FieldOffset,
447    FieldBorrow {
448        base: Local,
449        fields: Vec<usize>,
450    },
451    /// A known enum discriminant.
452    KnownDiscriminant(Int<'z3>),
453    /// Variant whose payload fields are being written before `SetDiscriminant`.
454    PendingEnumVariant(Int<'z3>),
455    /// A comparison result (`Eq`/`Ne`/`Le`/`Lt`/`Ge`/`Gt`): the operands and
456    /// the direct boolean condition (`offset <= len`) carried alongside the
457    /// ite-encoded term.
458    Comparison {
459        lhs: Option<PlaceKey>,
460        rhs: Option<PlaceKey>,
461        op: rustc_middle::mir::BinOp,
462        cond: Bool<'z3>,
463    },
464    /// A non-comparison binary-op result (`Add`/`Sub`/…/`Div`/`Rem`): the
465    /// operands and operator.
466    BinaryOp {
467        lhs: Option<PlaceKey>,
468        rhs: Option<PlaceKey>,
469        op: rustc_middle::mir::BinOp,
470    },
471}
472
473impl<'z3> ValueSource<'z3> {
474    /// The `(lhs, rhs, op)` of a binary-op/comparison result, if this value is
475    /// one.
476    pub(crate) fn operands(
477        &self,
478    ) -> Option<(
479        &Option<PlaceKey>,
480        &Option<PlaceKey>,
481        rustc_middle::mir::BinOp,
482    )> {
483        match self {
484            ValueSource::Comparison { lhs, rhs, op, .. } => Some((lhs, rhs, *op)),
485            ValueSource::BinaryOp { lhs, rhs, op } => Some((lhs, rhs, *op)),
486            _ => None,
487        }
488    }
489
490    /// Just the field-offset part of this source: `FieldOffset` if it is one,
491    /// otherwise `None`.
492    pub(crate) fn field_offset_only(&self) -> ValueSource<'z3> {
493        match self {
494            ValueSource::FieldOffset => ValueSource::FieldOffset,
495            _ => ValueSource::None,
496        }
497    }
498}
499
500/// A single allocation: its shape metadata ([`Allocation`]) plus its contents
501/// ([`MemoryContent`]).  Splitting the two keeps the identity/layout facts apart
502/// from the mutable memory the values live in, while colocating them in one
503/// unit so no parallel table can drift out of sync.  Facts live in three
504/// anchored layers — lifecycle ([`AllocFacts`]), content ([`ContentFacts`]),
505/// and value ([`ValueFacts`] on each [`VmValue`]) — see each type's doc.
506#[derive(Clone)]
507pub(crate) struct MemoryUnit<'z3, 'tcx> {
508    pub(crate) allocation: Allocation<'z3, 'tcx>,
509    pub(crate) content: MemoryContent<'z3, 'tcx>,
510}
511
512/// The per-allocation byte and typed-value layers. Typed values use a view type
513/// so fields from different casts do not collide. Unwritten bytes read as the
514/// `UNINIT` sentinel.
515#[derive(Default, Clone)]
516pub(crate) struct MemoryContent<'z3, 'tcx> {
517    /// Symbolic byte array; absent until the first byte write.
518    pub(crate) byte_array: Option<Array<'z3>>,
519    /// Concrete written byte offsets; symbolic writes update only `byte_array`.
520    pub(crate) byte_written: FxHashSet<usize>,
521    /// Typed values keyed by view type and field path; `[]` is the whole value.
522    pub(crate) values: FxHashMap<(Ty<'tcx>, Vec<usize>), VmValue<'z3, 'tcx>>,
523    /// `(address, type)` facts established by `Typed` contracts.
524    pub(crate) typed_facts: FxHashSet<(Int<'z3>, Ty<'tcx>)>,
525    pub(crate) indexed_elements: Vec<(Int<'z3>, VmValue<'z3, 'tcx>)>,
526    pub(crate) indexed_elements_modified: bool,
527    pub(crate) copied_prefix: Option<(Ty<'tcx>, Int<'z3>)>,
528    pub(crate) facts: ContentFacts<'tcx>,
529}
530
531impl MemoryContent<'_, '_> {
532    pub(crate) fn clear_byte_writes(&mut self) {
533        self.byte_array = None;
534        self.byte_written.clear();
535    }
536}
537
538/// Accumulated solver state for the current path.
539///
540/// `assertions` is the assertion stream fed to Z3; `term_caches` holds the
541/// per-phenomenon term-provenance caches that keep expressions compact and
542/// linear.  Everything is path-scoped and monotonic: it accumulates as the VM
543/// steps and is never reset within a path (or across inlined frames).
544#[derive(Default, Clone)]
545pub(crate) struct Constraints<'z3, 'tcx> {
546    /// Path conditions, call preconditions, and layout facts asserted to Z3.
547    pub(crate) assertions: Vec<Bool<'z3>>,
548    /// Path-scoped term provenance caches used to keep expressions compact.
549    pub(crate) term_caches: TermCaches<'z3, 'tcx>,
550}
551
552/// Term-provenance caches, one per phenomenon the VM must shape by hand.
553///
554/// Z3's nonlinear integer solver (NIA) cannot rewrite degree-3 products or
555/// deeply-nested pointer chains, so the VM records the *semantic meaning* of a
556/// symbol (what it divides, which iterator it indexes, …) and uses that
557/// provenance later to emit a compact, degree-≤2 term instead.  Each cache is
558/// independent — they share only the path-scoped, monotonic lifetime.
559#[derive(Default, Clone)]
560pub(crate) struct TermCaches<'z3, 'tcx> {
561    /// Shared symbolic `sizeof_T` term for each generic type.
562    pub(crate) sizes: FxHashMap<Ty<'tcx>, Int<'z3>>,
563    /// Positive size terms already proved on this path. Assertions only accumulate.
564    pub(crate) non_zst: FxHashSet<Int<'z3>>,
565    /// Shared symbolic `align_T` term for each generic type.
566    pub(crate) aligns: FxHashMap<Ty<'tcx>, Int<'z3>>,
567    /// Bitwise `Not` terms used to recognize alignment masks.
568    pub(crate) not_mask_terms: FxHashSet<Int<'z3>>,
569    /// Exact-division quotient mapped to its dividend for later bound proofs.
570    pub(crate) exact_div_roots: FxHashMap<Int<'z3>, Int<'z3>>,
571    /// Non-exact quotient mapped to its dividend and divisor.
572    pub(crate) div_roots: FxHashMap<Int<'z3>, (Int<'z3>, Int<'z3>)>,
573    /// Iterator offset and optional length, keyed by backing buffer and pointer.
574    pub(crate) iter_ptr_offset:
575        FxHashMap<(AllocId, Int<'z3>), (AllocId, Int<'z3>, Option<Int<'z3>>)>,
576    /// Shared byte-array sentinel outside the `u8` range.
577    pub(crate) uninit_byte: Option<Int<'z3>>,
578}
579
580/// The frame-scoped subset of [`VmExecutor`]: the name → allocation binding keyed
581/// by MIR `Local`, which the callee reuses, so it must be swapped out for the
582/// duration of an inlined callee and swapped back afterwards.
583///
584/// # Agent Rules
585/// Do not add new fields without human approval.
586#[derive(Clone)]
587pub(crate) struct FrameState<'tcx> {
588    /// Function executed by this frame.
589    pub(crate) current_def_id: DefId,
590    /// Optimized MIR with this frame's selected generic arguments substituted, if available.
591    pub(crate) instantiated_body: Option<&'tcx Body<'tcx>>,
592    /// Stack allocation backing each MIR local and its field values.
593    pub(crate) local_alloc: FxHashMap<Local, AllocId>,
594}
595
596/// Caller state parked during a path-replay call.
597#[derive(Clone)]
598pub(crate) struct SavedCallerFrame<'z3, 'tcx> {
599    /// Caller MIR frame restored when the inlined callee returns.
600    pub(crate) frame: FrameState<'tcx>,
601    /// Caller locals used to bind trait-method `ensures` after inlining.
602    pub(crate) postcondition_args: Vec<Option<Local>>,
603    /// Caller frame's argument referents restored on return.
604    pub(crate) arg_referents: Vec<Option<Local>>,
605    /// Caller frame's pending field writes restored on return.
606    pub(crate) deferred_writes: Vec<(Local, Vec<usize>, VmValue<'z3, 'tcx>)>,
607}
608
609/// A transferable ownership share. Copies of its pointer use the same entry.
610#[derive(Clone)]
611pub(crate) struct OwnershipTransfer {
612    alloc_id: AllocId,
613    owner: DefId,
614    available: usize,
615}
616
617impl<'z3, 'tcx> VmExecutor<'z3, 'tcx> {
618    pub(crate) fn ownership_share(&self, value: &VmValue<'z3, 'tcx>, owner: DefId) -> Option<usize> {
619        let transfer = self.path_state.ownership_transfers.get(value.facts.ownership_transfer?)?;
620        (transfer.owner == owner
621            && value
622                .provenance_alloc_id()
623                .is_some_and(|id| self.root_alloc(id) == transfer.alloc_id))
624        .then_some(transfer.available)
625    }
626
627    pub(crate) fn has_available_transfer(&self, alloc_id: AllocId) -> bool {
628        let root = self.root_alloc(alloc_id);
629        self.path_state.ownership_transfers
630            .iter()
631            .any(|transfer| transfer.alloc_id == root && transfer.available > 0)
632    }
633
634    pub(crate) fn begin_ownership_transfer(&mut self, local: Local, owner: DefId) {
635        let Some(alloc_id) = self.local_value(local).and_then(|value| value.provenance_alloc_id()) else {
636            return;
637        };
638        let id = self.path_state.ownership_transfers.len();
639        self.path_state.ownership_transfers.push(OwnershipTransfer {
640            alloc_id: self.root_alloc(alloc_id),
641            owner,
642            available: 1,
643        });
644        if let Some(mut value) = self.local_value(local).cloned() {
645            value.facts.ownership_transfer = Some(id);
646            self.set_local(local, value);
647        }
648    }
649
650    pub(crate) fn grant_ownership_share(&mut self, value: &VmValue<'z3, 'tcx>, owner: DefId) {
651        if self.ownership_share(value, owner).is_some()
652            && let Some(id) = value.facts.ownership_transfer
653        {
654            self.path_state.ownership_transfers[id].available += 1;
655        }
656    }
657
658    pub(crate) fn consume_ownership_share(
659        &mut self,
660        value: &VmValue<'z3, 'tcx>,
661        owner: DefId,
662        may_free: bool,
663    ) {
664        if self.ownership_share(value, owner).is_some()
665            && let Some(id) = value.facts.ownership_transfer
666        {
667            self.path_state.ownership_transfers[id].available =
668                self.path_state.ownership_transfers[id].available.saturating_sub(1);
669        }
670        if may_free && let Some(alloc_id) = value.provenance_alloc_id() {
671            self.alloc_mut(self.root_alloc(alloc_id)).facts.drop_may_free = true;
672        }
673    }
674
675    pub(crate) fn record_memory_drop(&mut self, alloc_id: AllocId, local: Local) {
676        if let Some(events) = &self.path_state.memory_events {
677            events.borrow_mut().push(MemoryEvent {
678                alloc_id,
679                kind: MemoryEventKind::Drop,
680                was_dead: self.alloc(alloc_id).facts.dead,
681                block: self.path_state.diagnostics.active_mir.as_ref().map(|location| location.block),
682                local: local.as_usize(),
683                span: self.path_state
684                    .diagnostics.active_mir
685                    .as_ref()
686                    .map(|location| location.span)
687                    .unwrap_or(rustc_span::DUMMY_SP),
688            });
689        }
690        self.alloc_mut(alloc_id).facts.dead = true;
691    }
692
693    pub(crate) fn record_memory_use(&self, alloc_id: AllocId, local: Local) {
694        if let Some(events) = &self.path_state.memory_events {
695            events.borrow_mut().push(MemoryEvent {
696                alloc_id,
697                kind: MemoryEventKind::Use,
698                was_dead: self.alloc(alloc_id).facts.dead,
699                block: self.path_state.diagnostics.active_mir.as_ref().map(|location| location.block),
700                local: local.as_usize(),
701                span: self.path_state
702                    .diagnostics.active_mir
703                    .as_ref()
704                    .map(|location| location.span)
705                    .unwrap_or(rustc_span::DUMMY_SP),
706            });
707        }
708    }
709
710    pub(crate) fn scalar_bits_term(&self, ty: Ty<'tcx>, bits: u128) -> Option<Int<'z3>> {
711        let bytes = self.size_of_ty(ty);
712        if bytes == 0 || bytes > 16 {
713            return None;
714        }
715        if bytes == 16 {
716            let two_64 = Int::add(
717                self.z3_ctx,
718                &[
719                    &Int::from_u64(self.z3_ctx, u64::MAX),
720                    &Int::from_u64(self.z3_ctx, 1),
721                ],
722            );
723            let unsigned = self.u128_term(bits);
724            return if matches!(ty.kind(), TyKind::Int(_)) && bits >> 127 != 0 {
725                let two_128 = Int::mul(self.z3_ctx, &[&two_64, &two_64]);
726                Some(Int::sub(self.z3_ctx, &[&unsigned, &two_128]))
727            } else {
728                Some(unsigned)
729            };
730        }
731        let width = bytes * 8;
732        if matches!(ty.kind(), TyKind::Int(_)) {
733            let shift = 64 - width;
734            let signed = ((bits as u64) << shift) as i64 >> shift;
735            Some(Int::from_i64(self.z3_ctx, signed))
736        } else {
737            u64::try_from(bits)
738                .ok()
739                .map(|unsigned| Int::from_u64(self.z3_ctx, unsigned))
740        }
741    }
742
743    pub(crate) fn u128_term(&self, value: u128) -> Int<'z3> {
744        let low = Int::from_u64(self.z3_ctx, value as u64);
745        if value <= u64::MAX as u128 {
746            return low;
747        }
748        let high = Int::from_u64(self.z3_ctx, (value >> 64) as u64);
749        let two_64 = Int::add(
750            self.z3_ctx,
751            &[
752                &Int::from_u64(self.z3_ctx, u64::MAX),
753                &Int::from_u64(self.z3_ctx, 1),
754            ],
755        );
756        Int::add(
757            self.z3_ctx,
758            &[&Int::mul(self.z3_ctx, &[&high, &two_64]), &low],
759        )
760    }
761
762    pub(crate) fn enum_discriminant_term(
763        &self,
764        ty: Ty<'tcx>,
765        variant: VariantIdx,
766    ) -> Option<Int<'z3>> {
767        let TyKind::Adt(adt, _) = ty.kind() else {
768            return None;
769        };
770        if !adt.is_enum() {
771            return None;
772        }
773        let discr = adt.discriminant_for_variant(self.tcx, variant);
774        self.scalar_bits_term(discr.ty, discr.val)
775    }
776
777    /// MIR for the current frame, preferring its selected generic instantiation.
778    pub(crate) fn body(&self) -> &'tcx Body<'tcx> {
779        self.body_for(self.path_state.current_frame.current_def_id)
780    }
781
782    pub(crate) fn body_for(&self, def_id: DefId) -> &'tcx Body<'tcx> {
783        if def_id == self.path_state.current_frame.current_def_id
784            && let Some(body) = self.path_state.current_frame.instantiated_body
785        {
786            body
787        } else if def_id == self.target_def_id
788            && let Some(body) = &self.instantiated_target_body
789        {
790            body
791        } else {
792            self.tcx.optimized_mir(def_id)
793        }
794    }
795
796    /// MIR for the verification target, preferring its selected generic instantiation.
797    pub(crate) fn target_body(&self) -> &rustc_middle::mir::Body<'tcx> {
798        self.instantiated_target_body
799            .unwrap_or_else(|| self.tcx.optimized_mir(self.target_def_id))
800    }
801
802    pub(crate) fn record_unsupported(&mut self, operation: &str) {
803        let location = self.path_state.diagnostics.location_label(self.tcx);
804        self.path_state.diagnostics.record_unsupported(
805            location.as_deref(),
806            operation,
807        );
808    }
809
810    pub(crate) fn record_unsupported_effect(&mut self, effect: &str) {
811        let location = self.path_state.diagnostics.location_label(self.tcx);
812        self.path_state.diagnostics.record_unsupported_effect(
813            location.as_deref(),
814            effect,
815        );
816    }
817
818    pub(crate) fn record_missing_mir(&mut self, callee: DefId) {
819        let location = self.path_state.diagnostics.location_label(self.tcx);
820        self.path_state.diagnostics.record_missing_mir(
821            location.as_deref(),
822            &self.tcx.def_path_str(callee),
823        );
824    }
825
826    pub(crate) fn record_opaque_control_flow(&mut self, operation: &str) {
827        let location = self.path_state.diagnostics.location_label(self.tcx);
828        self.path_state.diagnostics.record_opaque_control_flow(
829            location.as_deref(),
830            operation,
831        );
832    }
833
834    /// Capture the frame-scoped state before switching to an inlined callee.
835    ///
836    /// This is the single source of truth for *what* is frame-scoped: the whole
837    /// [`FrameState`] (function identity, local bindings, and operand sources).
838    /// Both inline mechanisms (`handle_callee_entry` in path replay and
839    /// `exec_inline_call`) call this, so they can no longer drift apart.
840    pub(crate) fn enter_frame(
841        &mut self,
842        callee: DefId,
843        body: Option<&'tcx Body<'tcx>>,
844    ) -> FrameState<'tcx> {
845        std::mem::replace(
846            &mut self.path_state.current_frame,
847            FrameState {
848                current_def_id: callee,
849                instantiated_body: body,
850                local_alloc: FxHashMap::default(),
851            },
852        )
853    }
854
855    /// Restore the frame-scoped state after an inlined callee returns.
856    pub(crate) fn restore_frame(&mut self, frame: FrameState<'tcx>) {
857        self.path_state.current_frame = frame;
858    }
859
860    /// Look up the whole value bound to a MIR local (its `path == []` slot in
861    /// the allocation backing the local).
862    pub(crate) fn local_value(&self, local: Local) -> Option<&VmValue<'z3, 'tcx>> {
863        let alloc_id = *self.path_state.current_frame.local_alloc.get(&local)?;
864        let view_ty = self.body().local_decls[local].ty;
865        self.load_value(alloc_id, view_ty, &[])
866    }
867
868    pub(crate) fn term_involves(terms: &FxHashSet<Int<'z3>>, term: &Int<'z3>) -> bool {
869        let mut pending = vec![Dynamic::from_ast(term)];
870        let mut seen = FxHashSet::default();
871        while let Some(ast) = pending.pop() {
872            if !seen.insert(ast.clone()) {
873                continue;
874            }
875            if ast.as_int().is_some_and(|value| terms.contains(&value)) {
876                return true;
877            }
878            pending.extend(ast.children());
879        }
880        false
881    }
882
883    /// Bind a whole value to a MIR local (store it at `path == []` in the
884    /// allocation backing the local, allocating that stack slot on demand).
885    pub(crate) fn set_local(&mut self, local: Local, mut value: VmValue<'z3, 'tcx>) {
886        self.ensure_local_allocation(local);
887        let alloc_id = self.path_state.current_frame.local_alloc[&local];
888        self.content_mut(alloc_id).facts.may_be_uninit = false;
889        let view_ty = self.body().local_decls[local].ty;
890        if matches!(view_ty.kind(), TyKind::Adt(def, _)
891            if type_ids::is_std_vec(def.did()))
892            && value.provenance.as_ref().is_none_or(|prov| {
893                let source = self.alloc(prov.alloc_id);
894                matches!(source.kind, AllocKind::Object)
895                    && matches!(source.element_ty.as_ty(), Some(ty)
896                        if matches!(ty.kind(), TyKind::Adt(source_def, _)
897                            if type_ids::is_std_vec(source_def.did())))
898            })
899        {
900            value.provenance = Some(Provenance {
901                alloc_id,
902                offset: Int::from_u64(self.z3_ctx, 0),
903                offset_kind: None,
904            });
905        }
906        if matches!(view_ty.kind(), TyKind::Adt(def, _)
907            if type_ids::is_maybe_uninit_type(def.did()))
908        {
909            self.clear_write_evidence(alloc_id);
910            self.content_mut(alloc_id).facts.inner_uninit = false;
911        }
912        self.store_value(alloc_id, view_ty, vec![], value);
913    }
914
915    pub(crate) fn invalidate_indexed_array(&mut self, local: Local) {
916        let view_ty = self.body().local_decls[local].ty;
917        let mut element_ty = view_ty;
918        let mut is_array = false;
919        while let rustc_middle::ty::TyKind::Array(inner, _) = element_ty.kind() {
920            element_ty = *inner;
921            is_array = true;
922        }
923        if is_array && let Some(&alloc_id) = self.path_state.current_frame.local_alloc.get(&local) {
924            let content = self.content_mut(alloc_id);
925            let was_tracked = content.indexed_elements_modified || !content.indexed_elements.is_empty();
926            content.indexed_elements.clear();
927            content.indexed_elements_modified = was_tracked;
928            content
929                .values
930                .retain(|(ty, path), _| *ty != view_ty || path.is_empty());
931        }
932    }
933
934    /// Mark a value as initialized (written), and sync its backing allocation's
935    /// [`ContentFacts::initialized`] fact.
936    ///
937    /// This is the single entry point that keeps the value-level
938    /// [`ValueFacts::init`] and the allocation-level [`ContentFacts::initialized`]
939    /// in sync; callers must set the pair through here rather than by hand so
940    /// the two facts cannot drift apart.
941    pub(crate) fn mark_initialized(&mut self, value: &mut VmValue<'z3, 'tcx>) {
942        value.facts.init = true;
943        if let Some(prov) = &value.provenance {
944            self.content_mut(prov.alloc_id).facts.initialized = true;
945        }
946    }
947
948    /// Get the symbolic address of a MIR local (its stack allocation's base).
949    pub(crate) fn local_address(&mut self, local: Local) -> Int<'z3> {
950        self.ensure_local_allocation(local);
951        let id = self.path_state.current_frame.local_alloc[&local];
952        self.path_state.mem_units[id.0].allocation.base.clone()
953    }
954
955    /// Allocate a fresh symbolic object and return its ID and base address.
956    pub(crate) fn allocate(
957        &mut self,
958        size: Int<'z3>,
959        align: Int<'z3>,
960        element_ty: Option<Ty<'tcx>>,
961    ) -> (AllocId, Int<'z3>) {
962        self.allocate_internal(size, align, element_ty, AllocKind::Object)
963    }
964
965    /// Allocate a fresh external allocation (for raw-pointer parameters).
966    /// External allocations may be null and have unlimited size.
967    pub(crate) fn allocate_external(
968        &mut self,
969        size: Int<'z3>,
970        align: Int<'z3>,
971        element_ty: Option<Ty<'tcx>>,
972    ) -> (AllocId, Int<'z3>) {
973        self.allocate_internal(size, align, element_ty, AllocKind::External)
974    }
975
976    /// Allocate a slice/array data allocation with a known (possibly symbolic)
977    /// element count. Computes `size = len * elem_size` and materializes `len`
978    /// in one step, so `size` and the slice length can never diverge (the
979    /// `size == len * elem_size` invariant is established here instead of being
980    /// re-derived by every caller).
981    pub(crate) fn allocate_slice(
982        &mut self,
983        len: Int<'z3>,
984        elem_size: Int<'z3>,
985        align: Int<'z3>,
986        element_ty: Option<Ty<'tcx>>,
987    ) -> (AllocId, Int<'z3>) {
988        let size = Int::mul(self.z3_ctx, &[&len, &elem_size]);
989        let (id, base) = self.allocate(size, align, element_ty);
990        self.alloc_mut(id).set_slice_len(len);
991        (id, base)
992    }
993
994    fn allocate_internal(
995        &mut self,
996        size: Int<'z3>,
997        align: Int<'z3>,
998        element_ty: Option<Ty<'tcx>>,
999        kind: AllocKind<'z3>,
1000    ) -> (AllocId, Int<'z3>) {
1001        let id = AllocId(self.path_state.mem_units.len());
1002        let base = {
1003            let name = format!(
1004                "{}_{}",
1005                if matches!(kind, AllocKind::External) {
1006                    "ext"
1007                } else {
1008                    "heap"
1009                },
1010                id.0
1011            );
1012            Int::new_const(self.z3_ctx, name.as_str())
1013        };
1014        let alloc = Allocation::new(base.clone(), size, align, element_ty, kind);
1015        self.path_state.mem_units.push(MemoryUnit {
1016            allocation: alloc,
1017            content: MemoryContent::default(),
1018        });
1019        (id, base)
1020    }
1021
1022    /// Indexed access to an allocation by its `AllocId` (the id is the index).
1023    pub(crate) fn alloc(&self, id: AllocId) -> &Allocation<'z3, 'tcx> {
1024        &self.path_state.mem_units[id.0].allocation
1025    }
1026
1027    /// Mutable indexed access to an allocation by its `AllocId`.
1028    pub(crate) fn alloc_mut(&mut self, id: AllocId) -> &mut Allocation<'z3, 'tcx> {
1029        &mut self.path_state.mem_units[id.0].allocation
1030    }
1031
1032    /// Indexed access to an allocation's contents by its `AllocId`.
1033    pub(crate) fn content(&self, id: AllocId) -> &MemoryContent<'z3, 'tcx> {
1034        &self.path_state.mem_units[id.0].content
1035    }
1036
1037    /// Mutable indexed access to an allocation's contents by its `AllocId`.
1038    pub(crate) fn content_mut(&mut self, id: AllocId) -> &mut MemoryContent<'z3, 'tcx> {
1039        &mut self.path_state.mem_units[id.0].content
1040    }
1041
1042    /// Whether `id` was asserted a valid C string via a `ValidCStr` contract
1043    /// fact / struct invariant.
1044    pub(crate) fn is_cstr_trusted(&self, id: AllocId) -> bool {
1045        self.content(id).facts.cstr_trusted
1046    }
1047
1048    /// Whether `id` was asserted valid UTF-8 via a `ValidString` contract fact.
1049    pub(crate) fn is_utf8_trusted(&self, id: AllocId) -> bool {
1050        self.content(id).facts.utf8_trusted
1051    }
1052
1053    /// The ultimate root allocation, following `parent` chains (sub-allocations
1054    /// created by `from_raw_parts` / `split_at` / `as_chunks`, whose `parent`
1055    /// points at the allocation they were split from).
1056    pub(crate) fn root_alloc(&self, id: AllocId) -> AllocId {
1057        let mut cur = id;
1058        let mut guard = 0;
1059        while let Some(parent) = self.alloc(cur).parent {
1060            cur = parent;
1061            guard += 1;
1062            // A parent chain as long as the total allocation count means a
1063            // cycle; stop rather than loop forever.
1064            if guard >= self.path_state.mem_units.len() {
1065                break;
1066            }
1067        }
1068        cur
1069    }
1070
1071    /// Create a fresh symbolic Z3 int constant (globally unique, even across
1072    /// calls with the same prefix — `Z3_mk_fresh_const` auto-suffixes the name).
1073    pub(crate) fn fresh_int(&self, prefix: &str) -> Int<'z3> {
1074        Int::fresh_const(self.z3_ctx, prefix)
1075    }
1076
1077    /// Get the value of a specific field within an aggregate local.
1078    ///
1079    /// Field values live in the allocation backing the local (the
1080    /// memory-contents layer [`MemoryContent::values`]), keyed by the local's declared
1081    /// type as the view type.  Returns `None` if the local has no allocation
1082    /// (the field was never materialized).
1083    pub(crate) fn field_value(&self, local: Local, path: &[usize]) -> Option<&VmValue<'z3, 'tcx>> {
1084        let alloc_id = *self.path_state.current_frame.local_alloc.get(&local)?;
1085        let view_ty = self.body().local_decls[local].ty;
1086        self.load_value(alloc_id, view_ty, path).or_else(|| {
1087            let mut candidates = vec![path.to_vec()];
1088            for position in (0..path.len()).rev() {
1089                if path[position] == REPEATED_ARRAY_ELEMENT {
1090                    continue;
1091                }
1092                let alternatives = candidates.clone();
1093                for mut candidate in alternatives {
1094                    candidate[position] = REPEATED_ARRAY_ELEMENT;
1095                    if let Some(value) = self.load_value(alloc_id, view_ty, &candidate) {
1096                        return Some(value);
1097                    }
1098                    candidates.push(candidate);
1099                }
1100            }
1101            None
1102        })
1103    }
1104
1105    /// Enumerate the field paths materialized for a local: every non-empty
1106    /// `path` for which [`Self::field_value`] currently returns a value (the
1107    /// local's allocation's fields under its declared view type).  The whole
1108    /// value (`path == []`) is deliberately excluded — it is read via
1109    /// [`Self::local_value`], not as a "field", so callers iterating fields do
1110    /// not accidentally treat the whole value as a field projection.
1111    pub(crate) fn field_paths(&self, local: Local) -> Vec<Vec<usize>> {
1112        let Some(&alloc_id) = self.path_state.current_frame.local_alloc.get(&local) else {
1113            return Vec::new();
1114        };
1115        let view_ty = self.body().local_decls[local].ty;
1116        self.path_state.mem_units[alloc_id.0]
1117            .content
1118            .values
1119            .keys()
1120            .filter(|(t, p)| *t == view_ty && !p.is_empty())
1121            .map(|(_, p)| p.clone())
1122            .collect()
1123    }
1124
1125    /// The declared type of `local` in `frame`'s body.
1126    pub(crate) fn frame_local_ty(&self, frame: &FrameState<'tcx>, local: Local) -> Ty<'tcx> {
1127        let body = frame
1128            .instantiated_body
1129            .or_else(|| {
1130                (frame.current_def_id == self.target_def_id)
1131                    .then_some(self.instantiated_target_body)
1132                    .flatten()
1133            })
1134            .unwrap_or_else(|| self.tcx.optimized_mir(frame.current_def_id));
1135        body.local_decls[local].ty
1136    }
1137
1138    /// Enumerate the field paths materialized for `local` in a saved caller
1139    /// `frame`. Field values live in the path-scoped [`MemoryContent::values`], so they
1140    /// are read via `frame`'s `local_alloc` and declared type.
1141    pub(crate) fn frame_field_paths(
1142        &self,
1143        frame: &FrameState<'tcx>,
1144        local: Local,
1145    ) -> Vec<Vec<usize>> {
1146        let Some(&alloc_id) = frame.local_alloc.get(&local) else {
1147            return Vec::new();
1148        };
1149        let view_ty = self.frame_local_ty(frame, local);
1150        self.path_state.mem_units[alloc_id.0]
1151            .content
1152            .values
1153            .keys()
1154            .filter(|(t, p)| *t == view_ty && !p.is_empty())
1155            .map(|(_, p)| p.clone())
1156            .collect()
1157    }
1158
1159    /// Read a field of `local` in a saved caller `frame`.
1160    pub(crate) fn frame_field_value(
1161        &self,
1162        frame: &FrameState<'tcx>,
1163        local: Local,
1164        path: &[usize],
1165    ) -> Option<&VmValue<'z3, 'tcx>> {
1166        let alloc_id = *frame.local_alloc.get(&local)?;
1167        let view_ty = self.frame_local_ty(frame, local);
1168        self.load_value(alloc_id, view_ty, path)
1169    }
1170
1171    /// Read the whole value of `local` in a saved caller `frame` (its
1172    /// `path == []` slot). The value lives in the path-scoped [`MemoryContent::values`],
1173    /// while the name → allocation binding lives in the saved `frame`.
1174    pub(crate) fn frame_local_value(
1175        &self,
1176        frame: &FrameState<'tcx>,
1177        local: Local,
1178    ) -> Option<&VmValue<'z3, 'tcx>> {
1179        let alloc_id = *frame.local_alloc.get(&local)?;
1180        let view_ty = self.frame_local_ty(frame, local);
1181        self.load_value(alloc_id, view_ty, &[])
1182    }
1183
1184    /// Enumerate `(local, whole value)` for every local with a materialized
1185    /// whole value (its `path == []` slot). This is the whole-value counterpart
1186    /// to [`Self::field_paths`], used where code used to iterate `locals`.
1187    pub(crate) fn all_local_values(&self) -> Vec<(Local, &VmValue<'z3, 'tcx>)> {
1188        self.path_state.current_frame
1189            .local_alloc
1190            .keys()
1191            .copied()
1192            .filter_map(|local| self.local_value(local).map(|value| (local, value)))
1193            .collect()
1194    }
1195
1196    /// The field carrying an owned value's heap pointer (`Box`/`Vec`/`String`'s
1197    /// owning pointer field), located generically via
1198    /// [`Self::container_ptr_field`] (e.g. `Box` → `[0, 0]`, `Vec` → `[0, 0, 0]`).
1199    /// Falls back to the first materialized field with heap provenance for
1200    /// owners whose deep `NonNull` leaf was not explicitly materialized (e.g. a
1201    /// `Box` produced by `into_boxed_slice`, which only records the whole value).
1202    pub(crate) fn owner_ptr_field(&self, local: Local) -> Option<&VmValue<'z3, 'tcx>> {
1203        let ty = self.body().local_decls[local].ty;
1204        if let Some(path) = self.container_ptr_field(ty)
1205            && let Some(v) = self.field_value(local, &path)
1206            && v.provenance_alloc_id().is_some()
1207        {
1208            return Some(v);
1209        }
1210        self.field_paths(local).iter().find_map(|path| {
1211            self.field_value(local, path)
1212                .filter(|v| v.provenance_alloc_id().is_some())
1213        })
1214    }
1215
1216    /// Invalidate `local`'s owner-field provenance (mark it moved-out after a
1217    /// whole-place move), so a later `Owning` check does not treat it as a
1218    /// second owner of the heap allocation it no longer owns.
1219    pub(crate) fn invalidate_owner_field(&mut self, local: Local) {
1220        let ty = self.body().local_decls[local].ty;
1221        let Some(path) = self.container_ptr_field(ty) else {
1222            return;
1223        };
1224        let Some(mut fv) = self.field_value(local, &path).cloned() else {
1225            return;
1226        };
1227        if fv.provenance_alloc_id().is_some() {
1228            fv.provenance = None;
1229            self.set_field_value(local, path, fv);
1230        }
1231    }
1232
1233    /// Set the value of a specific field within an aggregate local.
1234    ///
1235    /// Ensures the local has a backing allocation, then stores into the
1236    /// memory-contents layer ([`MemoryContent::values`]) keyed by the local's declared
1237    /// type as the view type.
1238    pub(crate) fn set_field_value(
1239        &mut self,
1240        local: Local,
1241        path: Vec<usize>,
1242        value: VmValue<'z3, 'tcx>,
1243    ) {
1244        let view_ty = self.body().local_decls[local].ty;
1245        self.ensure_local_allocation(local);
1246        let alloc_id = self.path_state.current_frame.local_alloc[&local];
1247        self.store_value(alloc_id, view_ty, path, value);
1248    }
1249
1250    pub(crate) fn write_local_path(
1251        &mut self,
1252        local: Local,
1253        path: Vec<usize>,
1254        value: VmValue<'z3, 'tcx>,
1255    ) {
1256        let written_ty = value.ty;
1257        let written_inner = matches!(self.body().local_decls[local].ty.kind(), TyKind::Adt(def, args)
1258            if type_ids::is_maybe_uninit_type(def.did())
1259                && args.first().and_then(|arg| arg.as_type()) == Some(value.ty))
1260            && !path.is_empty()
1261            && path.iter().all(|field| *field == 0)
1262            && value.facts.init;
1263        let prior_term = self
1264            .local_value(local)
1265            .map(|value| value.z3_term.to_string());
1266        self.path_state.index_access_facts
1267            .retain(|(slice_term, index_term, slice, index)| {
1268                *slice != local
1269                    && *index != local
1270                    && prior_term.as_ref().is_none_or(|term| {
1271                        *term != slice_term.to_string() && *term != index_term.to_string()
1272                    })
1273            });
1274        if path.is_empty() {
1275            self.invalidate_indexed_array(local);
1276            self.invalidate_field_descendants(local, &[]);
1277            self.set_local(local, value);
1278        } else {
1279            self.invalidate_field_descendants(local, &path);
1280            self.set_field_value(local, path, value);
1281            if written_inner && let Some(&alloc_id) = self.path_state.current_frame.local_alloc.get(&local) {
1282                self.content_mut(alloc_id).facts.written_pointee_ty = Some(written_ty);
1283            }
1284        }
1285    }
1286
1287    pub(crate) fn invalidate_field_descendants(&mut self, local: Local, path: &[usize]) {
1288        if let Some(&alloc_id) = self.path_state.current_frame.local_alloc.get(&local) {
1289            let view_ty = self.body().local_decls[local].ty;
1290            self.content_mut(alloc_id)
1291                .values
1292                .retain(|(ty, stored_path), _| {
1293                    *ty != view_ty
1294                        || stored_path.len() <= path.len()
1295                        || !stored_path.starts_with(path)
1296                });
1297        }
1298    }
1299
1300    /// Assert path conditions and invariant constraints into a solver.
1301    pub(crate) fn assert_all(&self, solver: &z3::Solver<'z3>) {
1302        self.assert_path_constraints(solver);
1303        let zero = Int::from_u64(self.z3_ctx, 0);
1304        for unit in &self.path_state.mem_units {
1305            let alloc = &unit.allocation;
1306            if !alloc.is_external() {
1307                solver.assert(&alloc.base._eq(&zero).not());
1308            }
1309            solver.assert(&alloc.size.ge(&zero));
1310            if alloc.align.simplify().as_u64() != Some(1) {
1311                solver.assert(&alloc.base.rem(&alloc.align)._eq(&zero));
1312            }
1313        }
1314
1315        // Whole values (`path == []`) and field values (`path == [i, ..]`) both
1316        // live in the memory-contents layer.  Field paths exclude the whole
1317        // value (see [`Self::field_paths`]), so assert the whole value and the
1318        // fields separately.
1319        let local_ids: Vec<Local> = self.path_state.current_frame.local_alloc.keys().copied().collect();
1320        for local in local_ids {
1321            if let Some(value) = self.local_value(local) {
1322                self.assert_value_constraints(solver, value);
1323            }
1324            for path in self.field_paths(local) {
1325                if let Some(value) = self.field_value(local, &path) {
1326                    self.assert_value_constraints(solver, value);
1327                }
1328            }
1329        }
1330    }
1331
1332    pub(crate) fn assert_path_constraints(&self, solver: &z3::Solver<'z3>) {
1333        for cond in &self.path_state.constraints.assertions {
1334            solver.assert(cond);
1335        }
1336    }
1337
1338    /// Assert a single symbolic value's known invariant constraints.
1339    fn assert_value_constraints(&self, solver: &z3::Solver<'z3>, value: &VmValue<'z3, 'tcx>) {
1340        let zero = Int::from_u64(self.z3_ctx, 0);
1341        if value.facts.non_null {
1342            solver.assert(&value.z3_term._eq(&zero).not());
1343        }
1344        if let Some(ref prov) = value.provenance {
1345            let is_scalar = matches!(
1346                value.ty.kind(),
1347                rustc_middle::ty::TyKind::Uint(_)
1348                    | rustc_middle::ty::TyKind::Int(_)
1349                    | rustc_middle::ty::TyKind::Bool
1350                    | rustc_middle::ty::TyKind::Char
1351            );
1352            if !is_scalar {
1353                let alloc = self.alloc(prov.alloc_id);
1354                let expected = Int::add(self.z3_ctx, &[&alloc.base, &prov.offset]);
1355                solver.assert(&value.z3_term._eq(&expected));
1356            }
1357        }
1358        if matches!(
1359            value.ty.kind(),
1360            rustc_middle::ty::TyKind::Uint(_)
1361                | rustc_middle::ty::TyKind::Bool
1362                | rustc_middle::ty::TyKind::Char
1363        ) {
1364            solver.assert(&value.z3_term.ge(&zero));
1365        }
1366        if matches!(value.ty.kind(), rustc_middle::ty::TyKind::Bool) {
1367            let one = Int::from_u64(self.z3_ctx, 1);
1368            solver.assert(&value.z3_term.le(&one));
1369        }
1370        if matches!(value.ty.kind(), rustc_middle::ty::TyKind::Char) {
1371            let max = Int::from_u64(self.z3_ctx, 0x10FFFF);
1372            solver.assert(&value.z3_term.le(&max));
1373        }
1374    }
1375}
1376
1377impl std::fmt::Debug for VmExecutor<'_, '_> {
1378    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1379        f.debug_struct("VmExecutor")
1380            .field("locals_count", &self.path_state.current_frame.local_alloc.len())
1381            .field("allocations_count", &self.path_state.mem_units.len())
1382            .field("assertions", &self.path_state.constraints.assertions.len())
1383            .finish()
1384    }
1385}
1386
1387// ── Shared value extraction ──────────────────────────────────────
1388
1389impl<'z3, 'tcx> VmExecutor<'z3, 'tcx> {
1390    pub(crate) fn indexed_element_target(
1391        &self,
1392        place: &Place<'tcx>,
1393    ) -> Option<(AllocId, Int<'z3>)> {
1394        let element_ty = place.ty(self.body(), self.tcx).ty;
1395        if !matches!(
1396            element_ty.kind(),
1397            rustc_middle::ty::TyKind::RawPtr(..)
1398                | rustc_middle::ty::TyKind::Int(..)
1399                | rustc_middle::ty::TyKind::Uint(..)
1400                | rustc_middle::ty::TyKind::Bool
1401                | rustc_middle::ty::TyKind::Char
1402                | rustc_middle::ty::TyKind::Float(..)
1403        ) {
1404            return None;
1405        }
1406        if !matches!(
1407            place.projection.last()?.kind(),
1408            ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. }
1409        ) {
1410            return None;
1411        }
1412        let mut current_ty = self.body().local_decls[place.local].ty;
1413        let mut fields = Vec::new();
1414        let mut index = Int::from_u64(self.z3_ctx, 0);
1415        let element_size = self.size_of_ty(element_ty);
1416        if element_size == 0 {
1417            return None;
1418        }
1419        let mut indexed = false;
1420        for projection in place.projection.iter() {
1421            match projection {
1422                ProjectionElem::Field(field, field_ty) if !indexed => {
1423                    fields.push(field.as_usize());
1424                    current_ty = field_ty;
1425                }
1426                ProjectionElem::Deref => {
1427                    current_ty = match current_ty.kind() {
1428                        rustc_middle::ty::TyKind::Ref(_, inner, _)
1429                        | rustc_middle::ty::TyKind::RawPtr(inner, _) => *inner,
1430                        _ => return None,
1431                    };
1432                }
1433                ProjectionElem::Downcast(..) => {}
1434                ProjectionElem::Index(local) => {
1435                    let inner = match current_ty.kind() {
1436                        rustc_middle::ty::TyKind::Array(inner, _)
1437                        | rustc_middle::ty::TyKind::Slice(inner) => *inner,
1438                        _ => return None,
1439                    };
1440                    let inner_size = self.size_of_ty(inner);
1441                    if inner_size == 0 || inner_size % element_size != 0 {
1442                        return None;
1443                    }
1444                    let term = self.local_value(local)?.z3_term.clone();
1445                    let stride = Int::from_u64(self.z3_ctx, inner_size / element_size);
1446                    let step = Int::mul(self.z3_ctx, &[&term, &stride]);
1447                    index = Int::add(self.z3_ctx, &[&index, &step]);
1448                    current_ty = inner;
1449                    indexed = true;
1450                }
1451                ProjectionElem::ConstantIndex {
1452                    offset, from_end, ..
1453                } => {
1454                    let (inner, length) = match current_ty.kind() {
1455                        rustc_middle::ty::TyKind::Array(inner, length) => (*inner, Some(length)),
1456                        rustc_middle::ty::TyKind::Slice(inner) => (*inner, None),
1457                        _ => return None,
1458                    };
1459                    let inner_size = self.size_of_ty(inner);
1460                    if inner_size == 0 || inner_size % element_size != 0 {
1461                        return None;
1462                    }
1463                    let position = if from_end {
1464                        length?.try_to_target_usize(self.tcx)?.checked_sub(offset)?
1465                    } else {
1466                        offset
1467                    };
1468                    let term = Int::from_u64(self.z3_ctx, position);
1469                    let stride = Int::from_u64(self.z3_ctx, inner_size / element_size);
1470                    let step = Int::mul(self.z3_ctx, &[&term, &stride]);
1471                    index = Int::add(self.z3_ctx, &[&index, &step]);
1472                    current_ty = inner;
1473                    indexed = true;
1474                }
1475                _ => return None,
1476            }
1477        }
1478        if current_ty != element_ty {
1479            return None;
1480        }
1481        let alloc_id = if fields.is_empty() {
1482            let local_ty = self.body().local_decls[place.local].ty;
1483            if matches!(local_ty.kind(), rustc_middle::ty::TyKind::Array(..)) {
1484                self.path_state.current_frame.local_alloc.get(&place.local).copied()?
1485            } else {
1486                self.local_value(place.local)
1487                    .and_then(|value| value.provenance_alloc_id())
1488                    .or_else(|| self.path_state.current_frame.local_alloc.get(&place.local).copied())?
1489            }
1490        } else {
1491            self.field_value(place.local, &fields)?
1492                .provenance_alloc_id()?
1493        };
1494        let stored_ty = self.alloc(alloc_id).element_ty.as_ty()?;
1495        let mut stored_leaf_ty = stored_ty;
1496        while let rustc_middle::ty::TyKind::Array(inner, _) = stored_leaf_ty.kind() {
1497            stored_leaf_ty = *inner;
1498        }
1499        (stored_leaf_ty == element_ty).then_some((alloc_id, index))
1500    }
1501
1502    pub(crate) fn store_indexed_element(
1503        &mut self,
1504        alloc_id: AllocId,
1505        index: Int<'z3>,
1506        value: VmValue<'z3, 'tcx>,
1507    ) {
1508        let retained = self
1509            .content(alloc_id)
1510            .indexed_elements
1511            .iter()
1512            .filter(|(stored_index, _)| self.path_implies(&stored_index._eq(&index).not()))
1513            .cloned()
1514            .collect();
1515        let content = self.content_mut(alloc_id);
1516        content.indexed_elements_modified = true;
1517        content.indexed_elements = retained;
1518        content.indexed_elements.push((index, value));
1519    }
1520
1521    pub(crate) fn store_repeated_indexed_elements(
1522        &mut self,
1523        alloc_id: AllocId,
1524        base: Int<'z3>,
1525        count: u64,
1526        value: VmValue<'z3, 'tcx>,
1527    ) {
1528        let end = Int::add(self.z3_ctx, &[&base, &Int::from_u64(self.z3_ctx, count)]);
1529        let retained = self
1530            .content(alloc_id)
1531            .indexed_elements
1532            .iter()
1533            .filter(|(index, _)| {
1534                let outside = Bool::or(self.z3_ctx, &[&index.lt(&base), &index.ge(&end)]);
1535                self.path_implies(&outside)
1536            })
1537            .cloned()
1538            .collect::<Vec<_>>();
1539        let mut elements = retained;
1540        for offset in 0..count {
1541            let index = Int::add(self.z3_ctx, &[&base, &Int::from_u64(self.z3_ctx, offset)]);
1542            elements.push((index, value.clone()));
1543        }
1544        let content = self.content_mut(alloc_id);
1545        content.indexed_elements_modified = true;
1546        content.indexed_elements = elements;
1547    }
1548
1549    pub(crate) fn path_implies(&self, condition: &Bool<'z3>) -> bool {
1550        if condition.simplify().as_bool() == Some(true) {
1551            return true;
1552        }
1553        let solver = Solver::new(self.z3_ctx);
1554        for assertion in &self.path_state.constraints.assertions {
1555            solver.assert(assertion);
1556        }
1557        solver.assert(&condition.not());
1558        solver.check() == SatResult::Unsat
1559    }
1560
1561    fn stored_indexed_element(&self, place: &Place<'tcx>) -> Option<VmValue<'z3, 'tcx>> {
1562        let (alloc_id, index) = self.indexed_element_target(place)?;
1563        let elements = &self.content(alloc_id).indexed_elements;
1564        if let Some((_, value)) = elements
1565            .iter()
1566            .rev()
1567            .find(|(stored_index, _)| index == *stored_index)
1568        {
1569            return Some(value.clone());
1570        }
1571        for (stored_index, value) in elements.iter().rev() {
1572            if self.path_implies(&index._eq(stored_index)) {
1573                return Some(value.clone());
1574            }
1575        }
1576        None
1577    }
1578
1579    pub(crate) fn symbolic_const_term(
1580        &self,
1581        constant: &rustc_middle::mir::Const<'tcx>,
1582    ) -> Int<'z3> {
1583        self.symbolic_const_term_text(&format!("{constant:?}"))
1584    }
1585
1586    pub(crate) fn symbolic_const_term_text(&self, text: &str) -> Int<'z3> {
1587        let name = format!("const_{}", text.replace([':', '#', ' '], "_"));
1588        Int::new_const(self.z3_ctx, name.as_str())
1589    }
1590
1591    pub(crate) fn const_param_term(&self, index: u32) -> Option<Int<'z3>> {
1592        let generics = self.tcx.generics_of(self.path_state.current_frame.current_def_id);
1593        if index as usize >= generics.count() {
1594            return None;
1595        }
1596        let param = generics.param_at(index as usize, self.tcx);
1597        if !matches!(
1598            param.kind,
1599            rustc_middle::ty::GenericParamDefKind::Const { .. }
1600        ) {
1601            return None;
1602        }
1603        let ty = self.tcx.type_of(param.def_id).instantiate_identity();
1604        let ty = ty.skip_norm_wip();
1605        let value = rustc_middle::ty::Const::new_param(
1606            self.tcx,
1607            rustc_middle::ty::ParamConst::new(index, param.name),
1608        );
1609        Some(self.symbolic_const_term(&rustc_middle::mir::Const::Ty(ty, value)))
1610    }
1611
1612    /// Extract a VmValue from a MIR operand.
1613    pub(crate) fn value_of_operand(&self, operand: &Operand<'tcx>) -> VmValue<'z3, 'tcx> {
1614        match operand {
1615            Operand::Copy(place) | Operand::Move(place) => self
1616                .value_of_place(place)
1617                .unwrap_or_else(|| self.unknown_value_for_place(place)),
1618            Operand::Constant(constant) => {
1619                let text = format!("{:?}", constant.const_);
1620                // `size_of::<T>()` / `align_of::<T>()` lower to the
1621                // `SizedTypeProperties::SIZE`/`::ALIGN` associated consts for a
1622                // generic `T`.  Bind them to the shared symbolic `sizeof_T` /
1623                // `align_T` (created by `size_sym`/`align_sym` during
1624                // `init_parameters`) so they agree with allocation sizes and
1625                // pointer strides instead of being unrelated fresh constants.
1626                if let rustc_middle::mir::Const::Unevaluated(uneval, _) = constant.const_ {
1627                    if mir_utils::is_sized_type_property(self.tcx, uneval.def, "IS_ZST")
1628                        && !uneval.args.is_empty()
1629                    {
1630                        let ty = uneval.args.type_at(0);
1631                        let size = if mir_utils::ty_has_type_param(ty) {
1632                            self.size_sym_read(ty)
1633                        } else {
1634                            Int::from_u64(self.z3_ctx, self.size_of_ty(ty))
1635                        };
1636                        let zero = Int::from_u64(self.z3_ctx, 0);
1637                        let one = Int::from_u64(self.z3_ctx, 1);
1638                        return VmValue::new(
1639                            size._eq(&zero).ite(&one, &zero),
1640                            constant.const_.ty(),
1641                        );
1642                    }
1643                    let is_size = mir_utils::is_sized_type_property(self.tcx, uneval.def, "SIZE");
1644                    let is_align = mir_utils::is_sized_type_property(self.tcx, uneval.def, "ALIGN");
1645                    if (is_size || is_align) && !uneval.args.is_empty() {
1646                        let ty = uneval.args.type_at(0);
1647                        let term = if is_size {
1648                            self.size_sym_read(ty)
1649                        } else {
1650                            self.align_sym_read(ty)
1651                        };
1652                        return VmValue::new(term, constant.const_.ty());
1653                    }
1654                }
1655                let int_val = mir_utils::eval_const_scalar_int(self.tcx, &constant.const_, &text);
1656                let field_offset = int_val.is_none()
1657                    && mir_utils::offset_of_container(self.tcx, &constant.const_).is_some();
1658                let enum_variant = mir_utils::const_destructure(self.tcx, &constant.const_)
1659                    .and_then(|(variant, _)| variant)
1660                    .or_else(|| {
1661                        let TyKind::Adt(adt, args) = constant.const_.ty().kind() else {
1662                            return None;
1663                        };
1664                        (int_val == Some(0)
1665                            && self
1666                                .tcx
1667                                .is_diagnostic_item(rustc_span::sym::Option, adt.did())
1668                            && matches!(args.type_at(0).kind(), TyKind::Ref(..)))
1669                        .then_some(0)
1670                    });
1671                let ty = constant.const_.ty();
1672                let wide_literal = matches!(
1673                    ty.kind(),
1674                    TyKind::Int(rustc_middle::ty::IntTy::I128)
1675                        | TyKind::Uint(rustc_middle::ty::UintTy::U128)
1676                )
1677                .then(|| {
1678                    constant
1679                        .const_
1680                        .eval(
1681                            self.tcx,
1682                            TypingEnv::fully_monomorphized(),
1683                            rustc_span::DUMMY_SP,
1684                        )
1685                        .ok()
1686                        .and_then(|value| value.try_to_scalar_int())
1687                        .and_then(|scalar| self.scalar_bits_term(ty, scalar.to_bits(scalar.size())))
1688                })
1689                .flatten();
1690                let term = wide_literal
1691                    .or_else(|| int_val.and_then(|value| self.scalar_bits_term(ty, value as u128)))
1692                    .unwrap_or_else(|| self.symbolic_const_term(&constant.const_));
1693                let enum_discriminant = enum_variant.and_then(|variant| {
1694                    self.enum_discriminant_term(ty, VariantIdx::from_usize(variant as usize))
1695                });
1696                VmValue {
1697                    z3_term: term,
1698                    ty,
1699                    provenance: None,
1700                    facts: ValueFacts::default(),
1701                    source: if let Some(term) = enum_discriminant {
1702                        ValueSource::KnownDiscriminant(term)
1703                    } else if field_offset {
1704                        ValueSource::FieldOffset
1705                    } else {
1706                        ValueSource::None
1707                    },
1708                }
1709            }
1710            Operand::RuntimeChecks(_) => VmValue::new(
1711                self.fresh_int("runtime_checks"),
1712                self.body().local_decls[Local::from_usize(0)].ty,
1713            ),
1714        }
1715    }
1716
1717    pub(crate) fn materialize_const_adt(
1718        &mut self,
1719        local: Local,
1720        constant: &rustc_middle::mir::Const<'tcx>,
1721    ) {
1722        if let rustc_middle::mir::Const::Unevaluated(uneval, _) = constant
1723            && mir_utils::is_sized_type_property(self.tcx, uneval.def, "LAYOUT")
1724            && !uneval.args.is_empty()
1725            && let TyKind::Adt(layout_def, layout_args) = constant.ty().kind()
1726        {
1727            let ty = uneval.args.type_at(0);
1728            for (index, field) in layout_def.non_enum_variant().fields.iter().enumerate() {
1729                let term = match field.name.as_str() {
1730                    "size" => self.size_sym(ty),
1731                    "align" => self.align_sym(ty),
1732                    _ => continue,
1733                };
1734                let field_ty = mir_utils::field_ty(self.tcx, field, layout_args);
1735                self.set_field_value(local, vec![index], VmValue::new(term, field_ty));
1736            }
1737            return;
1738        }
1739        let Some((_variant, fields)) = mir_utils::const_destructure(self.tcx, constant) else {
1740            return;
1741        };
1742        for (idx, (field_val, field_ty)) in fields.iter().enumerate() {
1743            let term = self.const_field_term(field_val, *field_ty);
1744            self.set_field_value(local, vec![idx], VmValue::new(term, *field_ty));
1745        }
1746    }
1747
1748    fn const_field_term(&self, val: &ConstValue, ty: Ty<'tcx>) -> Int<'z3> {
1749        if let Some(scalar) = (*val).try_to_scalar_int() {
1750            if let Some(term) = self.scalar_bits_term(ty, scalar.to_bits(scalar.size())) {
1751                return term;
1752            }
1753        }
1754        let name = format!(
1755            "const_field_{}",
1756            format!("{:?}", val).replace([':', '#', ' '], "_")
1757        );
1758        Int::new_const(self.z3_ctx, name.as_str())
1759    }
1760
1761    /// Read the byte at `offset` within a `repr(C)`-style ADT from its
1762    /// materialized scalar field values — the field→byte direction of the cast
1763    /// cross-view materialization.  Returns `None` when `offset` does not land
1764    /// inside a concrete scalar field (so the caller falls back to the base).
1765    fn byte_from_field(&self, alloc_id: AllocId, ty: Ty<'tcx>, offset: usize) -> Option<Int<'z3>> {
1766        let rustc_middle::ty::TyKind::Adt(adt_def, substs) = ty.kind() else {
1767            return None;
1768        };
1769        let variant = adt_def.non_enum_variant();
1770        for (idx, field_def) in variant.fields.iter().enumerate() {
1771            let field_ty = mir_utils::field_ty(self.tcx, field_def, substs);
1772            let field_off = self.field_offset_in_bytes(ty, idx) as usize;
1773            let field_size = self.size_of_ty(field_ty) as usize;
1774            if offset >= field_off && offset < field_off + field_size {
1775                let fv = self.load_value(alloc_id, ty, &[idx])?;
1776                let byte_idx = offset - field_off;
1777                // Fields wider than 8 bytes (e.g. `u128`) cannot be shifted by a
1778                // `u64` divisor; fall back to the base rather than overflow.
1779                if byte_idx >= 8 {
1780                    return None;
1781                }
1782                let divisor = Int::from_u64(self.z3_ctx, 1u64 << (byte_idx * 8));
1783                let modulus = Int::from_u64(self.z3_ctx, 256);
1784                return Some(fv.z3_term.div(&divisor).rem(&modulus));
1785            }
1786        }
1787        None
1788    }
1789
1790    /// Look up the value stored at a MIR place.
1791    pub(crate) fn value_of_place(&self, place: &Place<'tcx>) -> Option<VmValue<'z3, 'tcx>> {
1792        if place
1793            .projection
1794            .iter()
1795            .any(|projection| matches!(projection, ProjectionElem::Deref))
1796            && let Some(alloc_id) = self
1797                .local_value(place.local)
1798                .and_then(VmValue::provenance_alloc_id)
1799        {
1800            self.record_memory_use(alloc_id, place.local);
1801        }
1802        if place.projection.is_empty() {
1803            return self.local_value(place.local).cloned();
1804        }
1805        let place_ty = place.ty(self.body(), self.tcx).ty;
1806        if place.projection.len() == 3
1807            && matches!(place.projection[0].kind(), ProjectionElem::Deref)
1808            && matches!(place.projection[1].kind(), ProjectionElem::Downcast(..))
1809            && let ProjectionElem::Field(field, _) = place.projection[2].kind()
1810            && let Some(pointer) = self.local_value(place.local)
1811            && let Some(provenance) = &pointer.provenance
1812            && provenance.offset.simplify().as_u64() == Some(0)
1813            && let Some(pointee) = mir_utils::pointee_ty(pointer.ty)
1814            && matches!(pointee.kind(), TyKind::Adt(def, _) if def.is_enum())
1815            && self.alloc(provenance.alloc_id).element_ty.as_ty() == Some(pointee)
1816            && let Some(value) = self.load_value(provenance.alloc_id, pointee, &[field.as_usize()])
1817        {
1818            return Some(value.clone());
1819        }
1820        let last_is_index = place.projection.last().is_some_and(|projection| {
1821            matches!(
1822                projection.kind(),
1823                ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. }
1824            )
1825        });
1826        let indexed_target_modified = last_is_index
1827            && self
1828                .indexed_element_target(place)
1829                .is_some_and(|(alloc_id, _)| self.content(alloc_id).indexed_elements_modified);
1830        let index_count = place
1831            .projection
1832            .iter()
1833            .filter(|projection| {
1834                matches!(
1835                    projection.kind(),
1836                    ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. }
1837                )
1838            })
1839            .count();
1840        let indexed_value = last_is_index
1841            && (matches!(place_ty.kind(), rustc_middle::ty::TyKind::RawPtr(..))
1842                || index_count > 1
1843                || indexed_target_modified);
1844        if indexed_value {
1845            if let Some(value) = self.stored_indexed_element(place) {
1846                return Some(value);
1847            }
1848            if indexed_target_modified {
1849                return Some(self.unknown_value_for_place(place));
1850            }
1851            if let Some(&alloc_id) = self.path_state.current_frame.local_alloc.get(&place.local)
1852                && !self.content(alloc_id).indexed_elements_modified
1853            {
1854                let mut path = Vec::new();
1855                let mut supported = true;
1856                for projection in place.projection.iter() {
1857                    match projection {
1858                        ProjectionElem::Field(field, _) => path.push(field.as_usize()),
1859                        ProjectionElem::Index(local) => {
1860                            let index = self
1861                                .local_value(local)
1862                                .and_then(|value| value.z3_term.simplify().as_u64())
1863                                .and_then(|index| usize::try_from(index).ok())
1864                                .unwrap_or(REPEATED_ARRAY_ELEMENT);
1865                            path.push(index);
1866                        }
1867                        ProjectionElem::ConstantIndex {
1868                            offset,
1869                            from_end: false,
1870                            ..
1871                        } => {
1872                            path.push(offset as usize);
1873                        }
1874                        _ => supported = false,
1875                    }
1876                }
1877                if supported && let Some(value) = self.field_value(place.local, &path) {
1878                    return Some(value.clone());
1879                }
1880            }
1881        }
1882        if let Some(ProjectionElem::Index(index_local)) = place.projection.last()
1883            && place.projection[..place.projection.len() - 1]
1884                .iter()
1885                .all(|projection| matches!(projection.kind(), ProjectionElem::Field(..)))
1886            && let Some(index) = self
1887                .local_value(*index_local)
1888                .and_then(|value| value.z3_term.simplify().as_u64())
1889        {
1890            let mut path = place.projection[..place.projection.len() - 1]
1891                .iter()
1892                .filter_map(|projection| match projection.kind() {
1893                    ProjectionElem::Field(index, _) => Some(index.as_usize()),
1894                    _ => None,
1895                })
1896                .collect::<Vec<_>>();
1897            path.push(index as usize);
1898            if let Some(value) = self.field_value(place.local, &path) {
1899                return Some(value.clone());
1900            }
1901        }
1902        if indexed_value {
1903            return Some(self.unknown_value_for_place(place));
1904        }
1905        if place.projection.len() == 1
1906            && matches!(place.projection[0], ProjectionElem::Deref)
1907            && let Some(pointer) = self.local_value(place.local)
1908            && let Some(provenance) = &pointer.provenance
1909            && self.alloc(provenance.alloc_id).element_ty.as_ty() == Some(place_ty)
1910            && let Some(offset) = provenance.offset.simplify().as_u64()
1911            && let size = self.size_of_ty(place_ty)
1912            && size != 0
1913            && offset % size == 0
1914        {
1915            let value = self.path_state.mem_units[provenance.alloc_id.0]
1916                .content
1917                .values
1918                .iter()
1919                .find_map(|((ty, path), value)| {
1920                    (matches!(ty.kind(), rustc_middle::ty::TyKind::Array(elem, _) if *elem == place_ty)
1921                        && path.as_slice() == [offset as usize / size as usize])
1922                        .then_some(value.clone())
1923                });
1924            if let Some(value) = value {
1925                return Some(value);
1926            }
1927        }
1928        if place.projection.len() == 1
1929            && matches!(place.projection[0], ProjectionElem::Deref)
1930            && matches!(place_ty.kind(), TyKind::Adt(def, _) if def.is_enum())
1931            && let Some(pointer) = self.local_value(place.local)
1932            && let Some(provenance) = &pointer.provenance
1933            && provenance.offset.simplify().as_u64() == Some(0)
1934            && self.alloc(provenance.alloc_id).element_ty.as_ty() == Some(place_ty)
1935            && let Some(value) = self.load_value(provenance.alloc_id, place_ty, &[])
1936        {
1937            return Some(value.clone());
1938        }
1939        if place.projection.len() == 1
1940            && matches!(place.projection[0], ProjectionElem::Deref)
1941            && matches!(
1942                place_ty.kind(),
1943                rustc_middle::ty::TyKind::Int(_)
1944                    | rustc_middle::ty::TyKind::Uint(_)
1945                    | rustc_middle::ty::TyKind::Bool
1946                    | rustc_middle::ty::TyKind::Char
1947                    | rustc_middle::ty::TyKind::Float(_)
1948            )
1949        {
1950            let pointer = self.local_value(place.local)?;
1951            if let Some(value) = self.read_field_allocation(pointer, place_ty) {
1952                return Some(value);
1953            }
1954            if let Some(provenance) = &pointer.provenance
1955                && provenance.offset.simplify().as_u64() == Some(0)
1956                && let Some(value) = self.load_value(provenance.alloc_id, place_ty, &[])
1957            {
1958                return Some(value.clone());
1959            }
1960            return Some(self.unknown_value_for_place(place));
1961        }
1962
1963        let field_path: Vec<usize> = place
1964            .projection
1965            .iter()
1966            .filter_map(|proj| match proj.kind() {
1967                ProjectionElem::Field(field_idx, _) => Some(field_idx.as_usize()),
1968                _ => None,
1969            })
1970            .collect();
1971
1972        // If we have a pure field path (only Field / Downcast projections),
1973        // look up in the per-field value map first.  For `Option`/`ControlFlow`,
1974        // the variant's data is stored under the same field index as the enum
1975        // field (the discriminant is tracked separately, not in the field map),
1976        // so `(x as Some).0` resolves to `x`'s field `[0]`.
1977        let is_pure_field = place.projection.iter().all(|p| {
1978            matches!(
1979                p.kind(),
1980                ProjectionElem::Field(..) | ProjectionElem::Downcast(..)
1981            )
1982        });
1983        let has_downcast = place
1984            .projection
1985            .iter()
1986            .any(|p| matches!(p.kind(), ProjectionElem::Downcast(..)));
1987        if !field_path.is_empty() && is_pure_field {
1988            if let Some(val) = self.field_value(place.local, &field_path).cloned() {
1989                return Some(val);
1990            }
1991            if let Some(base_val) = self.local_value(place.local)
1992                && self.is_len_field_read(base_val.ty, &field_path)
1993                && let Some(len) = self.len_from_value(base_val)
1994            {
1995                return Some(VmValue::new(len, place_ty));
1996            }
1997            if let Some(base_val) = self.local_value(place.local)
1998                && self.is_cap_field_read(base_val.ty, &field_path)
1999                && let Some(cap) = self.capacity_from_value(base_val)
2000            {
2001                return Some(VmValue::new(cap, place_ty));
2002            }
2003            if !has_downcast {
2004                // Fallback: when the base local has provenance, propagate it
2005                // to field accesses. This handles pointer-wrapper types (Box,
2006                // Unique, NonNull) where accessing inner pointer fields yields
2007                // the same provenance as the container.
2008                if let Some(base_val) = self.local_value(place.local)
2009                    && let Some(ref prov) = base_val.provenance
2010                    && !matches!(place_ty.kind(), TyKind::Int(_) | TyKind::Uint(_) | TyKind::Bool | TyKind::Char | TyKind::Float(_))
2011                {
2012                    return Some(VmValue {
2013                        z3_term: base_val.z3_term.clone(),
2014                        ty: place_ty,
2015                        provenance: Some(prov.clone()),
2016                        facts: base_val.facts.clone(),
2017                        source: ValueSource::None,
2018                    });
2019                }
2020                return None;
2021            }
2022            // A Downcast without a materialized field falls through to the
2023            // Deref+Field / multi-element fallback below, which returns the
2024            // base local (preserving the pre-Downcast behavior instead of
2025            // forcing a fresh value).
2026        }
2027
2028        if !field_path.is_empty()
2029            && field_path.len() < place.projection.len()
2030            && place
2031                .projection
2032                .iter()
2033                .any(|p| matches!(p.kind(), ProjectionElem::Deref))
2034        {
2035            let non_field_deref = place.projection.iter().all(|p| {
2036                matches!(
2037                    p.kind(),
2038                    ProjectionElem::Field(..)
2039                        | ProjectionElem::Deref
2040                        | ProjectionElem::Subslice { .. }
2041                )
2042            });
2043            if non_field_deref {
2044                if let Some(val) = self.field_value(place.local, &field_path).cloned() {
2045                    return Some(val);
2046                }
2047                // Resolve a Deref+Field access through the pointee allocation's
2048                // per-allocation field tracking (e.g. `(*leaf).len` → the
2049                // `LeafNode.len` field value materialized by
2050                // `decompose_pointee_fields`).  The viewed type (pointee) is part
2051                // of the key so reinterpret casts (e.g. `LeafNode` → `InternalNode`)
2052                // resolve to the right field view.
2053                if let Some(base_val) = self.local_value(place.local)
2054                    && let Some(alloc_id) = base_val.provenance_alloc_id()
2055                {
2056                    let view_ty = mir_utils::pointee_ty(base_val.ty).unwrap_or(base_val.ty);
2057                    if let Some(val) = self.load_value(alloc_id, view_ty, &field_path).cloned() {
2058                        return Some(val);
2059                    }
2060                }
2061                if let Some(base_val) = self.local_value(place.local)
2062                    && self.is_len_field_read(base_val.ty, &field_path)
2063                    && let Some(len) = self.len_from_value(base_val)
2064                {
2065                    return Some(VmValue::new(len, place_ty));
2066                }
2067                if let Some(base_val) = self.local_value(place.local)
2068                    && self.is_cap_field_read(base_val.ty, &field_path)
2069                    && let Some(cap) = self.capacity_from_value(base_val)
2070                {
2071                    return Some(VmValue::new(cap, place_ty));
2072                }
2073            }
2074        }
2075
2076        let mut base = self.local_value(place.local)?.clone();
2077        for proj in place.projection.iter() {
2078            match proj.kind() {
2079                ProjectionElem::Deref => {
2080                    base.ty = place_ty;
2081                }
2082                ProjectionElem::Field(_field_idx, _) => {
2083                    if !field_path.is_empty()
2084                        && let Some(val) = self.field_value(place.local, &field_path).cloned()
2085                    {
2086                        return Some(val);
2087                    }
2088                    base.ty = place_ty;
2089                }
2090                _ => {}
2091            }
2092        }
2093
2094        let proj = place.projection.last().expect("non-empty projection");
2095        let prefix_is_deref = place.projection[..place.projection.len() - 1]
2096            .iter()
2097            .all(|p| matches!(p.kind(), ProjectionElem::Deref));
2098        if prefix_is_deref {
2099            let index = match proj {
2100                ProjectionElem::Index(local) => self
2101                    .local_value(*local)
2102                    .and_then(|value| value.z3_term.simplify().as_u64()),
2103                ProjectionElem::ConstantIndex {
2104                    offset,
2105                    from_end: false,
2106                    ..
2107                } => Some(*offset),
2108                _ => None,
2109            };
2110            if let Some(index) = index
2111                && let Some(value) = self.field_value(place.local, &[index as usize])
2112            {
2113                return Some(value.clone());
2114            }
2115            if let ProjectionElem::Index(local) = proj
2116                && let Some(index_value) = self.local_value(*local)
2117                && matches!(
2118                    place_ty.kind(),
2119                    rustc_middle::ty::TyKind::Int(_)
2120                        | rustc_middle::ty::TyKind::Uint(_)
2121                        | rustc_middle::ty::TyKind::Bool
2122                        | rustc_middle::ty::TyKind::Char
2123                )
2124                && let rustc_middle::ty::TyKind::Array(_, length) =
2125                    self.body().local_decls[place.local].ty.kind()
2126                && let Some(length) = length.try_to_target_usize(self.tcx)
2127            {
2128                let repeated = self
2129                    .field_value(place.local, &[REPEATED_ARRAY_ELEMENT])
2130                    .cloned();
2131                let elements = if repeated.is_some() {
2132                    self.field_paths(place.local)
2133                        .into_iter()
2134                        .filter_map(|path| {
2135                            (path.len() == 1
2136                                && path[0] < length as usize
2137                                && path[0] != REPEATED_ARRAY_ELEMENT)
2138                                .then(|| {
2139                                    self.field_value(place.local, &path)
2140                                        .cloned()
2141                                        .map(|value| (path[0], value))
2142                                })
2143                                .flatten()
2144                        })
2145                        .collect::<Vec<_>>()
2146                } else {
2147                    (0..length)
2148                        .filter_map(|index| {
2149                            self.field_value(place.local, &[index as usize])
2150                                .cloned()
2151                                .map(|value| (index as usize, value))
2152                        })
2153                        .collect::<Vec<_>>()
2154                };
2155                if repeated.is_some() || elements.len() == length as usize {
2156                    let mut term = repeated
2157                        .map(|value| value.z3_term)
2158                        .unwrap_or_else(|| self.fresh_int("array_index"));
2159                    for (index, element) in elements {
2160                        let selected = index_value
2161                            .z3_term
2162                            ._eq(&Int::from_u64(self.z3_ctx, index as u64));
2163                        term = selected.ite(&element.z3_term, &term);
2164                    }
2165                    return Some(VmValue::new(term, place_ty));
2166                }
2167            }
2168        }
2169        if let ProjectionElem::Index(local) = proj {
2170            if prefix_is_deref && let Some(ref prov) = base.provenance {
2171                let alloc_id = prov.alloc_id;
2172                // The base's type may have been overwritten to the
2173                // element type by the Deref strip above; recover the
2174                // pointee element type from the base local's declared
2175                // type (`&[u8]` → `u8`, `&[T; N]` → `T`).
2176                let decl_ty = self.body().local_decls[place.local].ty;
2177                let inner_ty = match decl_ty.kind() {
2178                    rustc_middle::ty::TyKind::Array(inner, _) => *inner,
2179                    rustc_middle::ty::TyKind::Ref(_, inner, _) => match inner.kind() {
2180                        rustc_middle::ty::TyKind::Slice(e) => *e,
2181                        _ => return Some(base.clone()),
2182                    },
2183                    rustc_middle::ty::TyKind::Slice(e) => *e,
2184                    _ => return Some(base.clone()),
2185                };
2186                let elem_sz = self.size_of_ty(inner_ty) as usize;
2187                let step = elem_sz.max(1);
2188                if let Some(index_val) = self.local_value(*local) {
2189                    let offset = Int::mul(
2190                        self.z3_ctx,
2191                        &[&index_val.z3_term, &Int::from_u64(self.z3_ctx, step as u64)],
2192                    );
2193                    // Byte-level tracking only exists once some byte of the
2194                    // allocation has been written; otherwise fall through to
2195                    // the field→byte materialization below.  Even when the
2196                    // allocation has a byte array, the byte may still read
2197                    // `UNINIT` (e.g. a struct whose fields were written in
2198                    // the value layer only), so also fall through to the
2199                    // field→byte materialization in that case.
2200                    if self.path_state.mem_units[alloc_id.0].content.byte_array.is_some() {
2201                        let term = self.byte_read(alloc_id, &offset);
2202                        let is_uninit = offset
2203                            .simplify()
2204                            .as_u64()
2205                            .map(|off| !self.is_byte_init(alloc_id, off as usize))
2206                            .unwrap_or(false);
2207                        if !is_uninit {
2208                            return Some(VmValue {
2209                                z3_term: term,
2210                                ty: place_ty,
2211                                provenance: None,
2212                                facts: ValueFacts::default(),
2213                                source: ValueSource::None,
2214                            });
2215                        }
2216                    }
2217                    // Field→byte direction of the cast cross-view
2218                    // materialization: the buffer was reinterpreted from a
2219                    // struct whose scalar fields were written in the value
2220                    // layer, so read the byte back out of the field value.
2221                    if let Some(off) = offset.simplify().as_u64()
2222                        && let Some(ty) = self.alloc(alloc_id).element_ty.as_ty()
2223                        && let Some(b) = self.byte_from_field(alloc_id, ty, off as usize)
2224                    {
2225                        return Some(VmValue {
2226                            z3_term: b,
2227                            ty: place_ty,
2228                            provenance: None,
2229                            facts: ValueFacts::default(),
2230                            source: ValueSource::None,
2231                        });
2232                    }
2233                }
2234            }
2235            return Some(self.unknown_value_for_place(place));
2236        }
2237        if !field_path.is_empty()
2238            && matches!(place_ty.kind(), TyKind::Int(_) | TyKind::Uint(_) | TyKind::Bool | TyKind::Char | TyKind::Float(_))
2239        {
2240            return Some(self.unknown_value_for_place(place));
2241        }
2242        let mut val = base;
2243        val.ty = place_ty;
2244        Some(val)
2245    }
2246
2247    /// Whether `field_path` selects a length field.
2248    fn is_len_field_read(&self, ty: Ty<'tcx>, field_path: &[usize]) -> bool {
2249        if field_path.is_empty() {
2250            return false;
2251        }
2252        let mut view_ty = match ty.kind() {
2253            rustc_middle::ty::TyKind::Ref(_, inner, _)
2254            | rustc_middle::ty::TyKind::RawPtr(inner, _) => match inner.kind() {
2255                rustc_middle::ty::TyKind::Slice(_) | rustc_middle::ty::TyKind::Str => {
2256                    return field_path == [1];
2257                }
2258                rustc_middle::ty::TyKind::Adt(..) => *inner,
2259                _ => return false,
2260            },
2261            rustc_middle::ty::TyKind::Adt(..) => ty,
2262            _ => return false,
2263        };
2264        if field_path.len() > 1
2265            && !matches!(view_ty.kind(), TyKind::Adt(adt, _) if type_ids::is_std_string(adt.did()))
2266        {
2267            return false;
2268        }
2269        for (index, &field_idx) in field_path.iter().enumerate() {
2270            let TyKind::Adt(adt, substs) = view_ty.kind() else {
2271                return false;
2272            };
2273            if !adt.is_struct() {
2274                return false;
2275            }
2276            let Some(field) = adt
2277                .non_enum_variant()
2278                .fields
2279                .get(rustc_abi::FieldIdx::from_usize(field_idx))
2280            else {
2281                return false;
2282            };
2283            if index + 1 == field_path.len() {
2284                return field.name.as_str() == "len";
2285            }
2286            view_ty = mir_utils::field_ty(self.tcx, field, substs);
2287        }
2288        false
2289    }
2290
2291    pub(super) fn is_cap_field_read(&self, ty: Ty<'tcx>, field_path: &[usize]) -> bool {
2292        if field_path.is_empty() {
2293            return false;
2294        }
2295        let mut view_ty = match ty.kind() {
2296            TyKind::Ref(_, inner, _) | TyKind::RawPtr(inner, _) => *inner,
2297            _ => ty,
2298        };
2299        if !matches!(view_ty.kind(), TyKind::Adt(adt, _) if type_ids::is_std_vec(adt.did()) || type_ids::is_std_string(adt.did()))
2300        {
2301            return false;
2302        }
2303        for (index, &field_idx) in field_path.iter().enumerate() {
2304            let TyKind::Adt(adt, substs) = view_ty.kind() else {
2305                return false;
2306            };
2307            let Some(field) = adt
2308                .non_enum_variant()
2309                .fields
2310                .get(rustc_abi::FieldIdx::from_usize(field_idx))
2311            else {
2312                return false;
2313            };
2314            if index + 1 == field_path.len() {
2315                return field.name.as_str() == "cap";
2316            }
2317            view_ty = mir_utils::field_ty(self.tcx, field, substs);
2318        }
2319        false
2320    }
2321
2322    /// Create an unknown value for a place.
2323    ///
2324    /// The value carries no `non_null` (or any other) assumption: a raw pointer
2325    /// whose provenance was lost may still be null, so assuming non-null here
2326    /// would let `NonNull`/null-guard checks pass unsoundly.
2327    pub(crate) fn unknown_value_for_place(&self, place: &Place<'tcx>) -> VmValue<'z3, 'tcx> {
2328        let ty = place.ty(self.body(), self.tcx).ty;
2329        VmValue::new(self.fresh_int("unknown"), ty)
2330    }
2331}