rustc_mir_transform/
gvn.rs

1//! Global value numbering.
2//!
3//! MIR may contain repeated and/or redundant computations. The objective of this pass is to detect
4//! such redundancies and re-use the already-computed result when possible.
5//!
6//! From those assignments, we construct a mapping `VnIndex -> Vec<(Local, Location)>` of available
7//! values, the locals in which they are stored, and the assignment location.
8//!
9//! We traverse all assignments `x = rvalue` and operands.
10//!
11//! For each SSA one, we compute a symbolic representation of values that are assigned to SSA
12//! locals. This symbolic representation is defined by the `Value` enum. Each produced instance of
13//! `Value` is interned as a `VnIndex`, which allows us to cheaply compute identical values.
14//!
15//! For each non-SSA
16//! one, we compute the `VnIndex` of the rvalue. If this `VnIndex` is associated to a constant, we
17//! replace the rvalue/operand by that constant. Otherwise, if there is an SSA local `y`
18//! associated to this `VnIndex`, and if its definition location strictly dominates the assignment
19//! to `x`, we replace the assignment by `x = y`.
20//!
21//! By opportunity, this pass simplifies some `Rvalue`s based on the accumulated knowledge.
22//!
23//! # Operational semantic
24//!
25//! Operationally, this pass attempts to prove bitwise equality between locals. Given this MIR:
26//! ```ignore (MIR)
27//! _a = some value // has VnIndex i
28//! // some MIR
29//! _b = some other value // also has VnIndex i
30//! ```
31//!
32//! We consider it to be replaceable by:
33//! ```ignore (MIR)
34//! _a = some value // has VnIndex i
35//! // some MIR
36//! _c = some other value // also has VnIndex i
37//! assume(_a bitwise equal to _c) // follows from having the same VnIndex
38//! _b = _a // follows from the `assume`
39//! ```
40//!
41//! Which is simplifiable to:
42//! ```ignore (MIR)
43//! _a = some value // has VnIndex i
44//! // some MIR
45//! _b = _a
46//! ```
47//!
48//! # Handling of references
49//!
50//! We handle references by assigning a different "provenance" index to each Ref/RawPtr rvalue.
51//! This ensure that we do not spuriously merge borrows that should not be merged. Meanwhile, we
52//! consider all the derefs of an immutable reference to a freeze type to give the same value:
53//! ```ignore (MIR)
54//! _a = *_b // _b is &Freeze
55//! _c = *_b // replaced by _c = _a
56//! ```
57//!
58//! # Determinism of constant propagation
59//!
60//! When registering a new `Value`, we attempt to opportunistically evaluate it as a constant.
61//! The evaluated form is inserted in `evaluated` as an `OpTy` or `None` if evaluation failed.
62//!
63//! The difficulty is non-deterministic evaluation of MIR constants. Some `Const` can have
64//! different runtime values each time they are evaluated. This is the case with
65//! `Const::Slice` which have a new pointer each time they are evaluated, and constants that
66//! contain a fn pointer (`AllocId` pointing to a `GlobalAlloc::Function`) pointing to a different
67//! symbol in each codegen unit.
68//!
69//! Meanwhile, we want to be able to read indirect constants. For instance:
70//! ```
71//! static A: &'static &'static u8 = &&63;
72//! fn foo() -> u8 {
73//!     **A // We want to replace by 63.
74//! }
75//! fn bar() -> u8 {
76//!     b"abc"[1] // We want to replace by 'b'.
77//! }
78//! ```
79//!
80//! The `Value::Constant` variant stores a possibly unevaluated constant. Evaluating that constant
81//! may be non-deterministic. When that happens, we assign a disambiguator to ensure that we do not
82//! merge the constants. See `duplicate_slice` test in `gvn.rs`.
83//!
84//! Second, when writing constants in MIR, we do not write `Const::Slice` or `Const`
85//! that contain `AllocId`s.
86
87use std::borrow::Cow;
88use std::hash::{Hash, Hasher};
89
90use either::Either;
91use hashbrown::hash_table::{Entry, HashTable};
92use itertools::Itertools as _;
93use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT, FieldIdx, Primitive, Size, VariantIdx};
94use rustc_arena::DroplessArena;
95use rustc_const_eval::const_eval::DummyMachine;
96use rustc_const_eval::interpret::{
97    ImmTy, Immediate, InterpCx, MemPlaceMeta, MemoryKind, OpTy, Projectable, Scalar,
98    intern_const_alloc_for_constprop,
99};
100use rustc_data_structures::fx::FxHasher;
101use rustc_data_structures::graph::dominators::Dominators;
102use rustc_hir::def::DefKind;
103use rustc_index::bit_set::DenseBitSet;
104use rustc_index::{IndexVec, newtype_index};
105use rustc_middle::bug;
106use rustc_middle::mir::interpret::GlobalAlloc;
107use rustc_middle::mir::visit::*;
108use rustc_middle::mir::*;
109use rustc_middle::ty::layout::HasTypingEnv;
110use rustc_middle::ty::{self, Ty, TyCtxt};
111use rustc_span::DUMMY_SP;
112use smallvec::SmallVec;
113use tracing::{debug, instrument, trace};
114
115use crate::ssa::SsaLocals;
116
117pub(super) struct GVN;
118
119impl<'tcx> crate::MirPass<'tcx> for GVN {
120    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
121        sess.mir_opt_level() >= 2
122    }
123
124    #[instrument(level = "trace", skip(self, tcx, body))]
125    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
126        debug!(def_id = ?body.source.def_id());
127
128        let typing_env = body.typing_env(tcx);
129        let ssa = SsaLocals::new(tcx, body, typing_env);
130        // Clone dominators because we need them while mutating the body.
131        let dominators = body.basic_blocks.dominators().clone();
132
133        let arena = DroplessArena::default();
134        let mut state =
135            VnState::new(tcx, body, typing_env, &ssa, dominators, &body.local_decls, &arena);
136
137        for local in body.args_iter().filter(|&local| ssa.is_ssa(local)) {
138            let opaque = state.new_opaque(body.local_decls[local].ty);
139            state.assign(local, opaque);
140        }
141
142        let reverse_postorder = body.basic_blocks.reverse_postorder().to_vec();
143        for bb in reverse_postorder {
144            let data = &mut body.basic_blocks.as_mut_preserves_cfg()[bb];
145            state.visit_basic_block_data(bb, data);
146        }
147
148        // For each local that is reused (`y` above), we remove its storage statements do avoid any
149        // difficulty. Those locals are SSA, so should be easy to optimize by LLVM without storage
150        // statements.
151        StorageRemover { tcx, reused_locals: state.reused_locals }.visit_body_preserves_cfg(body);
152    }
153
154    fn is_required(&self) -> bool {
155        false
156    }
157}
158
159newtype_index! {
160    /// This represents a `Value` in the symbolic execution.
161    #[debug_format = "_v{}"]
162    struct VnIndex {}
163}
164
165/// Marker type to forbid hashing and comparing opaque values.
166/// This struct should only be constructed by `ValueSet::insert_unique` to ensure we use that
167/// method to create non-unifiable values. It will ICE if used in `ValueSet::insert`.
168#[derive(Copy, Clone, Debug, Eq)]
169struct VnOpaque;
170impl PartialEq for VnOpaque {
171    fn eq(&self, _: &VnOpaque) -> bool {
172        // ICE if we try to compare unique values
173        unreachable!()
174    }
175}
176impl Hash for VnOpaque {
177    fn hash<T: Hasher>(&self, _: &mut T) {
178        // ICE if we try to hash unique values
179        unreachable!()
180    }
181}
182
183#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
184enum AddressKind {
185    Ref(BorrowKind),
186    Address(RawPtrKind),
187}
188
189#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
190enum AddressBase {
191    /// This address is based on this local.
192    Local(Local),
193    /// This address is based on the deref of this pointer.
194    Deref(VnIndex),
195}
196
197#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
198enum Value<'a, 'tcx> {
199    // Root values.
200    /// Used to represent values we know nothing about.
201    /// The `usize` is a counter incremented by `new_opaque`.
202    Opaque(VnOpaque),
203    /// Evaluated or unevaluated constant value.
204    Constant {
205        value: Const<'tcx>,
206        /// Some constants do not have a deterministic value. To avoid merging two instances of the
207        /// same `Const`, we assign them an additional integer index.
208        // `disambiguator` is `None` iff the constant is deterministic.
209        disambiguator: Option<VnOpaque>,
210    },
211
212    // Aggregates.
213    /// An aggregate value, either tuple/closure/struct/enum.
214    /// This does not contain unions, as we cannot reason with the value.
215    Aggregate(VariantIdx, &'a [VnIndex]),
216    /// A union aggregate value.
217    Union(FieldIdx, VnIndex),
218    /// A raw pointer aggregate built from a thin pointer and metadata.
219    RawPtr {
220        /// Thin pointer component. This is field 0 in MIR.
221        pointer: VnIndex,
222        /// Metadata component. This is field 1 in MIR.
223        metadata: VnIndex,
224    },
225    /// This corresponds to a `[value; count]` expression.
226    Repeat(VnIndex, ty::Const<'tcx>),
227    /// The address of a place.
228    Address {
229        base: AddressBase,
230        // We do not use a plain `Place` as we want to be able to reason about indices.
231        // This does not contain any `Deref` projection.
232        projection: &'a [ProjectionElem<VnIndex, Ty<'tcx>>],
233        kind: AddressKind,
234        /// Give each borrow and pointer a different provenance, so we don't merge them.
235        provenance: VnOpaque,
236    },
237
238    // Extractions.
239    /// This is the *value* obtained by projecting another value.
240    Projection(VnIndex, ProjectionElem<VnIndex, ()>),
241    /// Discriminant of the given value.
242    Discriminant(VnIndex),
243
244    // Operations.
245    NullaryOp(NullOp<'tcx>, Ty<'tcx>),
246    UnaryOp(UnOp, VnIndex),
247    BinaryOp(BinOp, VnIndex, VnIndex),
248    Cast {
249        kind: CastKind,
250        value: VnIndex,
251    },
252}
253
254/// Stores and deduplicates pairs of `(Value, Ty)` into in `VnIndex` numbered values.
255///
256/// This data structure is mostly a partial reimplementation of `FxIndexMap<VnIndex, (Value, Ty)>`.
257/// We do not use a regular `FxIndexMap` to skip hashing values that are unique by construction,
258/// like opaque values, address with provenance and non-deterministic constants.
259struct ValueSet<'a, 'tcx> {
260    indices: HashTable<VnIndex>,
261    hashes: IndexVec<VnIndex, u64>,
262    values: IndexVec<VnIndex, Value<'a, 'tcx>>,
263    types: IndexVec<VnIndex, Ty<'tcx>>,
264}
265
266impl<'a, 'tcx> ValueSet<'a, 'tcx> {
267    fn new(num_values: usize) -> ValueSet<'a, 'tcx> {
268        ValueSet {
269            indices: HashTable::with_capacity(num_values),
270            hashes: IndexVec::with_capacity(num_values),
271            values: IndexVec::with_capacity(num_values),
272            types: IndexVec::with_capacity(num_values),
273        }
274    }
275
276    /// Insert a `(Value, Ty)` pair without hashing or deduplication.
277    /// This always creates a new `VnIndex`.
278    #[inline]
279    fn insert_unique(
280        &mut self,
281        ty: Ty<'tcx>,
282        value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
283    ) -> VnIndex {
284        let value = value(VnOpaque);
285
286        debug_assert!(match value {
287            Value::Opaque(_) | Value::Address { .. } => true,
288            Value::Constant { disambiguator, .. } => disambiguator.is_some(),
289            _ => false,
290        });
291
292        let index = self.hashes.push(0);
293        let _index = self.types.push(ty);
294        debug_assert_eq!(index, _index);
295        let _index = self.values.push(value);
296        debug_assert_eq!(index, _index);
297        index
298    }
299
300    /// Insert a `(Value, Ty)` pair to be deduplicated.
301    /// Returns `true` as second tuple field if this value did not exist previously.
302    #[allow(rustc::pass_by_value)] // closures take `&VnIndex`
303    fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> (VnIndex, bool) {
304        debug_assert!(match value {
305            Value::Opaque(_) | Value::Address { .. } => false,
306            Value::Constant { disambiguator, .. } => disambiguator.is_none(),
307            _ => true,
308        });
309
310        let hash: u64 = {
311            let mut h = FxHasher::default();
312            value.hash(&mut h);
313            ty.hash(&mut h);
314            h.finish()
315        };
316
317        let eq = |index: &VnIndex| self.values[*index] == value && self.types[*index] == ty;
318        let hasher = |index: &VnIndex| self.hashes[*index];
319        match self.indices.entry(hash, eq, hasher) {
320            Entry::Occupied(entry) => {
321                let index = *entry.get();
322                (index, false)
323            }
324            Entry::Vacant(entry) => {
325                let index = self.hashes.push(hash);
326                entry.insert(index);
327                let _index = self.values.push(value);
328                debug_assert_eq!(index, _index);
329                let _index = self.types.push(ty);
330                debug_assert_eq!(index, _index);
331                (index, true)
332            }
333        }
334    }
335
336    /// Return the `Value` associated with the given `VnIndex`.
337    #[inline]
338    fn value(&self, index: VnIndex) -> Value<'a, 'tcx> {
339        self.values[index]
340    }
341
342    /// Return the type associated with the given `VnIndex`.
343    #[inline]
344    fn ty(&self, index: VnIndex) -> Ty<'tcx> {
345        self.types[index]
346    }
347
348    /// Replace the value associated with `index` with an opaque value.
349    #[inline]
350    fn forget(&mut self, index: VnIndex) {
351        self.values[index] = Value::Opaque(VnOpaque);
352    }
353}
354
355struct VnState<'body, 'a, 'tcx> {
356    tcx: TyCtxt<'tcx>,
357    ecx: InterpCx<'tcx, DummyMachine>,
358    local_decls: &'body LocalDecls<'tcx>,
359    is_coroutine: bool,
360    /// Value stored in each local.
361    locals: IndexVec<Local, Option<VnIndex>>,
362    /// Locals that are assigned that value.
363    // This vector does not hold all the values of `VnIndex` that we create.
364    rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
365    values: ValueSet<'a, 'tcx>,
366    /// Values evaluated as constants if possible.
367    /// - `None` are values not computed yet;
368    /// - `Some(None)` are values for which computation has failed;
369    /// - `Some(Some(op))` are successful computations.
370    evaluated: IndexVec<VnIndex, Option<Option<&'a OpTy<'tcx>>>>,
371    /// Cache the deref values.
372    derefs: Vec<VnIndex>,
373    ssa: &'body SsaLocals,
374    dominators: Dominators<BasicBlock>,
375    reused_locals: DenseBitSet<Local>,
376    arena: &'a DroplessArena,
377}
378
379impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> {
380    fn new(
381        tcx: TyCtxt<'tcx>,
382        body: &Body<'tcx>,
383        typing_env: ty::TypingEnv<'tcx>,
384        ssa: &'body SsaLocals,
385        dominators: Dominators<BasicBlock>,
386        local_decls: &'body LocalDecls<'tcx>,
387        arena: &'a DroplessArena,
388    ) -> Self {
389        // Compute a rough estimate of the number of values in the body from the number of
390        // statements. This is meant to reduce the number of allocations, but it's all right if
391        // we miss the exact amount. We estimate based on 2 values per statement (one in LHS and
392        // one in RHS) and 4 values per terminator (for call operands).
393        let num_values =
394            2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
395                + 4 * body.basic_blocks.len();
396        VnState {
397            tcx,
398            ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
399            local_decls,
400            is_coroutine: body.coroutine.is_some(),
401            locals: IndexVec::from_elem(None, local_decls),
402            rev_locals: IndexVec::with_capacity(num_values),
403            values: ValueSet::new(num_values),
404            evaluated: IndexVec::with_capacity(num_values),
405            derefs: Vec::new(),
406            ssa,
407            dominators,
408            reused_locals: DenseBitSet::new_empty(local_decls.len()),
409            arena,
410        }
411    }
412
413    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
414        self.ecx.typing_env()
415    }
416
417    #[instrument(level = "trace", skip(self), ret)]
418    fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
419        let (index, new) = self.values.insert(ty, value);
420        if new {
421            // Grow `evaluated` and `rev_locals` here to amortize the allocations.
422            let _index = self.evaluated.push(None);
423            debug_assert_eq!(index, _index);
424            let _index = self.rev_locals.push(SmallVec::new());
425            debug_assert_eq!(index, _index);
426        }
427        index
428    }
429
430    /// Create a new `Value` for which we have no information at all, except that it is distinct
431    /// from all the others.
432    #[instrument(level = "trace", skip(self), ret)]
433    fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
434        let index = self.values.insert_unique(ty, Value::Opaque);
435        let _index = self.evaluated.push(Some(None));
436        debug_assert_eq!(index, _index);
437        let _index = self.rev_locals.push(SmallVec::new());
438        debug_assert_eq!(index, _index);
439        index
440    }
441
442    /// Create a new `Value::Address` distinct from all the others.
443    #[instrument(level = "trace", skip(self), ret)]
444    fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
445        let pty = place.ty(self.local_decls, self.tcx).ty;
446        let ty = match kind {
447            AddressKind::Ref(bk) => {
448                Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
449            }
450            AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
451        };
452
453        let mut projection = place.projection.iter();
454        let base = if place.is_indirect_first_projection() {
455            let base = self.locals[place.local]?;
456            // Skip the initial `Deref`.
457            projection.next();
458            AddressBase::Deref(base)
459        } else {
460            AddressBase::Local(place.local)
461        };
462        // Do not try evaluating inside `Index`, this has been done by `simplify_place_projection`.
463        let projection =
464            projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
465        let projection = self.arena.try_alloc_from_iter(projection).ok()?;
466
467        let index = self.values.insert_unique(ty, |provenance| Value::Address {
468            base,
469            projection,
470            kind,
471            provenance,
472        });
473        let _index = self.evaluated.push(None);
474        debug_assert_eq!(index, _index);
475        let _index = self.rev_locals.push(SmallVec::new());
476        debug_assert_eq!(index, _index);
477
478        Some(index)
479    }
480
481    #[instrument(level = "trace", skip(self), ret)]
482    fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
483        let (index, new) = if value.is_deterministic() {
484            // The constant is deterministic, no need to disambiguate.
485            let constant = Value::Constant { value, disambiguator: None };
486            self.values.insert(value.ty(), constant)
487        } else {
488            // Multiple mentions of this constant will yield different values,
489            // so assign a different `disambiguator` to ensure they do not get the same `VnIndex`.
490            let index = self.values.insert_unique(value.ty(), |disambiguator| Value::Constant {
491                value,
492                disambiguator: Some(disambiguator),
493            });
494            (index, true)
495        };
496        if new {
497            let _index = self.evaluated.push(None);
498            debug_assert_eq!(index, _index);
499            let _index = self.rev_locals.push(SmallVec::new());
500            debug_assert_eq!(index, _index);
501        }
502        index
503    }
504
505    #[inline]
506    fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
507        self.values.value(index)
508    }
509
510    #[inline]
511    fn ty(&self, index: VnIndex) -> Ty<'tcx> {
512        self.values.ty(index)
513    }
514
515    /// Record that `local` is assigned `value`. `local` must be SSA.
516    #[instrument(level = "trace", skip(self))]
517    fn assign(&mut self, local: Local, value: VnIndex) {
518        debug_assert!(self.ssa.is_ssa(local));
519        self.locals[local] = Some(value);
520        self.rev_locals[value].push(local);
521    }
522
523    fn insert_bool(&mut self, flag: bool) -> VnIndex {
524        // Booleans are deterministic.
525        let value = Const::from_bool(self.tcx, flag);
526        debug_assert!(value.is_deterministic());
527        self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
528    }
529
530    fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
531        // Scalars are deterministic.
532        let value = Const::from_scalar(self.tcx, scalar, ty);
533        debug_assert!(value.is_deterministic());
534        self.insert(ty, Value::Constant { value, disambiguator: None })
535    }
536
537    fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
538        self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
539    }
540
541    fn insert_deref(&mut self, ty: Ty<'tcx>, value: VnIndex) -> VnIndex {
542        let value = self.insert(ty, Value::Projection(value, ProjectionElem::Deref));
543        self.derefs.push(value);
544        value
545    }
546
547    fn invalidate_derefs(&mut self) {
548        for deref in std::mem::take(&mut self.derefs) {
549            self.values.forget(deref);
550        }
551    }
552
553    #[instrument(level = "trace", skip(self), ret)]
554    fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
555        use Value::*;
556        let ty = self.ty(value);
557        // Avoid computing layouts inside a coroutine, as that can cause cycles.
558        let ty = if !self.is_coroutine || ty.is_scalar() {
559            self.ecx.layout_of(ty).ok()?
560        } else {
561            return None;
562        };
563        let op = match self.get(value) {
564            _ if ty.is_zst() => ImmTy::uninit(ty).into(),
565
566            Opaque(_) => return None,
567            // Do not bother evaluating repeat expressions. This would uselessly consume memory.
568            Repeat(..) => return None,
569
570            Constant { ref value, disambiguator: _ } => {
571                self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
572            }
573            Aggregate(variant, ref fields) => {
574                let fields =
575                    fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
576                let variant = if ty.ty.is_enum() { Some(variant) } else { None };
577                if matches!(ty.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
578                {
579                    let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
580                    let variant_dest = if let Some(variant) = variant {
581                        self.ecx.project_downcast(&dest, variant).discard_err()?
582                    } else {
583                        dest.clone()
584                    };
585                    for (field_index, op) in fields.into_iter().enumerate() {
586                        let field_dest = self
587                            .ecx
588                            .project_field(&variant_dest, FieldIdx::from_usize(field_index))
589                            .discard_err()?;
590                        self.ecx.copy_op(op, &field_dest).discard_err()?;
591                    }
592                    self.ecx
593                        .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
594                        .discard_err()?;
595                    self.ecx
596                        .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
597                        .discard_err()?;
598                    dest.into()
599                } else {
600                    return None;
601                }
602            }
603            Union(active_field, field) => {
604                let field = self.eval_to_const(field)?;
605                if matches!(ty.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
606                {
607                    let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
608                    let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
609                    self.ecx.copy_op(field, &field_dest).discard_err()?;
610                    self.ecx
611                        .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
612                        .discard_err()?;
613                    dest.into()
614                } else {
615                    return None;
616                }
617            }
618            RawPtr { pointer, metadata } => {
619                let pointer = self.eval_to_const(pointer)?;
620                let metadata = self.eval_to_const(metadata)?;
621
622                // Pointers don't have fields, so don't `project_field` them.
623                let data = self.ecx.read_pointer(pointer).discard_err()?;
624                let meta = if metadata.layout.is_zst() {
625                    MemPlaceMeta::None
626                } else {
627                    MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
628                };
629                let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
630                ImmTy::from_immediate(ptr_imm, ty).into()
631            }
632
633            Projection(base, elem) => {
634                let base = self.eval_to_const(base)?;
635                // `Index` by constants should have been replaced by `ConstantIndex` by
636                // `simplify_place_projection`.
637                let elem = elem.try_map(|_| None, |()| ty.ty)?;
638                self.ecx.project(base, elem).discard_err()?
639            }
640            Address { base, projection, .. } => {
641                debug_assert!(!projection.contains(&ProjectionElem::Deref));
642                let pointer = match base {
643                    AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
644                    // We have no stack to point to.
645                    AddressBase::Local(_) => return None,
646                };
647                let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
648                for elem in projection {
649                    // `Index` by constants should have been replaced by `ConstantIndex` by
650                    // `simplify_place_projection`.
651                    let elem = elem.try_map(|_| None, |ty| ty)?;
652                    mplace = self.ecx.project(&mplace, elem).discard_err()?;
653                }
654                let pointer = mplace.to_ref(&self.ecx);
655                ImmTy::from_immediate(pointer, ty).into()
656            }
657
658            Discriminant(base) => {
659                let base = self.eval_to_const(base)?;
660                let variant = self.ecx.read_discriminant(base).discard_err()?;
661                let discr_value =
662                    self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
663                discr_value.into()
664            }
665            NullaryOp(null_op, arg_ty) => {
666                let arg_layout = self.ecx.layout_of(arg_ty).ok()?;
667                if let NullOp::SizeOf | NullOp::AlignOf = null_op
668                    && arg_layout.is_unsized()
669                {
670                    return None;
671                }
672                let val = match null_op {
673                    NullOp::SizeOf => arg_layout.size.bytes(),
674                    NullOp::AlignOf => arg_layout.align.bytes(),
675                    NullOp::OffsetOf(fields) => self
676                        .tcx
677                        .offset_of_subfield(self.typing_env(), arg_layout, fields.iter())
678                        .bytes(),
679                    NullOp::UbChecks => return None,
680                    NullOp::ContractChecks => return None,
681                };
682                ImmTy::from_uint(val, ty).into()
683            }
684            UnaryOp(un_op, operand) => {
685                let operand = self.eval_to_const(operand)?;
686                let operand = self.ecx.read_immediate(operand).discard_err()?;
687                let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
688                val.into()
689            }
690            BinaryOp(bin_op, lhs, rhs) => {
691                let lhs = self.eval_to_const(lhs)?;
692                let rhs = self.eval_to_const(rhs)?;
693                let lhs = self.ecx.read_immediate(lhs).discard_err()?;
694                let rhs = self.ecx.read_immediate(rhs).discard_err()?;
695                let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
696                val.into()
697            }
698            Cast { kind, value } => match kind {
699                CastKind::IntToInt | CastKind::IntToFloat => {
700                    let value = self.eval_to_const(value)?;
701                    let value = self.ecx.read_immediate(value).discard_err()?;
702                    let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
703                    res.into()
704                }
705                CastKind::FloatToFloat | CastKind::FloatToInt => {
706                    let value = self.eval_to_const(value)?;
707                    let value = self.ecx.read_immediate(value).discard_err()?;
708                    let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
709                    res.into()
710                }
711                CastKind::Transmute | CastKind::Subtype => {
712                    let value = self.eval_to_const(value)?;
713                    // `offset` for immediates generally only supports projections that match the
714                    // type of the immediate. However, as a HACK, we exploit that it can also do
715                    // limited transmutes: it only works between types with the same layout, and
716                    // cannot transmute pointers to integers.
717                    if value.as_mplace_or_imm().is_right() {
718                        let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
719                            (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
720                                s1.size(&self.ecx) == s2.size(&self.ecx)
721                                    && !matches!(s1.primitive(), Primitive::Pointer(..))
722                            }
723                            (BackendRepr::ScalarPair(a1, b1), BackendRepr::ScalarPair(a2, b2)) => {
724                                a1.size(&self.ecx) == a2.size(&self.ecx)
725                                    && b1.size(&self.ecx) == b2.size(&self.ecx)
726                                    // The alignment of the second component determines its offset, so that also needs to match.
727                                    && b1.align(&self.ecx) == b2.align(&self.ecx)
728                                    // None of the inputs may be a pointer.
729                                    && !matches!(a1.primitive(), Primitive::Pointer(..))
730                                    && !matches!(b1.primitive(), Primitive::Pointer(..))
731                            }
732                            _ => false,
733                        };
734                        if !can_transmute {
735                            return None;
736                        }
737                    }
738                    value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
739                }
740                CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
741                    let src = self.eval_to_const(value)?;
742                    let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
743                    self.ecx.unsize_into(src, ty, &dest).discard_err()?;
744                    self.ecx
745                        .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
746                        .discard_err()?;
747                    dest.into()
748                }
749                CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
750                    let src = self.eval_to_const(value)?;
751                    let src = self.ecx.read_immediate(src).discard_err()?;
752                    let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
753                    ret.into()
754                }
755                CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
756                    let src = self.eval_to_const(value)?;
757                    let src = self.ecx.read_immediate(src).discard_err()?;
758                    ImmTy::from_immediate(*src, ty).into()
759                }
760                _ => return None,
761            },
762        };
763        Some(op)
764    }
765
766    fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
767        if let Some(op) = self.evaluated[index] {
768            return op;
769        }
770        let op = self.eval_to_const_inner(index);
771        self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
772        self.evaluated[index].unwrap()
773    }
774
775    /// Represent the *value* we obtain by dereferencing an `Address` value.
776    #[instrument(level = "trace", skip(self), ret)]
777    fn dereference_address(
778        &mut self,
779        base: AddressBase,
780        projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
781    ) -> Option<VnIndex> {
782        let (mut place_ty, mut value) = match base {
783            // The base is a local, so we take the local's value and project from it.
784            AddressBase::Local(local) => {
785                let local = self.locals[local]?;
786                let place_ty = PlaceTy::from_ty(self.ty(local));
787                (place_ty, local)
788            }
789            // The base is a pointer's deref, so we introduce the implicit deref.
790            AddressBase::Deref(reborrow) => {
791                let place_ty = PlaceTy::from_ty(self.ty(reborrow));
792                self.project(place_ty, reborrow, ProjectionElem::Deref)?
793            }
794        };
795        for &proj in projection {
796            (place_ty, value) = self.project(place_ty, value, proj)?;
797        }
798        Some(value)
799    }
800
801    #[instrument(level = "trace", skip(self), ret)]
802    fn project(
803        &mut self,
804        place_ty: PlaceTy<'tcx>,
805        value: VnIndex,
806        proj: ProjectionElem<VnIndex, Ty<'tcx>>,
807    ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
808        let projection_ty = place_ty.projection_ty(self.tcx, proj);
809        let proj = match proj {
810            ProjectionElem::Deref => {
811                if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
812                    && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
813                {
814                    if let Value::Address { base, projection, .. } = self.get(value)
815                        && let Some(value) = self.dereference_address(base, projection)
816                    {
817                        return Some((projection_ty, value));
818                    }
819
820                    // An immutable borrow `_x` always points to the same value for the
821                    // lifetime of the borrow, so we can merge all instances of `*_x`.
822                    return Some((projection_ty, self.insert_deref(projection_ty.ty, value)));
823                } else {
824                    return None;
825                }
826            }
827            ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
828            ProjectionElem::Field(f, _) => match self.get(value) {
829                Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
830                Value::Union(active, field) if active == f => return Some((projection_ty, field)),
831                Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
832                    if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
833                    // This pass is not aware of control-flow, so we do not know whether the
834                    // replacement we are doing is actually reachable. We could be in any arm of
835                    // ```
836                    // match Some(x) {
837                    //     Some(y) => /* stuff */,
838                    //     None => /* other */,
839                    // }
840                    // ```
841                    //
842                    // In surface rust, the current statement would be unreachable.
843                    //
844                    // However, from the reference chapter on enums and RFC 2195,
845                    // accessing the wrong variant is not UB if the enum has repr.
846                    // So it's not impossible for a series of MIR opts to generate
847                    // a downcast to an inactive variant.
848                    && written_variant == read_variant =>
849                {
850                    return Some((projection_ty, fields[f.as_usize()]));
851                }
852                _ => ProjectionElem::Field(f, ()),
853            },
854            ProjectionElem::Index(idx) => {
855                if let Value::Repeat(inner, _) = self.get(value) {
856                    return Some((projection_ty, inner));
857                }
858                ProjectionElem::Index(idx)
859            }
860            ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
861                match self.get(value) {
862                    Value::Repeat(inner, _) => {
863                        return Some((projection_ty, inner));
864                    }
865                    Value::Aggregate(_, operands) => {
866                        let offset = if from_end {
867                            operands.len() - offset as usize
868                        } else {
869                            offset as usize
870                        };
871                        let value = operands.get(offset).copied()?;
872                        return Some((projection_ty, value));
873                    }
874                    _ => {}
875                };
876                ProjectionElem::ConstantIndex { offset, min_length, from_end }
877            }
878            ProjectionElem::Subslice { from, to, from_end } => {
879                ProjectionElem::Subslice { from, to, from_end }
880            }
881            ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
882            ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
883        };
884
885        let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
886        Some((projection_ty, value))
887    }
888
889    /// Simplify the projection chain if we know better.
890    #[instrument(level = "trace", skip(self))]
891    fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
892        // If the projection is indirect, we treat the local as a value, so can replace it with
893        // another local.
894        if place.is_indirect_first_projection()
895            && let Some(base) = self.locals[place.local]
896            && let Some(new_local) = self.try_as_local(base, location)
897            && place.local != new_local
898        {
899            place.local = new_local;
900            self.reused_locals.insert(new_local);
901        }
902
903        let mut projection = Cow::Borrowed(&place.projection[..]);
904
905        for i in 0..projection.len() {
906            let elem = projection[i];
907            if let ProjectionElem::Index(idx_local) = elem
908                && let Some(idx) = self.locals[idx_local]
909            {
910                if let Some(offset) = self.eval_to_const(idx)
911                    && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
912                    && let Some(min_length) = offset.checked_add(1)
913                {
914                    projection.to_mut()[i] =
915                        ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
916                } else if let Some(new_idx_local) = self.try_as_local(idx, location)
917                    && idx_local != new_idx_local
918                {
919                    projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
920                    self.reused_locals.insert(new_idx_local);
921                }
922            }
923        }
924
925        if projection.is_owned() {
926            place.projection = self.tcx.mk_place_elems(&projection);
927        }
928
929        trace!(?place);
930    }
931
932    /// Represent the *value* which would be read from `place`. If we succeed, return it.
933    /// If we fail, return a `PlaceRef` that contains the same value.
934    #[instrument(level = "trace", skip(self), ret)]
935    fn compute_place_value(
936        &mut self,
937        place: Place<'tcx>,
938        location: Location,
939    ) -> Result<VnIndex, PlaceRef<'tcx>> {
940        // Invariant: `place` and `place_ref` point to the same value, even if they point to
941        // different memory locations.
942        let mut place_ref = place.as_ref();
943
944        // Invariant: `value` holds the value up-to the `index`th projection excluded.
945        let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
946        // Invariant: `value` has type `place_ty`, with optional downcast variant if needed.
947        let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
948        for (index, proj) in place.projection.iter().enumerate() {
949            if let Some(local) = self.try_as_local(value, location) {
950                // Both `local` and `Place { local: place.local, projection: projection[..index] }`
951                // hold the same value. Therefore, following place holds the value in the original
952                // `place`.
953                place_ref = PlaceRef { local, projection: &place.projection[index..] };
954            }
955
956            let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
957                return Err(place_ref);
958            };
959            let Some(ty_and_value) = self.project(place_ty, value, proj) else {
960                return Err(place_ref);
961            };
962            (place_ty, value) = ty_and_value;
963        }
964
965        Ok(value)
966    }
967
968    /// Represent the *value* which would be read from `place`, and point `place` to a preexisting
969    /// place with the same value (if that already exists).
970    #[instrument(level = "trace", skip(self), ret)]
971    fn simplify_place_value(
972        &mut self,
973        place: &mut Place<'tcx>,
974        location: Location,
975    ) -> Option<VnIndex> {
976        self.simplify_place_projection(place, location);
977
978        match self.compute_place_value(*place, location) {
979            Ok(value) => {
980                if let Some(new_place) = self.try_as_place(value, location, true)
981                    && (new_place.local != place.local
982                        || new_place.projection.len() < place.projection.len())
983                {
984                    *place = new_place;
985                    self.reused_locals.insert(new_place.local);
986                }
987                Some(value)
988            }
989            Err(place_ref) => {
990                if place_ref.local != place.local
991                    || place_ref.projection.len() < place.projection.len()
992                {
993                    // By the invariant on `place_ref`.
994                    *place = place_ref.project_deeper(&[], self.tcx);
995                    self.reused_locals.insert(place_ref.local);
996                }
997                None
998            }
999        }
1000    }
1001
1002    #[instrument(level = "trace", skip(self), ret)]
1003    fn simplify_operand(
1004        &mut self,
1005        operand: &mut Operand<'tcx>,
1006        location: Location,
1007    ) -> Option<VnIndex> {
1008        match *operand {
1009            Operand::Constant(ref constant) => Some(self.insert_constant(constant.const_)),
1010            Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
1011                let value = self.simplify_place_value(place, location)?;
1012                if let Some(const_) = self.try_as_constant(value) {
1013                    *operand = Operand::Constant(Box::new(const_));
1014                }
1015                Some(value)
1016            }
1017        }
1018    }
1019
1020    #[instrument(level = "trace", skip(self), ret)]
1021    fn simplify_rvalue(
1022        &mut self,
1023        lhs: &Place<'tcx>,
1024        rvalue: &mut Rvalue<'tcx>,
1025        location: Location,
1026    ) -> Option<VnIndex> {
1027        let value = match *rvalue {
1028            // Forward values.
1029            Rvalue::Use(ref mut operand) => return self.simplify_operand(operand, location),
1030            Rvalue::CopyForDeref(place) => {
1031                let mut operand = Operand::Copy(place);
1032                let val = self.simplify_operand(&mut operand, location);
1033                *rvalue = Rvalue::Use(operand);
1034                return val;
1035            }
1036
1037            // Roots.
1038            Rvalue::Repeat(ref mut op, amount) => {
1039                let op = self.simplify_operand(op, location)?;
1040                Value::Repeat(op, amount)
1041            }
1042            Rvalue::NullaryOp(op, ty) => Value::NullaryOp(op, ty),
1043            Rvalue::Aggregate(..) => return self.simplify_aggregate(lhs, rvalue, location),
1044            Rvalue::Ref(_, borrow_kind, ref mut place) => {
1045                self.simplify_place_projection(place, location);
1046                return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1047            }
1048            Rvalue::RawPtr(mutbl, ref mut place) => {
1049                self.simplify_place_projection(place, location);
1050                return self.new_pointer(*place, AddressKind::Address(mutbl));
1051            }
1052            Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1053                let value = self.simplify_operand(op, location)?;
1054                Value::Cast { kind: CastKind::Transmute, value }
1055            }
1056
1057            // Operations.
1058            Rvalue::Cast(ref mut kind, ref mut value, to) => {
1059                return self.simplify_cast(kind, value, to, location);
1060            }
1061            Rvalue::BinaryOp(op, box (ref mut lhs, ref mut rhs)) => {
1062                return self.simplify_binary(op, lhs, rhs, location);
1063            }
1064            Rvalue::UnaryOp(op, ref mut arg_op) => {
1065                return self.simplify_unary(op, arg_op, location);
1066            }
1067            Rvalue::Discriminant(ref mut place) => {
1068                let place = self.simplify_place_value(place, location)?;
1069                if let Some(discr) = self.simplify_discriminant(place) {
1070                    return Some(discr);
1071                }
1072                Value::Discriminant(place)
1073            }
1074
1075            // Unsupported values.
1076            Rvalue::ThreadLocalRef(..) | Rvalue::ShallowInitBox(..) => return None,
1077        };
1078        let ty = rvalue.ty(self.local_decls, self.tcx);
1079        Some(self.insert(ty, value))
1080    }
1081
1082    fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1083        let enum_ty = self.ty(place);
1084        if enum_ty.is_enum()
1085            && let Value::Aggregate(variant, _) = self.get(place)
1086        {
1087            let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1088            return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1089        }
1090
1091        None
1092    }
1093
1094    fn try_as_place_elem(
1095        &mut self,
1096        ty: Ty<'tcx>,
1097        proj: ProjectionElem<VnIndex, ()>,
1098        loc: Location,
1099    ) -> Option<PlaceElem<'tcx>> {
1100        proj.try_map(
1101            |value| {
1102                let local = self.try_as_local(value, loc)?;
1103                self.reused_locals.insert(local);
1104                Some(local)
1105            },
1106            |()| ty,
1107        )
1108    }
1109
1110    fn simplify_aggregate_to_copy(
1111        &mut self,
1112        ty: Ty<'tcx>,
1113        variant_index: VariantIdx,
1114        fields: &[VnIndex],
1115    ) -> Option<VnIndex> {
1116        let Some(&first_field) = fields.first() else { return None };
1117        let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1118
1119        // All fields must correspond one-to-one and come from the same aggregate value.
1120        if fields.iter().enumerate().any(|(index, &v)| {
1121            if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1122                && copy_from_value == pointer
1123                && from_index.index() == index
1124            {
1125                return false;
1126            }
1127            true
1128        }) {
1129            return None;
1130        }
1131
1132        let mut copy_from_local_value = copy_from_value;
1133        if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1134            && let ProjectionElem::Downcast(_, read_variant) = proj
1135        {
1136            if variant_index == read_variant {
1137                // When copying a variant, there is no need to downcast.
1138                copy_from_local_value = pointer;
1139            } else {
1140                // The copied variant must be identical.
1141                return None;
1142            }
1143        }
1144
1145        // Both must be variants of the same type.
1146        if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1147    }
1148
1149    fn simplify_aggregate(
1150        &mut self,
1151        lhs: &Place<'tcx>,
1152        rvalue: &mut Rvalue<'tcx>,
1153        location: Location,
1154    ) -> Option<VnIndex> {
1155        let tcx = self.tcx;
1156        let ty = rvalue.ty(self.local_decls, tcx);
1157
1158        let Rvalue::Aggregate(box ref kind, ref mut field_ops) = *rvalue else { bug!() };
1159
1160        if field_ops.is_empty() {
1161            let is_zst = match *kind {
1162                AggregateKind::Array(..)
1163                | AggregateKind::Tuple
1164                | AggregateKind::Closure(..)
1165                | AggregateKind::CoroutineClosure(..) => true,
1166                // Only enums can be non-ZST.
1167                AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1168                // Coroutines are never ZST, as they at least contain the implicit states.
1169                AggregateKind::Coroutine(..) => false,
1170                AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1171            };
1172
1173            if is_zst {
1174                return Some(self.insert_constant(Const::zero_sized(ty)));
1175            }
1176        }
1177
1178        let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1179            self.simplify_operand(op, location)
1180                .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1181        }));
1182
1183        let variant_index = match *kind {
1184            AggregateKind::Array(..) | AggregateKind::Tuple => {
1185                assert!(!field_ops.is_empty());
1186                FIRST_VARIANT
1187            }
1188            AggregateKind::Closure(..)
1189            | AggregateKind::CoroutineClosure(..)
1190            | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1191            AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1192            // Do not track unions.
1193            AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1194                let field = *fields.first()?;
1195                return Some(self.insert(ty, Value::Union(active_field, field)));
1196            }
1197            AggregateKind::RawPtr(..) => {
1198                assert_eq!(field_ops.len(), 2);
1199                let [mut pointer, metadata] = fields.try_into().unwrap();
1200
1201                // Any thin pointer of matching mutability is fine as the data pointer.
1202                let mut was_updated = false;
1203                while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1204                    self.get(pointer)
1205                    && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1206                    && let ty::RawPtr(_, output_mtbl) = ty.kind()
1207                    && from_mtbl == output_mtbl
1208                    && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1209                {
1210                    pointer = cast_value;
1211                    was_updated = true;
1212                }
1213
1214                if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1215                    field_ops[FieldIdx::ZERO] = op;
1216                }
1217
1218                return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1219            }
1220        };
1221
1222        if ty.is_array()
1223            && fields.len() > 4
1224            && let Ok(&first) = fields.iter().all_equal_value()
1225        {
1226            let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1227            if let Some(op) = self.try_as_operand(first, location) {
1228                *rvalue = Rvalue::Repeat(op, len);
1229            }
1230            return Some(self.insert(ty, Value::Repeat(first, len)));
1231        }
1232
1233        if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1234            // Allow introducing places with non-constant offsets, as those are still better than
1235            // reconstructing an aggregate. But avoid creating `*a = copy (*b)`, as they might be
1236            // aliases resulting in overlapping assignments.
1237            let allow_complex_projection =
1238                lhs.projection[..].iter().all(PlaceElem::is_stable_offset);
1239            if let Some(place) = self.try_as_place(value, location, allow_complex_projection) {
1240                self.reused_locals.insert(place.local);
1241                *rvalue = Rvalue::Use(Operand::Copy(place));
1242            }
1243            return Some(value);
1244        }
1245
1246        Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1247    }
1248
1249    #[instrument(level = "trace", skip(self), ret)]
1250    fn simplify_unary(
1251        &mut self,
1252        op: UnOp,
1253        arg_op: &mut Operand<'tcx>,
1254        location: Location,
1255    ) -> Option<VnIndex> {
1256        let mut arg_index = self.simplify_operand(arg_op, location)?;
1257        let arg_ty = self.ty(arg_index);
1258        let ret_ty = op.ty(self.tcx, arg_ty);
1259
1260        // PtrMetadata doesn't care about *const vs *mut vs & vs &mut,
1261        // so start by removing those distinctions so we can update the `Operand`
1262        if op == UnOp::PtrMetadata {
1263            let mut was_updated = false;
1264            loop {
1265                arg_index = match self.get(arg_index) {
1266                    // Pointer casts that preserve metadata, such as
1267                    // `*const [i32]` <-> `*mut [i32]` <-> `*mut [f32]`.
1268                    // It's critical that this not eliminate cases like
1269                    // `*const [T]` -> `*const T` which remove metadata.
1270                    // We run on potentially-generic MIR, though, so unlike codegen
1271                    // we can't always know exactly what the metadata are.
1272                    // To allow things like `*mut (?A, ?T)` <-> `*mut (?B, ?T)`,
1273                    // it's fine to get a projection as the type.
1274                    Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1275                        if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1276                    {
1277                        inner
1278                    }
1279
1280                    // We have an unsizing cast, which assigns the length to wide pointer metadata.
1281                    Value::Cast {
1282                        kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1283                        value: from,
1284                    } if let Some(from) = self.ty(from).builtin_deref(true)
1285                        && let ty::Array(_, len) = from.kind()
1286                        && let Some(to) = self.ty(arg_index).builtin_deref(true)
1287                        && let ty::Slice(..) = to.kind() =>
1288                    {
1289                        return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1290                    }
1291
1292                    // `&mut *p`, `&raw *p`, etc don't change metadata.
1293                    Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1294                        if projection.is_empty() =>
1295                    {
1296                        reborrowed
1297                    }
1298
1299                    _ => break,
1300                };
1301                was_updated = true;
1302            }
1303
1304            if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1305                *arg_op = op;
1306            }
1307        }
1308
1309        let value = match (op, self.get(arg_index)) {
1310            (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1311            (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1312            (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1313                Value::BinaryOp(BinOp::Ne, lhs, rhs)
1314            }
1315            (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1316                Value::BinaryOp(BinOp::Eq, lhs, rhs)
1317            }
1318            (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1319            // We have an unsizing cast, which assigns the length to wide pointer metadata.
1320            (
1321                UnOp::PtrMetadata,
1322                Value::Cast {
1323                    kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1324                    value: inner,
1325                },
1326            ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1327                && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1328            {
1329                return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1330            }
1331            _ => Value::UnaryOp(op, arg_index),
1332        };
1333        Some(self.insert(ret_ty, value))
1334    }
1335
1336    #[instrument(level = "trace", skip(self), ret)]
1337    fn simplify_binary(
1338        &mut self,
1339        op: BinOp,
1340        lhs_operand: &mut Operand<'tcx>,
1341        rhs_operand: &mut Operand<'tcx>,
1342        location: Location,
1343    ) -> Option<VnIndex> {
1344        let lhs = self.simplify_operand(lhs_operand, location);
1345        let rhs = self.simplify_operand(rhs_operand, location);
1346
1347        // Only short-circuit options after we called `simplify_operand`
1348        // on both operands for side effect.
1349        let mut lhs = lhs?;
1350        let mut rhs = rhs?;
1351
1352        let lhs_ty = self.ty(lhs);
1353
1354        // If we're comparing pointers, remove `PtrToPtr` casts if the from
1355        // types of both casts and the metadata all match.
1356        if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1357            && lhs_ty.is_any_ptr()
1358            && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1359            && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1360            && let lhs_from = self.ty(lhs_value)
1361            && lhs_from == self.ty(rhs_value)
1362            && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1363        {
1364            lhs = lhs_value;
1365            rhs = rhs_value;
1366            if let Some(lhs_op) = self.try_as_operand(lhs, location)
1367                && let Some(rhs_op) = self.try_as_operand(rhs, location)
1368            {
1369                *lhs_operand = lhs_op;
1370                *rhs_operand = rhs_op;
1371            }
1372        }
1373
1374        if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1375            return Some(value);
1376        }
1377        let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1378        let value = Value::BinaryOp(op, lhs, rhs);
1379        Some(self.insert(ty, value))
1380    }
1381
1382    fn simplify_binary_inner(
1383        &mut self,
1384        op: BinOp,
1385        lhs_ty: Ty<'tcx>,
1386        lhs: VnIndex,
1387        rhs: VnIndex,
1388    ) -> Option<VnIndex> {
1389        // Floats are weird enough that none of the logic below applies.
1390        let reasonable_ty =
1391            lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1392        if !reasonable_ty {
1393            return None;
1394        }
1395
1396        let layout = self.ecx.layout_of(lhs_ty).ok()?;
1397
1398        let mut as_bits = |value: VnIndex| {
1399            let constant = self.eval_to_const(value)?;
1400            if layout.backend_repr.is_scalar() {
1401                let scalar = self.ecx.read_scalar(constant).discard_err()?;
1402                scalar.to_bits(constant.layout.size).discard_err()
1403            } else {
1404                // `constant` is a wide pointer. Do not evaluate to bits.
1405                None
1406            }
1407        };
1408
1409        // Represent the values as `Left(bits)` or `Right(VnIndex)`.
1410        use Either::{Left, Right};
1411        let a = as_bits(lhs).map_or(Right(lhs), Left);
1412        let b = as_bits(rhs).map_or(Right(rhs), Left);
1413
1414        let result = match (op, a, b) {
1415            // Neutral elements.
1416            (
1417                BinOp::Add
1418                | BinOp::AddWithOverflow
1419                | BinOp::AddUnchecked
1420                | BinOp::BitOr
1421                | BinOp::BitXor,
1422                Left(0),
1423                Right(p),
1424            )
1425            | (
1426                BinOp::Add
1427                | BinOp::AddWithOverflow
1428                | BinOp::AddUnchecked
1429                | BinOp::BitOr
1430                | BinOp::BitXor
1431                | BinOp::Sub
1432                | BinOp::SubWithOverflow
1433                | BinOp::SubUnchecked
1434                | BinOp::Offset
1435                | BinOp::Shl
1436                | BinOp::Shr,
1437                Right(p),
1438                Left(0),
1439            )
1440            | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1441            | (
1442                BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1443                Right(p),
1444                Left(1),
1445            ) => p,
1446            // Attempt to simplify `x & ALL_ONES` to `x`, with `ALL_ONES` depending on type size.
1447            (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1448                if ones == layout.size.truncate(u128::MAX)
1449                    || (layout.ty.is_bool() && ones == 1) =>
1450            {
1451                p
1452            }
1453            // Absorbing elements.
1454            (
1455                BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1456                _,
1457                Left(0),
1458            )
1459            | (BinOp::Rem, _, Left(1))
1460            | (
1461                BinOp::Mul
1462                | BinOp::MulWithOverflow
1463                | BinOp::MulUnchecked
1464                | BinOp::Div
1465                | BinOp::Rem
1466                | BinOp::BitAnd
1467                | BinOp::Shl
1468                | BinOp::Shr,
1469                Left(0),
1470                _,
1471            ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1472            // Attempt to simplify `x | ALL_ONES` to `ALL_ONES`.
1473            (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1474                if ones == layout.size.truncate(u128::MAX)
1475                    || (layout.ty.is_bool() && ones == 1) =>
1476            {
1477                self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1478            }
1479            // Sub/Xor with itself.
1480            (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1481                if a == b =>
1482            {
1483                self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1484            }
1485            // Comparison:
1486            // - if both operands can be computed as bits, just compare the bits;
1487            // - if we proved that both operands have the same value, we can insert true/false;
1488            // - otherwise, do nothing, as we do not try to prove inequality.
1489            (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1490            (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1491            (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1492            (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1493            _ => return None,
1494        };
1495
1496        if op.is_overflowing() {
1497            let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1498            let false_val = self.insert_bool(false);
1499            Some(self.insert_tuple(ty, &[result, false_val]))
1500        } else {
1501            Some(result)
1502        }
1503    }
1504
1505    fn simplify_cast(
1506        &mut self,
1507        initial_kind: &mut CastKind,
1508        initial_operand: &mut Operand<'tcx>,
1509        to: Ty<'tcx>,
1510        location: Location,
1511    ) -> Option<VnIndex> {
1512        use CastKind::*;
1513        use rustc_middle::ty::adjustment::PointerCoercion::*;
1514
1515        let mut kind = *initial_kind;
1516        let mut value = self.simplify_operand(initial_operand, location)?;
1517        let mut from = self.ty(value);
1518        if from == to {
1519            return Some(value);
1520        }
1521
1522        if let CastKind::PointerCoercion(ReifyFnPointer | ClosureFnPointer(_), _) = kind {
1523            // Each reification of a generic fn may get a different pointer.
1524            // Do not try to merge them.
1525            return Some(self.new_opaque(to));
1526        }
1527
1528        let mut was_ever_updated = false;
1529        loop {
1530            let mut was_updated_this_iteration = false;
1531
1532            // Transmuting between raw pointers is just a pointer cast so long as
1533            // they have the same metadata type (like `*const i32` <=> `*mut u64`
1534            // or `*mut [i32]` <=> `*const [u64]`), including the common special
1535            // case of `*const T` <=> `*mut T`.
1536            if let Transmute = kind
1537                && from.is_raw_ptr()
1538                && to.is_raw_ptr()
1539                && self.pointers_have_same_metadata(from, to)
1540            {
1541                kind = PtrToPtr;
1542                was_updated_this_iteration = true;
1543            }
1544
1545            // If a cast just casts away the metadata again, then we can get it by
1546            // casting the original thin pointer passed to `from_raw_parts`
1547            if let PtrToPtr = kind
1548                && let Value::RawPtr { pointer, .. } = self.get(value)
1549                && let ty::RawPtr(to_pointee, _) = to.kind()
1550                && to_pointee.is_sized(self.tcx, self.typing_env())
1551            {
1552                from = self.ty(pointer);
1553                value = pointer;
1554                was_updated_this_iteration = true;
1555                if from == to {
1556                    return Some(pointer);
1557                }
1558            }
1559
1560            // Aggregate-then-Transmute can just transmute the original field value,
1561            // so long as the bytes of a value from only from a single field.
1562            if let Transmute = kind
1563                && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1564                && let Some((field_idx, field_ty)) =
1565                    self.value_is_all_in_one_field(from, variant_idx)
1566            {
1567                from = field_ty;
1568                value = field_values[field_idx.as_usize()];
1569                was_updated_this_iteration = true;
1570                if field_ty == to {
1571                    return Some(value);
1572                }
1573            }
1574
1575            // Various cast-then-cast cases can be simplified.
1576            if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1577                let inner_from = self.ty(inner_value);
1578                let new_kind = match (inner_kind, kind) {
1579                    // Even if there's a narrowing cast in here that's fine, because
1580                    // things like `*mut [i32] -> *mut i32 -> *const i32` and
1581                    // `*mut [i32] -> *const [i32] -> *const i32` can skip the middle in MIR.
1582                    (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1583                    // PtrToPtr-then-Transmute is fine so long as the pointer cast is identity:
1584                    // `*const T -> *mut T -> NonNull<T>` is fine, but we need to check for narrowing
1585                    // to skip things like `*const [i32] -> *const i32 -> NonNull<T>`.
1586                    (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1587                        Some(Transmute)
1588                    }
1589                    // Similarly, for Transmute-then-PtrToPtr. Note that we need to check different
1590                    // variables for their metadata, and thus this can't merge with the previous arm.
1591                    (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1592                        Some(Transmute)
1593                    }
1594                    // If would be legal to always do this, but we don't want to hide information
1595                    // from the backend that it'd otherwise be able to use for optimizations.
1596                    (Transmute, Transmute)
1597                        if !self.type_may_have_niche_of_interest_to_backend(from) =>
1598                    {
1599                        Some(Transmute)
1600                    }
1601                    _ => None,
1602                };
1603                if let Some(new_kind) = new_kind {
1604                    kind = new_kind;
1605                    from = inner_from;
1606                    value = inner_value;
1607                    was_updated_this_iteration = true;
1608                    if inner_from == to {
1609                        return Some(inner_value);
1610                    }
1611                }
1612            }
1613
1614            if was_updated_this_iteration {
1615                was_ever_updated = true;
1616            } else {
1617                break;
1618            }
1619        }
1620
1621        if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1622            *initial_operand = op;
1623            *initial_kind = kind;
1624        }
1625
1626        Some(self.insert(to, Value::Cast { kind, value }))
1627    }
1628
1629    fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1630        let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1631        let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1632        if left_meta_ty == right_meta_ty {
1633            true
1634        } else if let Ok(left) =
1635            self.tcx.try_normalize_erasing_regions(self.typing_env(), left_meta_ty)
1636            && let Ok(right) =
1637                self.tcx.try_normalize_erasing_regions(self.typing_env(), right_meta_ty)
1638        {
1639            left == right
1640        } else {
1641            false
1642        }
1643    }
1644
1645    /// Returns `false` if we know for sure that this type has no interesting niche,
1646    /// and thus we can skip transmuting through it without worrying.
1647    ///
1648    /// The backend will emit `assume`s when transmuting between types with niches,
1649    /// so we want to preserve `i32 -> char -> u32` so that that data is around,
1650    /// but it's fine to skip whole-range-is-value steps like `A -> u32 -> B`.
1651    fn type_may_have_niche_of_interest_to_backend(&self, ty: Ty<'tcx>) -> bool {
1652        let Ok(layout) = self.ecx.layout_of(ty) else {
1653            // If it's too generic or something, then assume it might be interesting later.
1654            return true;
1655        };
1656
1657        if layout.uninhabited {
1658            return true;
1659        }
1660
1661        match layout.backend_repr {
1662            BackendRepr::Scalar(a) => !a.is_always_valid(&self.ecx),
1663            BackendRepr::ScalarPair(a, b) => {
1664                !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1665            }
1666            BackendRepr::SimdVector { .. } | BackendRepr::Memory { .. } => false,
1667        }
1668    }
1669
1670    fn value_is_all_in_one_field(
1671        &self,
1672        ty: Ty<'tcx>,
1673        variant: VariantIdx,
1674    ) -> Option<(FieldIdx, Ty<'tcx>)> {
1675        if let Ok(layout) = self.ecx.layout_of(ty)
1676            && let abi::Variants::Single { index } = layout.variants
1677            && index == variant
1678            && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1679            && layout.size == field_layout.size
1680        {
1681            // We needed to check the variant to avoid trying to read the tag
1682            // field from an enum where no fields have variants, since that tag
1683            // field isn't in the `Aggregate` from which we're getting values.
1684            Some((field_idx, field_layout.ty))
1685        } else if let ty::Adt(adt, args) = ty.kind()
1686            && adt.is_struct()
1687            && adt.repr().transparent()
1688            && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1689        {
1690            Some((FieldIdx::ZERO, single_field.ty(self.tcx, args)))
1691        } else {
1692            None
1693        }
1694    }
1695}
1696
1697fn op_to_prop_const<'tcx>(
1698    ecx: &mut InterpCx<'tcx, DummyMachine>,
1699    op: &OpTy<'tcx>,
1700) -> Option<ConstValue> {
1701    // Do not attempt to propagate unsized locals.
1702    if op.layout.is_unsized() {
1703        return None;
1704    }
1705
1706    // This constant is a ZST, just return an empty value.
1707    if op.layout.is_zst() {
1708        return Some(ConstValue::ZeroSized);
1709    }
1710
1711    // Do not synthetize too large constants. Codegen will just memcpy them, which we'd like to
1712    // avoid.
1713    if !matches!(op.layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) {
1714        return None;
1715    }
1716
1717    // If this constant has scalar ABI, return it as a `ConstValue::Scalar`.
1718    if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1719        && let Some(scalar) = ecx.read_scalar(op).discard_err()
1720    {
1721        if !scalar.try_to_scalar_int().is_ok() {
1722            // Check that we do not leak a pointer.
1723            // Those pointers may lose part of their identity in codegen.
1724            // FIXME: remove this hack once https://github.com/rust-lang/rust/issues/79738 is fixed.
1725            return None;
1726        }
1727        return Some(ConstValue::Scalar(scalar));
1728    }
1729
1730    // If this constant is already represented as an `Allocation`,
1731    // try putting it into global memory to return it.
1732    if let Either::Left(mplace) = op.as_mplace_or_imm() {
1733        let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
1734
1735        // Do not try interning a value that contains provenance.
1736        // Due to https://github.com/rust-lang/rust/issues/79738, doing so could lead to bugs.
1737        // FIXME: remove this hack once that issue is fixed.
1738        let alloc_ref = ecx.get_ptr_alloc(mplace.ptr(), size).discard_err()??;
1739        if alloc_ref.has_provenance() {
1740            return None;
1741        }
1742
1743        let pointer = mplace.ptr().into_pointer_or_addr().ok()?;
1744        let (prov, offset) = pointer.prov_and_relative_offset();
1745        let alloc_id = prov.alloc_id();
1746        intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1747
1748        // `alloc_id` may point to a static. Codegen will choke on an `Indirect` with anything
1749        // by `GlobalAlloc::Memory`, so do fall through to copying if needed.
1750        // FIXME: find a way to treat this more uniformly (probably by fixing codegen)
1751        if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1752            // Transmuting a constant is just an offset in the allocation. If the alignment of the
1753            // allocation is not enough, fallback to copying into a properly aligned value.
1754            && alloc.inner().align >= op.layout.align.abi
1755        {
1756            return Some(ConstValue::Indirect { alloc_id, offset });
1757        }
1758    }
1759
1760    // Everything failed: create a new allocation to hold the data.
1761    let alloc_id =
1762        ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1763    let value = ConstValue::Indirect { alloc_id, offset: Size::ZERO };
1764
1765    // Check that we do not leak a pointer.
1766    // Those pointers may lose part of their identity in codegen.
1767    // FIXME: remove this hack once https://github.com/rust-lang/rust/issues/79738 is fixed.
1768    if ecx.tcx.global_alloc(alloc_id).unwrap_memory().inner().provenance().ptrs().is_empty() {
1769        return Some(value);
1770    }
1771
1772    None
1773}
1774
1775impl<'tcx> VnState<'_, '_, 'tcx> {
1776    /// If either [`Self::try_as_constant`] as [`Self::try_as_place`] succeeds,
1777    /// returns that result as an [`Operand`].
1778    fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1779        if let Some(const_) = self.try_as_constant(index) {
1780            Some(Operand::Constant(Box::new(const_)))
1781        } else if let Some(place) = self.try_as_place(index, location, false) {
1782            self.reused_locals.insert(place.local);
1783            Some(Operand::Copy(place))
1784        } else {
1785            None
1786        }
1787    }
1788
1789    /// If `index` is a `Value::Constant`, return the `Constant` to be put in the MIR.
1790    fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1791        // This was already constant in MIR, do not change it. If the constant is not
1792        // deterministic, adding an additional mention of it in MIR will not give the same value as
1793        // the former mention.
1794        if let Value::Constant { value, disambiguator: None } = self.get(index) {
1795            debug_assert!(value.is_deterministic());
1796            return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1797        }
1798
1799        let op = self.eval_to_const(index)?;
1800        if op.layout.is_unsized() {
1801            // Do not attempt to propagate unsized locals.
1802            return None;
1803        }
1804
1805        let value = op_to_prop_const(&mut self.ecx, op)?;
1806
1807        // Check that we do not leak a pointer.
1808        // Those pointers may lose part of their identity in codegen.
1809        // FIXME: remove this hack once https://github.com/rust-lang/rust/issues/79738 is fixed.
1810        assert!(!value.may_have_provenance(self.tcx, op.layout.size));
1811
1812        let const_ = Const::Val(value, op.layout.ty);
1813        Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_ })
1814    }
1815
1816    /// Construct a place which holds the same value as `index` and for which all locals strictly
1817    /// dominate `loc`. If you used this place, add its base local to `reused_locals` to remove
1818    /// storage statements.
1819    #[instrument(level = "trace", skip(self), ret)]
1820    fn try_as_place(
1821        &mut self,
1822        mut index: VnIndex,
1823        loc: Location,
1824        allow_complex_projection: bool,
1825    ) -> Option<Place<'tcx>> {
1826        let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
1827        loop {
1828            if let Some(local) = self.try_as_local(index, loc) {
1829                projection.reverse();
1830                let place =
1831                    Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
1832                return Some(place);
1833            } else if projection.last() == Some(&PlaceElem::Deref) {
1834                // `Deref` can only be the first projection in a place.
1835                // If we are here, we failed to find a local, and we already have a `Deref`.
1836                // Trying to add projections will only result in an ill-formed place.
1837                return None;
1838            } else if let Value::Projection(pointer, proj) = self.get(index)
1839                && (allow_complex_projection || proj.is_stable_offset())
1840                && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
1841            {
1842                projection.push(proj);
1843                index = pointer;
1844            } else {
1845                return None;
1846            }
1847        }
1848    }
1849
1850    /// If there is a local which is assigned `index`, and its assignment strictly dominates `loc`,
1851    /// return it. If you used this local, add it to `reused_locals` to remove storage statements.
1852    fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
1853        let other = self.rev_locals.get(index)?;
1854        other
1855            .iter()
1856            .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
1857            .copied()
1858    }
1859}
1860
1861impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
1862    fn tcx(&self) -> TyCtxt<'tcx> {
1863        self.tcx
1864    }
1865
1866    fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
1867        self.simplify_place_projection(place, location);
1868        if context.is_mutating_use() && place.is_indirect() {
1869            // Non-local mutation maybe invalidate deref.
1870            self.invalidate_derefs();
1871        }
1872        self.super_place(place, context, location);
1873    }
1874
1875    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1876        self.simplify_operand(operand, location);
1877        self.super_operand(operand, location);
1878    }
1879
1880    fn visit_assign(
1881        &mut self,
1882        lhs: &mut Place<'tcx>,
1883        rvalue: &mut Rvalue<'tcx>,
1884        location: Location,
1885    ) {
1886        self.simplify_place_projection(lhs, location);
1887
1888        let value = self.simplify_rvalue(lhs, rvalue, location);
1889        if let Some(value) = value {
1890            if let Some(const_) = self.try_as_constant(value) {
1891                *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)));
1892            } else if let Some(place) = self.try_as_place(value, location, false)
1893                && *rvalue != Rvalue::Use(Operand::Move(place))
1894                && *rvalue != Rvalue::Use(Operand::Copy(place))
1895            {
1896                *rvalue = Rvalue::Use(Operand::Copy(place));
1897                self.reused_locals.insert(place.local);
1898            }
1899        }
1900
1901        if lhs.is_indirect() {
1902            // Non-local mutation maybe invalidate deref.
1903            self.invalidate_derefs();
1904        }
1905
1906        if let Some(local) = lhs.as_local()
1907            && self.ssa.is_ssa(local)
1908            && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
1909            // FIXME(#112651) `rvalue` may have a subtype to `local`. We can only mark
1910            // `local` as reusable if we have an exact type match.
1911            && self.local_decls[local].ty == rvalue_ty
1912        {
1913            let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
1914            self.assign(local, value);
1915        }
1916    }
1917
1918    fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1919        if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
1920            if let Some(local) = destination.as_local()
1921                && self.ssa.is_ssa(local)
1922            {
1923                let ty = self.local_decls[local].ty;
1924                let opaque = self.new_opaque(ty);
1925                self.assign(local, opaque);
1926            }
1927        }
1928        // Function calls and ASM may invalidate (nested) derefs. We must handle them carefully.
1929        // Currently, only preserving derefs for trivial terminators like SwitchInt and Goto.
1930        let safe_to_preserve_derefs = matches!(
1931            terminator.kind,
1932            TerminatorKind::SwitchInt { .. } | TerminatorKind::Goto { .. }
1933        );
1934        if !safe_to_preserve_derefs {
1935            self.invalidate_derefs();
1936        }
1937        self.super_terminator(terminator, location);
1938    }
1939}
1940
1941struct StorageRemover<'tcx> {
1942    tcx: TyCtxt<'tcx>,
1943    reused_locals: DenseBitSet<Local>,
1944}
1945
1946impl<'tcx> MutVisitor<'tcx> for StorageRemover<'tcx> {
1947    fn tcx(&self) -> TyCtxt<'tcx> {
1948        self.tcx
1949    }
1950
1951    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
1952        if let Operand::Move(place) = *operand
1953            && !place.is_indirect_first_projection()
1954            && self.reused_locals.contains(place.local)
1955        {
1956            *operand = Operand::Copy(place);
1957        }
1958    }
1959
1960    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
1961        match stmt.kind {
1962            // When removing storage statements, we need to remove both (#107511).
1963            StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
1964                if self.reused_locals.contains(l) =>
1965            {
1966                stmt.make_nop(true)
1967            }
1968            _ => self.super_statement(stmt, loc),
1969        }
1970    }
1971}