1use std::borrow::Cow;
88use std::hash::{Hash, Hasher};
89
90use either::Either;
91use hashbrown::hash_table::{Entry, HashTable};
92use itertools::Itertools as _;
93use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT, FieldIdx, Primitive, Size, VariantIdx};
94use rustc_arena::DroplessArena;
95use rustc_const_eval::const_eval::DummyMachine;
96use rustc_const_eval::interpret::{
97 ImmTy, Immediate, InterpCx, MemPlaceMeta, MemoryKind, OpTy, Projectable, Scalar,
98 intern_const_alloc_for_constprop,
99};
100use rustc_data_structures::fx::FxHasher;
101use rustc_data_structures::graph::dominators::Dominators;
102use rustc_hir::def::DefKind;
103use rustc_index::bit_set::DenseBitSet;
104use rustc_index::{IndexVec, newtype_index};
105use rustc_middle::bug;
106use rustc_middle::mir::interpret::GlobalAlloc;
107use rustc_middle::mir::visit::*;
108use rustc_middle::mir::*;
109use rustc_middle::ty::layout::HasTypingEnv;
110use rustc_middle::ty::{self, Ty, TyCtxt};
111use rustc_span::DUMMY_SP;
112use smallvec::SmallVec;
113use tracing::{debug, instrument, trace};
114
115use crate::ssa::SsaLocals;
116
117pub(super) struct GVN;
118
119impl<'tcx> crate::MirPass<'tcx> for GVN {
120 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
121 sess.mir_opt_level() >= 2
122 }
123
124 #[instrument(level = "trace", skip(self, tcx, body))]
125 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
126 debug!(def_id = ?body.source.def_id());
127
128 let typing_env = body.typing_env(tcx);
129 let ssa = SsaLocals::new(tcx, body, typing_env);
130 let dominators = body.basic_blocks.dominators().clone();
132 let maybe_loop_headers = loops::maybe_loop_headers(body);
133
134 let arena = DroplessArena::default();
135 let mut state =
136 VnState::new(tcx, body, typing_env, &ssa, dominators, &body.local_decls, &arena);
137
138 for local in body.args_iter().filter(|&local| ssa.is_ssa(local)) {
139 let opaque = state.new_opaque(body.local_decls[local].ty);
140 state.assign(local, opaque);
141 }
142
143 let reverse_postorder = body.basic_blocks.reverse_postorder().to_vec();
144 for bb in reverse_postorder {
145 if maybe_loop_headers.contains(bb) {
148 state.invalidate_derefs();
149 }
150 let data = &mut body.basic_blocks.as_mut_preserves_cfg()[bb];
151 state.visit_basic_block_data(bb, data);
152 }
153
154 StorageRemover { tcx, reused_locals: state.reused_locals }.visit_body_preserves_cfg(body);
158 }
159
160 fn is_required(&self) -> bool {
161 false
162 }
163}
164
165newtype_index! {
166 #[debug_format = "_v{}"]
168 struct VnIndex {}
169}
170
171#[derive(Copy, Clone, Debug, Eq)]
175struct VnOpaque;
176impl PartialEq for VnOpaque {
177 fn eq(&self, _: &VnOpaque) -> bool {
178 unreachable!()
180 }
181}
182impl Hash for VnOpaque {
183 fn hash<T: Hasher>(&self, _: &mut T) {
184 unreachable!()
186 }
187}
188
189#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
190enum AddressKind {
191 Ref(BorrowKind),
192 Address(RawPtrKind),
193}
194
195#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
196enum AddressBase {
197 Local(Local),
199 Deref(VnIndex),
201}
202
203#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
204enum Value<'a, 'tcx> {
205 Opaque(VnOpaque),
209 Constant {
211 value: Const<'tcx>,
212 disambiguator: Option<VnOpaque>,
216 },
217
218 Aggregate(VariantIdx, &'a [VnIndex]),
222 Union(FieldIdx, VnIndex),
224 RawPtr {
226 pointer: VnIndex,
228 metadata: VnIndex,
230 },
231 Repeat(VnIndex, ty::Const<'tcx>),
233 Address {
235 base: AddressBase,
236 projection: &'a [ProjectionElem<VnIndex, Ty<'tcx>>],
239 kind: AddressKind,
240 provenance: VnOpaque,
242 },
243
244 Projection(VnIndex, ProjectionElem<VnIndex, ()>),
247 Discriminant(VnIndex),
249
250 NullaryOp(NullOp<'tcx>, Ty<'tcx>),
252 UnaryOp(UnOp, VnIndex),
253 BinaryOp(BinOp, VnIndex, VnIndex),
254 Cast {
255 kind: CastKind,
256 value: VnIndex,
257 },
258}
259
260struct ValueSet<'a, 'tcx> {
266 indices: HashTable<VnIndex>,
267 hashes: IndexVec<VnIndex, u64>,
268 values: IndexVec<VnIndex, Value<'a, 'tcx>>,
269 types: IndexVec<VnIndex, Ty<'tcx>>,
270}
271
272impl<'a, 'tcx> ValueSet<'a, 'tcx> {
273 fn new(num_values: usize) -> ValueSet<'a, 'tcx> {
274 ValueSet {
275 indices: HashTable::with_capacity(num_values),
276 hashes: IndexVec::with_capacity(num_values),
277 values: IndexVec::with_capacity(num_values),
278 types: IndexVec::with_capacity(num_values),
279 }
280 }
281
282 #[inline]
285 fn insert_unique(
286 &mut self,
287 ty: Ty<'tcx>,
288 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
289 ) -> VnIndex {
290 let value = value(VnOpaque);
291
292 debug_assert!(match value {
293 Value::Opaque(_) | Value::Address { .. } => true,
294 Value::Constant { disambiguator, .. } => disambiguator.is_some(),
295 _ => false,
296 });
297
298 let index = self.hashes.push(0);
299 let _index = self.types.push(ty);
300 debug_assert_eq!(index, _index);
301 let _index = self.values.push(value);
302 debug_assert_eq!(index, _index);
303 index
304 }
305
306 #[allow(rustc::pass_by_value)] fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> (VnIndex, bool) {
310 debug_assert!(match value {
311 Value::Opaque(_) | Value::Address { .. } => false,
312 Value::Constant { disambiguator, .. } => disambiguator.is_none(),
313 _ => true,
314 });
315
316 let hash: u64 = {
317 let mut h = FxHasher::default();
318 value.hash(&mut h);
319 ty.hash(&mut h);
320 h.finish()
321 };
322
323 let eq = |index: &VnIndex| self.values[*index] == value && self.types[*index] == ty;
324 let hasher = |index: &VnIndex| self.hashes[*index];
325 match self.indices.entry(hash, eq, hasher) {
326 Entry::Occupied(entry) => {
327 let index = *entry.get();
328 (index, false)
329 }
330 Entry::Vacant(entry) => {
331 let index = self.hashes.push(hash);
332 entry.insert(index);
333 let _index = self.values.push(value);
334 debug_assert_eq!(index, _index);
335 let _index = self.types.push(ty);
336 debug_assert_eq!(index, _index);
337 (index, true)
338 }
339 }
340 }
341
342 #[inline]
344 fn value(&self, index: VnIndex) -> Value<'a, 'tcx> {
345 self.values[index]
346 }
347
348 #[inline]
350 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
351 self.types[index]
352 }
353
354 #[inline]
356 fn forget(&mut self, index: VnIndex) {
357 self.values[index] = Value::Opaque(VnOpaque);
358 }
359}
360
361struct VnState<'body, 'a, 'tcx> {
362 tcx: TyCtxt<'tcx>,
363 ecx: InterpCx<'tcx, DummyMachine>,
364 local_decls: &'body LocalDecls<'tcx>,
365 is_coroutine: bool,
366 locals: IndexVec<Local, Option<VnIndex>>,
368 rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
371 values: ValueSet<'a, 'tcx>,
372 evaluated: IndexVec<VnIndex, Option<Option<&'a OpTy<'tcx>>>>,
377 derefs: Vec<VnIndex>,
379 ssa: &'body SsaLocals,
380 dominators: Dominators<BasicBlock>,
381 reused_locals: DenseBitSet<Local>,
382 arena: &'a DroplessArena,
383}
384
385impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> {
386 fn new(
387 tcx: TyCtxt<'tcx>,
388 body: &Body<'tcx>,
389 typing_env: ty::TypingEnv<'tcx>,
390 ssa: &'body SsaLocals,
391 dominators: Dominators<BasicBlock>,
392 local_decls: &'body LocalDecls<'tcx>,
393 arena: &'a DroplessArena,
394 ) -> Self {
395 let num_values =
400 2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
401 + 4 * body.basic_blocks.len();
402 VnState {
403 tcx,
404 ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
405 local_decls,
406 is_coroutine: body.coroutine.is_some(),
407 locals: IndexVec::from_elem(None, local_decls),
408 rev_locals: IndexVec::with_capacity(num_values),
409 values: ValueSet::new(num_values),
410 evaluated: IndexVec::with_capacity(num_values),
411 derefs: Vec::new(),
412 ssa,
413 dominators,
414 reused_locals: DenseBitSet::new_empty(local_decls.len()),
415 arena,
416 }
417 }
418
419 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
420 self.ecx.typing_env()
421 }
422
423 #[instrument(level = "trace", skip(self), ret)]
424 fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
425 let (index, new) = self.values.insert(ty, value);
426 if new {
427 let _index = self.evaluated.push(None);
429 debug_assert_eq!(index, _index);
430 let _index = self.rev_locals.push(SmallVec::new());
431 debug_assert_eq!(index, _index);
432 }
433 index
434 }
435
436 #[instrument(level = "trace", skip(self), ret)]
439 fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
440 let index = self.values.insert_unique(ty, Value::Opaque);
441 let _index = self.evaluated.push(Some(None));
442 debug_assert_eq!(index, _index);
443 let _index = self.rev_locals.push(SmallVec::new());
444 debug_assert_eq!(index, _index);
445 index
446 }
447
448 #[instrument(level = "trace", skip(self), ret)]
450 fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
451 let pty = place.ty(self.local_decls, self.tcx).ty;
452 let ty = match kind {
453 AddressKind::Ref(bk) => {
454 Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
455 }
456 AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
457 };
458
459 let mut projection = place.projection.iter();
460 let base = if place.is_indirect_first_projection() {
461 let base = self.locals[place.local]?;
462 projection.next();
464 AddressBase::Deref(base)
465 } else {
466 AddressBase::Local(place.local)
467 };
468 let projection =
470 projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
471 let projection = self.arena.try_alloc_from_iter(projection).ok()?;
472
473 let index = self.values.insert_unique(ty, |provenance| Value::Address {
474 base,
475 projection,
476 kind,
477 provenance,
478 });
479 let _index = self.evaluated.push(None);
480 debug_assert_eq!(index, _index);
481 let _index = self.rev_locals.push(SmallVec::new());
482 debug_assert_eq!(index, _index);
483
484 Some(index)
485 }
486
487 #[instrument(level = "trace", skip(self), ret)]
488 fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
489 let (index, new) = if value.is_deterministic() {
490 let constant = Value::Constant { value, disambiguator: None };
492 self.values.insert(value.ty(), constant)
493 } else {
494 let index = self.values.insert_unique(value.ty(), |disambiguator| Value::Constant {
497 value,
498 disambiguator: Some(disambiguator),
499 });
500 (index, true)
501 };
502 if new {
503 let _index = self.evaluated.push(None);
504 debug_assert_eq!(index, _index);
505 let _index = self.rev_locals.push(SmallVec::new());
506 debug_assert_eq!(index, _index);
507 }
508 index
509 }
510
511 #[inline]
512 fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
513 self.values.value(index)
514 }
515
516 #[inline]
517 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
518 self.values.ty(index)
519 }
520
521 #[instrument(level = "trace", skip(self))]
523 fn assign(&mut self, local: Local, value: VnIndex) {
524 debug_assert!(self.ssa.is_ssa(local));
525 self.locals[local] = Some(value);
526 self.rev_locals[value].push(local);
527 }
528
529 fn insert_bool(&mut self, flag: bool) -> VnIndex {
530 let value = Const::from_bool(self.tcx, flag);
532 debug_assert!(value.is_deterministic());
533 self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
534 }
535
536 fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
537 let value = Const::from_scalar(self.tcx, scalar, ty);
539 debug_assert!(value.is_deterministic());
540 self.insert(ty, Value::Constant { value, disambiguator: None })
541 }
542
543 fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
544 self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
545 }
546
547 fn insert_deref(&mut self, ty: Ty<'tcx>, value: VnIndex) -> VnIndex {
548 let value = self.insert(ty, Value::Projection(value, ProjectionElem::Deref));
549 self.derefs.push(value);
550 value
551 }
552
553 fn invalidate_derefs(&mut self) {
554 for deref in std::mem::take(&mut self.derefs) {
555 self.values.forget(deref);
556 }
557 }
558
559 #[instrument(level = "trace", skip(self), ret)]
560 fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
561 use Value::*;
562 let ty = self.ty(value);
563 let ty = if !self.is_coroutine || ty.is_scalar() {
565 self.ecx.layout_of(ty).ok()?
566 } else {
567 return None;
568 };
569 let op = match self.get(value) {
570 _ if ty.is_zst() => ImmTy::uninit(ty).into(),
571
572 Opaque(_) => return None,
573 Repeat(..) => return None,
575
576 Constant { ref value, disambiguator: _ } => {
577 self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
578 }
579 Aggregate(variant, ref fields) => {
580 let fields =
581 fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
582 let variant = if ty.ty.is_enum() { Some(variant) } else { None };
583 if matches!(ty.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
584 {
585 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
586 let variant_dest = if let Some(variant) = variant {
587 self.ecx.project_downcast(&dest, variant).discard_err()?
588 } else {
589 dest.clone()
590 };
591 for (field_index, op) in fields.into_iter().enumerate() {
592 let field_dest = self
593 .ecx
594 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
595 .discard_err()?;
596 self.ecx.copy_op(op, &field_dest).discard_err()?;
597 }
598 self.ecx
599 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
600 .discard_err()?;
601 self.ecx
602 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
603 .discard_err()?;
604 dest.into()
605 } else {
606 return None;
607 }
608 }
609 Union(active_field, field) => {
610 let field = self.eval_to_const(field)?;
611 if matches!(ty.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
612 {
613 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
614 let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
615 self.ecx.copy_op(field, &field_dest).discard_err()?;
616 self.ecx
617 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
618 .discard_err()?;
619 dest.into()
620 } else {
621 return None;
622 }
623 }
624 RawPtr { pointer, metadata } => {
625 let pointer = self.eval_to_const(pointer)?;
626 let metadata = self.eval_to_const(metadata)?;
627
628 let data = self.ecx.read_pointer(pointer).discard_err()?;
630 let meta = if metadata.layout.is_zst() {
631 MemPlaceMeta::None
632 } else {
633 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
634 };
635 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
636 ImmTy::from_immediate(ptr_imm, ty).into()
637 }
638
639 Projection(base, elem) => {
640 let base = self.eval_to_const(base)?;
641 let elem = elem.try_map(|_| None, |()| ty.ty)?;
644 self.ecx.project(base, elem).discard_err()?
645 }
646 Address { base, projection, .. } => {
647 debug_assert!(!projection.contains(&ProjectionElem::Deref));
648 let pointer = match base {
649 AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
650 AddressBase::Local(_) => return None,
652 };
653 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
654 for elem in projection {
655 let elem = elem.try_map(|_| None, |ty| ty)?;
658 mplace = self.ecx.project(&mplace, elem).discard_err()?;
659 }
660 let pointer = mplace.to_ref(&self.ecx);
661 ImmTy::from_immediate(pointer, ty).into()
662 }
663
664 Discriminant(base) => {
665 let base = self.eval_to_const(base)?;
666 let variant = self.ecx.read_discriminant(base).discard_err()?;
667 let discr_value =
668 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
669 discr_value.into()
670 }
671 NullaryOp(null_op, arg_ty) => {
672 let arg_layout = self.ecx.layout_of(arg_ty).ok()?;
673 let val = match null_op {
674 NullOp::OffsetOf(fields) => self
675 .tcx
676 .offset_of_subfield(self.typing_env(), arg_layout, fields.iter())
677 .bytes(),
678 NullOp::RuntimeChecks(_) => return None,
679 };
680 ImmTy::from_uint(val, ty).into()
681 }
682 UnaryOp(un_op, operand) => {
683 let operand = self.eval_to_const(operand)?;
684 let operand = self.ecx.read_immediate(operand).discard_err()?;
685 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
686 val.into()
687 }
688 BinaryOp(bin_op, lhs, rhs) => {
689 let lhs = self.eval_to_const(lhs)?;
690 let rhs = self.eval_to_const(rhs)?;
691 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
692 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
693 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
694 val.into()
695 }
696 Cast { kind, value } => match kind {
697 CastKind::IntToInt | CastKind::IntToFloat => {
698 let value = self.eval_to_const(value)?;
699 let value = self.ecx.read_immediate(value).discard_err()?;
700 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
701 res.into()
702 }
703 CastKind::FloatToFloat | CastKind::FloatToInt => {
704 let value = self.eval_to_const(value)?;
705 let value = self.ecx.read_immediate(value).discard_err()?;
706 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
707 res.into()
708 }
709 CastKind::Transmute | CastKind::Subtype => {
710 let value = self.eval_to_const(value)?;
711 if value.as_mplace_or_imm().is_right() {
716 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
717 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
718 s1.size(&self.ecx) == s2.size(&self.ecx)
719 && !matches!(s1.primitive(), Primitive::Pointer(..))
720 }
721 (BackendRepr::ScalarPair(a1, b1), BackendRepr::ScalarPair(a2, b2)) => {
722 a1.size(&self.ecx) == a2.size(&self.ecx)
723 && b1.size(&self.ecx) == b2.size(&self.ecx)
724 && b1.align(&self.ecx) == b2.align(&self.ecx)
726 && !matches!(a1.primitive(), Primitive::Pointer(..))
728 && !matches!(b1.primitive(), Primitive::Pointer(..))
729 }
730 _ => false,
731 };
732 if !can_transmute {
733 return None;
734 }
735 }
736 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
737 }
738 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
739 let src = self.eval_to_const(value)?;
740 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
741 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
742 self.ecx
743 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
744 .discard_err()?;
745 dest.into()
746 }
747 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
748 let src = self.eval_to_const(value)?;
749 let src = self.ecx.read_immediate(src).discard_err()?;
750 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
751 ret.into()
752 }
753 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
754 let src = self.eval_to_const(value)?;
755 let src = self.ecx.read_immediate(src).discard_err()?;
756 ImmTy::from_immediate(*src, ty).into()
757 }
758 _ => return None,
759 },
760 };
761 Some(op)
762 }
763
764 fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
765 if let Some(op) = self.evaluated[index] {
766 return op;
767 }
768 let op = self.eval_to_const_inner(index);
769 self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
770 self.evaluated[index].unwrap()
771 }
772
773 #[instrument(level = "trace", skip(self), ret)]
775 fn dereference_address(
776 &mut self,
777 base: AddressBase,
778 projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
779 ) -> Option<VnIndex> {
780 let (mut place_ty, mut value) = match base {
781 AddressBase::Local(local) => {
783 let local = self.locals[local]?;
784 let place_ty = PlaceTy::from_ty(self.ty(local));
785 (place_ty, local)
786 }
787 AddressBase::Deref(reborrow) => {
789 let place_ty = PlaceTy::from_ty(self.ty(reborrow));
790 self.project(place_ty, reborrow, ProjectionElem::Deref)?
791 }
792 };
793 for &proj in projection {
794 (place_ty, value) = self.project(place_ty, value, proj)?;
795 }
796 Some(value)
797 }
798
799 #[instrument(level = "trace", skip(self), ret)]
800 fn project(
801 &mut self,
802 place_ty: PlaceTy<'tcx>,
803 value: VnIndex,
804 proj: ProjectionElem<VnIndex, Ty<'tcx>>,
805 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
806 let projection_ty = place_ty.projection_ty(self.tcx, proj);
807 let proj = match proj {
808 ProjectionElem::Deref => {
809 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
810 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
811 {
812 if let Value::Address { base, projection, .. } = self.get(value)
813 && let Some(value) = self.dereference_address(base, projection)
814 {
815 return Some((projection_ty, value));
816 }
817
818 return Some((projection_ty, self.insert_deref(projection_ty.ty, value)));
821 } else {
822 return None;
823 }
824 }
825 ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
826 ProjectionElem::Field(f, _) => match self.get(value) {
827 Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
828 Value::Union(active, field) if active == f => return Some((projection_ty, field)),
829 Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
830 if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
831 && written_variant == read_variant =>
847 {
848 return Some((projection_ty, fields[f.as_usize()]));
849 }
850 _ => ProjectionElem::Field(f, ()),
851 },
852 ProjectionElem::Index(idx) => {
853 if let Value::Repeat(inner, _) = self.get(value) {
854 return Some((projection_ty, inner));
855 }
856 ProjectionElem::Index(idx)
857 }
858 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
859 match self.get(value) {
860 Value::Repeat(inner, _) => {
861 return Some((projection_ty, inner));
862 }
863 Value::Aggregate(_, operands) => {
864 let offset = if from_end {
865 operands.len() - offset as usize
866 } else {
867 offset as usize
868 };
869 let value = operands.get(offset).copied()?;
870 return Some((projection_ty, value));
871 }
872 _ => {}
873 };
874 ProjectionElem::ConstantIndex { offset, min_length, from_end }
875 }
876 ProjectionElem::Subslice { from, to, from_end } => {
877 ProjectionElem::Subslice { from, to, from_end }
878 }
879 ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
880 ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
881 };
882
883 let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
884 Some((projection_ty, value))
885 }
886
887 #[instrument(level = "trace", skip(self))]
889 fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
890 if place.is_indirect_first_projection()
893 && let Some(base) = self.locals[place.local]
894 && let Some(new_local) = self.try_as_local(base, location)
895 && place.local != new_local
896 {
897 place.local = new_local;
898 self.reused_locals.insert(new_local);
899 }
900
901 let mut projection = Cow::Borrowed(&place.projection[..]);
902
903 for i in 0..projection.len() {
904 let elem = projection[i];
905 if let ProjectionElem::Index(idx_local) = elem
906 && let Some(idx) = self.locals[idx_local]
907 {
908 if let Some(offset) = self.eval_to_const(idx)
909 && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
910 && let Some(min_length) = offset.checked_add(1)
911 {
912 projection.to_mut()[i] =
913 ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
914 } else if let Some(new_idx_local) = self.try_as_local(idx, location)
915 && idx_local != new_idx_local
916 {
917 projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
918 self.reused_locals.insert(new_idx_local);
919 }
920 }
921 }
922
923 if Cow::is_owned(&projection) {
924 place.projection = self.tcx.mk_place_elems(&projection);
925 }
926
927 trace!(?place);
928 }
929
930 #[instrument(level = "trace", skip(self), ret)]
933 fn compute_place_value(
934 &mut self,
935 place: Place<'tcx>,
936 location: Location,
937 ) -> Result<VnIndex, PlaceRef<'tcx>> {
938 let mut place_ref = place.as_ref();
941
942 let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
944 let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
946 for (index, proj) in place.projection.iter().enumerate() {
947 if let Some(local) = self.try_as_local(value, location) {
948 place_ref = PlaceRef { local, projection: &place.projection[index..] };
952 }
953
954 let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
955 return Err(place_ref);
956 };
957 let Some(ty_and_value) = self.project(place_ty, value, proj) else {
958 return Err(place_ref);
959 };
960 (place_ty, value) = ty_and_value;
961 }
962
963 Ok(value)
964 }
965
966 #[instrument(level = "trace", skip(self), ret)]
969 fn simplify_place_value(
970 &mut self,
971 place: &mut Place<'tcx>,
972 location: Location,
973 ) -> Option<VnIndex> {
974 self.simplify_place_projection(place, location);
975
976 match self.compute_place_value(*place, location) {
977 Ok(value) => {
978 if let Some(new_place) = self.try_as_place(value, location, true)
979 && (new_place.local != place.local
980 || new_place.projection.len() < place.projection.len())
981 {
982 *place = new_place;
983 self.reused_locals.insert(new_place.local);
984 }
985 Some(value)
986 }
987 Err(place_ref) => {
988 if place_ref.local != place.local
989 || place_ref.projection.len() < place.projection.len()
990 {
991 *place = place_ref.project_deeper(&[], self.tcx);
993 self.reused_locals.insert(place_ref.local);
994 }
995 None
996 }
997 }
998 }
999
1000 #[instrument(level = "trace", skip(self), ret)]
1001 fn simplify_operand(
1002 &mut self,
1003 operand: &mut Operand<'tcx>,
1004 location: Location,
1005 ) -> Option<VnIndex> {
1006 match *operand {
1007 Operand::Constant(ref constant) => Some(self.insert_constant(constant.const_)),
1008 Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
1009 let value = self.simplify_place_value(place, location)?;
1010 if let Some(const_) = self.try_as_constant(value) {
1011 *operand = Operand::Constant(Box::new(const_));
1012 }
1013 Some(value)
1014 }
1015 }
1016 }
1017
1018 #[instrument(level = "trace", skip(self), ret)]
1019 fn simplify_rvalue(
1020 &mut self,
1021 lhs: &Place<'tcx>,
1022 rvalue: &mut Rvalue<'tcx>,
1023 location: Location,
1024 ) -> Option<VnIndex> {
1025 let value = match *rvalue {
1026 Rvalue::Use(ref mut operand) => return self.simplify_operand(operand, location),
1028
1029 Rvalue::Repeat(ref mut op, amount) => {
1031 let op = self.simplify_operand(op, location)?;
1032 Value::Repeat(op, amount)
1033 }
1034 Rvalue::NullaryOp(op, ty) => Value::NullaryOp(op, ty),
1035 Rvalue::Aggregate(..) => return self.simplify_aggregate(lhs, rvalue, location),
1036 Rvalue::Ref(_, borrow_kind, ref mut place) => {
1037 self.simplify_place_projection(place, location);
1038 return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1039 }
1040 Rvalue::RawPtr(mutbl, ref mut place) => {
1041 self.simplify_place_projection(place, location);
1042 return self.new_pointer(*place, AddressKind::Address(mutbl));
1043 }
1044 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1045 let value = self.simplify_operand(op, location)?;
1046 Value::Cast { kind: CastKind::Transmute, value }
1047 }
1048
1049 Rvalue::Cast(ref mut kind, ref mut value, to) => {
1051 return self.simplify_cast(kind, value, to, location);
1052 }
1053 Rvalue::BinaryOp(op, box (ref mut lhs, ref mut rhs)) => {
1054 return self.simplify_binary(op, lhs, rhs, location);
1055 }
1056 Rvalue::UnaryOp(op, ref mut arg_op) => {
1057 return self.simplify_unary(op, arg_op, location);
1058 }
1059 Rvalue::Discriminant(ref mut place) => {
1060 let place = self.simplify_place_value(place, location)?;
1061 if let Some(discr) = self.simplify_discriminant(place) {
1062 return Some(discr);
1063 }
1064 Value::Discriminant(place)
1065 }
1066
1067 Rvalue::ThreadLocalRef(..) => return None,
1069 Rvalue::CopyForDeref(_) | Rvalue::ShallowInitBox(..) => {
1070 bug!("forbidden in runtime MIR: {rvalue:?}")
1071 }
1072 };
1073 let ty = rvalue.ty(self.local_decls, self.tcx);
1074 Some(self.insert(ty, value))
1075 }
1076
1077 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1078 let enum_ty = self.ty(place);
1079 if enum_ty.is_enum()
1080 && let Value::Aggregate(variant, _) = self.get(place)
1081 {
1082 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1083 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1084 }
1085
1086 None
1087 }
1088
1089 fn try_as_place_elem(
1090 &mut self,
1091 ty: Ty<'tcx>,
1092 proj: ProjectionElem<VnIndex, ()>,
1093 loc: Location,
1094 ) -> Option<PlaceElem<'tcx>> {
1095 proj.try_map(
1096 |value| {
1097 let local = self.try_as_local(value, loc)?;
1098 self.reused_locals.insert(local);
1099 Some(local)
1100 },
1101 |()| ty,
1102 )
1103 }
1104
1105 fn simplify_aggregate_to_copy(
1106 &mut self,
1107 ty: Ty<'tcx>,
1108 variant_index: VariantIdx,
1109 fields: &[VnIndex],
1110 ) -> Option<VnIndex> {
1111 let Some(&first_field) = fields.first() else { return None };
1112 let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1113
1114 if fields.iter().enumerate().any(|(index, &v)| {
1116 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1117 && copy_from_value == pointer
1118 && from_index.index() == index
1119 {
1120 return false;
1121 }
1122 true
1123 }) {
1124 return None;
1125 }
1126
1127 let mut copy_from_local_value = copy_from_value;
1128 if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1129 && let ProjectionElem::Downcast(_, read_variant) = proj
1130 {
1131 if variant_index == read_variant {
1132 copy_from_local_value = pointer;
1134 } else {
1135 return None;
1137 }
1138 }
1139
1140 if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1142 }
1143
1144 fn simplify_aggregate(
1145 &mut self,
1146 lhs: &Place<'tcx>,
1147 rvalue: &mut Rvalue<'tcx>,
1148 location: Location,
1149 ) -> Option<VnIndex> {
1150 let tcx = self.tcx;
1151 let ty = rvalue.ty(self.local_decls, tcx);
1152
1153 let Rvalue::Aggregate(box ref kind, ref mut field_ops) = *rvalue else { bug!() };
1154
1155 if field_ops.is_empty() {
1156 let is_zst = match *kind {
1157 AggregateKind::Array(..)
1158 | AggregateKind::Tuple
1159 | AggregateKind::Closure(..)
1160 | AggregateKind::CoroutineClosure(..) => true,
1161 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1163 AggregateKind::Coroutine(..) => false,
1165 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1166 };
1167
1168 if is_zst {
1169 return Some(self.insert_constant(Const::zero_sized(ty)));
1170 }
1171 }
1172
1173 let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1174 self.simplify_operand(op, location)
1175 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1176 }));
1177
1178 let variant_index = match *kind {
1179 AggregateKind::Array(..) | AggregateKind::Tuple => {
1180 assert!(!field_ops.is_empty());
1181 FIRST_VARIANT
1182 }
1183 AggregateKind::Closure(..)
1184 | AggregateKind::CoroutineClosure(..)
1185 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1186 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1187 AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1189 let field = *fields.first()?;
1190 return Some(self.insert(ty, Value::Union(active_field, field)));
1191 }
1192 AggregateKind::RawPtr(..) => {
1193 assert_eq!(field_ops.len(), 2);
1194 let [mut pointer, metadata] = fields.try_into().unwrap();
1195
1196 let mut was_updated = false;
1198 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1199 self.get(pointer)
1200 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1201 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1202 && from_mtbl == output_mtbl
1203 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1204 {
1205 pointer = cast_value;
1206 was_updated = true;
1207 }
1208
1209 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1210 field_ops[FieldIdx::ZERO] = op;
1211 }
1212
1213 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1214 }
1215 };
1216
1217 if ty.is_array()
1218 && fields.len() > 4
1219 && let Ok(&first) = fields.iter().all_equal_value()
1220 {
1221 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1222 if let Some(op) = self.try_as_operand(first, location) {
1223 *rvalue = Rvalue::Repeat(op, len);
1224 }
1225 return Some(self.insert(ty, Value::Repeat(first, len)));
1226 }
1227
1228 if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1229 let allow_complex_projection =
1233 lhs.projection[..].iter().all(PlaceElem::is_stable_offset);
1234 if let Some(place) = self.try_as_place(value, location, allow_complex_projection) {
1235 self.reused_locals.insert(place.local);
1236 *rvalue = Rvalue::Use(Operand::Copy(place));
1237 }
1238 return Some(value);
1239 }
1240
1241 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1242 }
1243
1244 #[instrument(level = "trace", skip(self), ret)]
1245 fn simplify_unary(
1246 &mut self,
1247 op: UnOp,
1248 arg_op: &mut Operand<'tcx>,
1249 location: Location,
1250 ) -> Option<VnIndex> {
1251 let mut arg_index = self.simplify_operand(arg_op, location)?;
1252 let arg_ty = self.ty(arg_index);
1253 let ret_ty = op.ty(self.tcx, arg_ty);
1254
1255 if op == UnOp::PtrMetadata {
1258 let mut was_updated = false;
1259 loop {
1260 arg_index = match self.get(arg_index) {
1261 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1270 if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1271 {
1272 inner
1273 }
1274
1275 Value::Cast {
1277 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1278 value: from,
1279 } if let Some(from) = self.ty(from).builtin_deref(true)
1280 && let ty::Array(_, len) = from.kind()
1281 && let Some(to) = self.ty(arg_index).builtin_deref(true)
1282 && let ty::Slice(..) = to.kind() =>
1283 {
1284 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1285 }
1286
1287 Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1289 if projection.is_empty() =>
1290 {
1291 reborrowed
1292 }
1293
1294 _ => break,
1295 };
1296 was_updated = true;
1297 }
1298
1299 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1300 *arg_op = op;
1301 }
1302 }
1303
1304 let value = match (op, self.get(arg_index)) {
1305 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1306 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1307 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1308 Value::BinaryOp(BinOp::Ne, lhs, rhs)
1309 }
1310 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1311 Value::BinaryOp(BinOp::Eq, lhs, rhs)
1312 }
1313 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1314 (
1316 UnOp::PtrMetadata,
1317 Value::Cast {
1318 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1319 value: inner,
1320 },
1321 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1322 && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1323 {
1324 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1325 }
1326 _ => Value::UnaryOp(op, arg_index),
1327 };
1328 Some(self.insert(ret_ty, value))
1329 }
1330
1331 #[instrument(level = "trace", skip(self), ret)]
1332 fn simplify_binary(
1333 &mut self,
1334 op: BinOp,
1335 lhs_operand: &mut Operand<'tcx>,
1336 rhs_operand: &mut Operand<'tcx>,
1337 location: Location,
1338 ) -> Option<VnIndex> {
1339 let lhs = self.simplify_operand(lhs_operand, location);
1340 let rhs = self.simplify_operand(rhs_operand, location);
1341
1342 let mut lhs = lhs?;
1345 let mut rhs = rhs?;
1346
1347 let lhs_ty = self.ty(lhs);
1348
1349 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1352 && lhs_ty.is_any_ptr()
1353 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1354 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1355 && let lhs_from = self.ty(lhs_value)
1356 && lhs_from == self.ty(rhs_value)
1357 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1358 {
1359 lhs = lhs_value;
1360 rhs = rhs_value;
1361 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1362 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1363 {
1364 *lhs_operand = lhs_op;
1365 *rhs_operand = rhs_op;
1366 }
1367 }
1368
1369 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1370 return Some(value);
1371 }
1372 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1373 let value = Value::BinaryOp(op, lhs, rhs);
1374 Some(self.insert(ty, value))
1375 }
1376
1377 fn simplify_binary_inner(
1378 &mut self,
1379 op: BinOp,
1380 lhs_ty: Ty<'tcx>,
1381 lhs: VnIndex,
1382 rhs: VnIndex,
1383 ) -> Option<VnIndex> {
1384 let reasonable_ty =
1386 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1387 if !reasonable_ty {
1388 return None;
1389 }
1390
1391 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1392
1393 let mut as_bits = |value: VnIndex| {
1394 let constant = self.eval_to_const(value)?;
1395 if layout.backend_repr.is_scalar() {
1396 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1397 scalar.to_bits(constant.layout.size).discard_err()
1398 } else {
1399 None
1401 }
1402 };
1403
1404 use Either::{Left, Right};
1406 let a = as_bits(lhs).map_or(Right(lhs), Left);
1407 let b = as_bits(rhs).map_or(Right(rhs), Left);
1408
1409 let result = match (op, a, b) {
1410 (
1412 BinOp::Add
1413 | BinOp::AddWithOverflow
1414 | BinOp::AddUnchecked
1415 | BinOp::BitOr
1416 | BinOp::BitXor,
1417 Left(0),
1418 Right(p),
1419 )
1420 | (
1421 BinOp::Add
1422 | BinOp::AddWithOverflow
1423 | BinOp::AddUnchecked
1424 | BinOp::BitOr
1425 | BinOp::BitXor
1426 | BinOp::Sub
1427 | BinOp::SubWithOverflow
1428 | BinOp::SubUnchecked
1429 | BinOp::Offset
1430 | BinOp::Shl
1431 | BinOp::Shr,
1432 Right(p),
1433 Left(0),
1434 )
1435 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1436 | (
1437 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1438 Right(p),
1439 Left(1),
1440 ) => p,
1441 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1443 if ones == layout.size.truncate(u128::MAX)
1444 || (layout.ty.is_bool() && ones == 1) =>
1445 {
1446 p
1447 }
1448 (
1450 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1451 _,
1452 Left(0),
1453 )
1454 | (BinOp::Rem, _, Left(1))
1455 | (
1456 BinOp::Mul
1457 | BinOp::MulWithOverflow
1458 | BinOp::MulUnchecked
1459 | BinOp::Div
1460 | BinOp::Rem
1461 | BinOp::BitAnd
1462 | BinOp::Shl
1463 | BinOp::Shr,
1464 Left(0),
1465 _,
1466 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1467 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1469 if ones == layout.size.truncate(u128::MAX)
1470 || (layout.ty.is_bool() && ones == 1) =>
1471 {
1472 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1473 }
1474 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1476 if a == b =>
1477 {
1478 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1479 }
1480 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1485 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1486 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1487 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1488 _ => return None,
1489 };
1490
1491 if op.is_overflowing() {
1492 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1493 let false_val = self.insert_bool(false);
1494 Some(self.insert_tuple(ty, &[result, false_val]))
1495 } else {
1496 Some(result)
1497 }
1498 }
1499
1500 fn simplify_cast(
1501 &mut self,
1502 initial_kind: &mut CastKind,
1503 initial_operand: &mut Operand<'tcx>,
1504 to: Ty<'tcx>,
1505 location: Location,
1506 ) -> Option<VnIndex> {
1507 use CastKind::*;
1508 use rustc_middle::ty::adjustment::PointerCoercion::*;
1509
1510 let mut kind = *initial_kind;
1511 let mut value = self.simplify_operand(initial_operand, location)?;
1512 let mut from = self.ty(value);
1513 if from == to {
1514 return Some(value);
1515 }
1516
1517 if let CastKind::PointerCoercion(ReifyFnPointer | ClosureFnPointer(_), _) = kind {
1518 return Some(self.new_opaque(to));
1521 }
1522
1523 let mut was_ever_updated = false;
1524 loop {
1525 let mut was_updated_this_iteration = false;
1526
1527 if let Transmute = kind
1532 && from.is_raw_ptr()
1533 && to.is_raw_ptr()
1534 && self.pointers_have_same_metadata(from, to)
1535 {
1536 kind = PtrToPtr;
1537 was_updated_this_iteration = true;
1538 }
1539
1540 if let PtrToPtr = kind
1543 && let Value::RawPtr { pointer, .. } = self.get(value)
1544 && let ty::RawPtr(to_pointee, _) = to.kind()
1545 && to_pointee.is_sized(self.tcx, self.typing_env())
1546 {
1547 from = self.ty(pointer);
1548 value = pointer;
1549 was_updated_this_iteration = true;
1550 if from == to {
1551 return Some(pointer);
1552 }
1553 }
1554
1555 if let Transmute = kind
1558 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1559 && let Some((field_idx, field_ty)) =
1560 self.value_is_all_in_one_field(from, variant_idx)
1561 {
1562 from = field_ty;
1563 value = field_values[field_idx.as_usize()];
1564 was_updated_this_iteration = true;
1565 if field_ty == to {
1566 return Some(value);
1567 }
1568 }
1569
1570 if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1572 let inner_from = self.ty(inner_value);
1573 let new_kind = match (inner_kind, kind) {
1574 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1578 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1582 Some(Transmute)
1583 }
1584 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1587 Some(Transmute)
1588 }
1589 (Transmute, Transmute)
1592 if !self.type_may_have_niche_of_interest_to_backend(from) =>
1593 {
1594 Some(Transmute)
1595 }
1596 _ => None,
1597 };
1598 if let Some(new_kind) = new_kind {
1599 kind = new_kind;
1600 from = inner_from;
1601 value = inner_value;
1602 was_updated_this_iteration = true;
1603 if inner_from == to {
1604 return Some(inner_value);
1605 }
1606 }
1607 }
1608
1609 if was_updated_this_iteration {
1610 was_ever_updated = true;
1611 } else {
1612 break;
1613 }
1614 }
1615
1616 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1617 *initial_operand = op;
1618 *initial_kind = kind;
1619 }
1620
1621 Some(self.insert(to, Value::Cast { kind, value }))
1622 }
1623
1624 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1625 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1626 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1627 if left_meta_ty == right_meta_ty {
1628 true
1629 } else if let Ok(left) =
1630 self.tcx.try_normalize_erasing_regions(self.typing_env(), left_meta_ty)
1631 && let Ok(right) =
1632 self.tcx.try_normalize_erasing_regions(self.typing_env(), right_meta_ty)
1633 {
1634 left == right
1635 } else {
1636 false
1637 }
1638 }
1639
1640 fn type_may_have_niche_of_interest_to_backend(&self, ty: Ty<'tcx>) -> bool {
1647 let Ok(layout) = self.ecx.layout_of(ty) else {
1648 return true;
1650 };
1651
1652 if layout.uninhabited {
1653 return true;
1654 }
1655
1656 match layout.backend_repr {
1657 BackendRepr::Scalar(a) => !a.is_always_valid(&self.ecx),
1658 BackendRepr::ScalarPair(a, b) => {
1659 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1660 }
1661 BackendRepr::SimdVector { .. } | BackendRepr::Memory { .. } => false,
1662 }
1663 }
1664
1665 fn value_is_all_in_one_field(
1666 &self,
1667 ty: Ty<'tcx>,
1668 variant: VariantIdx,
1669 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1670 if let Ok(layout) = self.ecx.layout_of(ty)
1671 && let abi::Variants::Single { index } = layout.variants
1672 && index == variant
1673 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1674 && layout.size == field_layout.size
1675 {
1676 Some((field_idx, field_layout.ty))
1680 } else if let ty::Adt(adt, args) = ty.kind()
1681 && adt.is_struct()
1682 && adt.repr().transparent()
1683 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1684 {
1685 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args)))
1686 } else {
1687 None
1688 }
1689 }
1690}
1691
1692fn op_to_prop_const<'tcx>(
1693 ecx: &mut InterpCx<'tcx, DummyMachine>,
1694 op: &OpTy<'tcx>,
1695) -> Option<ConstValue> {
1696 if op.layout.is_unsized() {
1698 return None;
1699 }
1700
1701 if op.layout.is_zst() {
1703 return Some(ConstValue::ZeroSized);
1704 }
1705
1706 if !matches!(op.layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) {
1709 return None;
1710 }
1711
1712 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1714 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1715 {
1716 if !scalar.try_to_scalar_int().is_ok() {
1717 return None;
1721 }
1722 return Some(ConstValue::Scalar(scalar));
1723 }
1724
1725 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1728 let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
1729
1730 let alloc_ref = ecx.get_ptr_alloc(mplace.ptr(), size).discard_err()??;
1734 if alloc_ref.has_provenance() {
1735 return None;
1736 }
1737
1738 let pointer = mplace.ptr().into_pointer_or_addr().ok()?;
1739 let (prov, offset) = pointer.prov_and_relative_offset();
1740 let alloc_id = prov.alloc_id();
1741 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1742
1743 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1747 && alloc.inner().align >= op.layout.align.abi
1750 {
1751 return Some(ConstValue::Indirect { alloc_id, offset });
1752 }
1753 }
1754
1755 let alloc_id =
1757 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1758 let value = ConstValue::Indirect { alloc_id, offset: Size::ZERO };
1759
1760 if ecx.tcx.global_alloc(alloc_id).unwrap_memory().inner().provenance().ptrs().is_empty() {
1764 return Some(value);
1765 }
1766
1767 None
1768}
1769
1770impl<'tcx> VnState<'_, '_, 'tcx> {
1771 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1774 if let Some(const_) = self.try_as_constant(index) {
1775 Some(Operand::Constant(Box::new(const_)))
1776 } else if let Some(place) = self.try_as_place(index, location, false) {
1777 self.reused_locals.insert(place.local);
1778 Some(Operand::Copy(place))
1779 } else {
1780 None
1781 }
1782 }
1783
1784 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1786 if let Value::Constant { value, disambiguator: None } = self.get(index) {
1790 debug_assert!(value.is_deterministic());
1791 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1792 }
1793
1794 let op = self.eval_to_const(index)?;
1795 if op.layout.is_unsized() {
1796 return None;
1798 }
1799
1800 let value = op_to_prop_const(&mut self.ecx, op)?;
1801
1802 assert!(!value.may_have_provenance(self.tcx, op.layout.size));
1806
1807 let const_ = Const::Val(value, op.layout.ty);
1808 Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_ })
1809 }
1810
1811 #[instrument(level = "trace", skip(self), ret)]
1815 fn try_as_place(
1816 &mut self,
1817 mut index: VnIndex,
1818 loc: Location,
1819 allow_complex_projection: bool,
1820 ) -> Option<Place<'tcx>> {
1821 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
1822 loop {
1823 if let Some(local) = self.try_as_local(index, loc) {
1824 projection.reverse();
1825 let place =
1826 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
1827 return Some(place);
1828 } else if projection.last() == Some(&PlaceElem::Deref) {
1829 return None;
1833 } else if let Value::Projection(pointer, proj) = self.get(index)
1834 && (allow_complex_projection || proj.is_stable_offset())
1835 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
1836 {
1837 projection.push(proj);
1838 index = pointer;
1839 } else {
1840 return None;
1841 }
1842 }
1843 }
1844
1845 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
1848 let other = self.rev_locals.get(index)?;
1849 other
1850 .iter()
1851 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
1852 .copied()
1853 }
1854}
1855
1856impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
1857 fn tcx(&self) -> TyCtxt<'tcx> {
1858 self.tcx
1859 }
1860
1861 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
1862 self.simplify_place_projection(place, location);
1863 if context.is_mutating_use() && place.is_indirect() {
1864 self.invalidate_derefs();
1866 }
1867 self.super_place(place, context, location);
1868 }
1869
1870 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1871 self.simplify_operand(operand, location);
1872 self.super_operand(operand, location);
1873 }
1874
1875 fn visit_assign(
1876 &mut self,
1877 lhs: &mut Place<'tcx>,
1878 rvalue: &mut Rvalue<'tcx>,
1879 location: Location,
1880 ) {
1881 self.simplify_place_projection(lhs, location);
1882
1883 let value = self.simplify_rvalue(lhs, rvalue, location);
1884 if let Some(value) = value {
1885 if let Some(const_) = self.try_as_constant(value) {
1886 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)));
1887 } else if let Some(place) = self.try_as_place(value, location, false)
1888 && *rvalue != Rvalue::Use(Operand::Move(place))
1889 && *rvalue != Rvalue::Use(Operand::Copy(place))
1890 {
1891 *rvalue = Rvalue::Use(Operand::Copy(place));
1892 self.reused_locals.insert(place.local);
1893 }
1894 }
1895
1896 if lhs.is_indirect() {
1897 self.invalidate_derefs();
1899 }
1900
1901 if let Some(local) = lhs.as_local()
1902 && self.ssa.is_ssa(local)
1903 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
1904 && self.local_decls[local].ty == rvalue_ty
1907 {
1908 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
1909 self.assign(local, value);
1910 }
1911 }
1912
1913 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1914 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
1915 if let Some(local) = destination.as_local()
1916 && self.ssa.is_ssa(local)
1917 {
1918 let ty = self.local_decls[local].ty;
1919 let opaque = self.new_opaque(ty);
1920 self.assign(local, opaque);
1921 }
1922 }
1923 if terminator.kind.can_write_to_memory() {
1925 self.invalidate_derefs();
1926 }
1927 self.super_terminator(terminator, location);
1928 }
1929}
1930
1931struct StorageRemover<'tcx> {
1932 tcx: TyCtxt<'tcx>,
1933 reused_locals: DenseBitSet<Local>,
1934}
1935
1936impl<'tcx> MutVisitor<'tcx> for StorageRemover<'tcx> {
1937 fn tcx(&self) -> TyCtxt<'tcx> {
1938 self.tcx
1939 }
1940
1941 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
1942 if let Operand::Move(place) = *operand
1943 && !place.is_indirect_first_projection()
1944 && self.reused_locals.contains(place.local)
1945 {
1946 *operand = Operand::Copy(place);
1947 }
1948 }
1949
1950 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
1951 match stmt.kind {
1952 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
1954 if self.reused_locals.contains(l) =>
1955 {
1956 stmt.make_nop(true)
1957 }
1958 _ => self.super_statement(stmt, loc),
1959 }
1960 }
1961}