Skip to main content

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