1use 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, Unnormalized};
120use rustc_mir_dataflow::{Analysis, ResultsCursor};
121use rustc_span::DUMMY_SP;
122use smallvec::SmallVec;
123use tracing::{debug, instrument, trace};
124
125use crate::ssa::{MaybeUninitializedLocals, SsaLocals};
126
127pub(super) struct GVN;
128
129impl<'tcx> crate::MirPass<'tcx> for GVN {
130 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
131 sess.mir_opt_level() >= 2
132 }
133
134 #[instrument(level = "trace", skip(self, tcx, body))]
135 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
136 debug!(def_id = ?body.source.def_id());
137
138 let typing_env = body.typing_env(tcx);
139 let ssa = SsaLocals::new(tcx, body, typing_env);
140 let dominators = body.basic_blocks.dominators().clone();
142
143 let arena = DroplessArena::default();
144 let mut state =
145 VnState::new(tcx, body, typing_env, &ssa, dominators, &body.local_decls, &arena);
146
147 for local in body.args_iter().filter(|&local| ssa.is_ssa(local)) {
148 let opaque = state.new_argument(body.local_decls[local].ty);
149 state.assign(local, opaque);
150 }
151
152 let reverse_postorder = body.basic_blocks.reverse_postorder().to_vec();
153 for bb in reverse_postorder {
154 let data = &mut body.basic_blocks.as_mut_preserves_cfg()[bb];
155 state.visit_basic_block_data(bb, data);
156 }
157
158 let storage_to_remove = if tcx.sess.emit_lifetime_markers() {
162 let maybe_uninit = MaybeUninitializedLocals
163 .iterate_to_fixpoint(tcx, body, Some("mir_opt::gvn"))
164 .into_results_cursor(body);
165
166 let mut storage_checker = StorageChecker {
167 reused_locals: &state.reused_locals,
168 storage_to_remove: DenseBitSet::new_empty(body.local_decls.len()),
169 maybe_uninit,
170 };
171
172 for (bb, data) in traversal::reachable(body) {
173 storage_checker.visit_basic_block_data(bb, data);
174 }
175
176 Some(storage_checker.storage_to_remove)
177 } else {
178 None
179 };
180
181 let storage_to_remove = storage_to_remove.as_ref().unwrap_or(&state.reused_locals);
183 debug!(?storage_to_remove);
184
185 StorageRemover { tcx, reused_locals: &state.reused_locals, storage_to_remove }
186 .visit_body_preserves_cfg(body);
187 }
188
189 fn is_required(&self) -> bool {
190 false
191 }
192}
193
194newtype_index! {
195 #[debug_format = "_v{}"]
197 struct VnIndex {}
198}
199
200#[derive(Copy, Clone, Debug, Eq)]
204struct VnOpaque;
205impl PartialEq for VnOpaque {
206 fn eq(&self, _: &VnOpaque) -> bool {
207 unreachable!()
209 }
210}
211impl Hash for VnOpaque {
212 fn hash<T: Hasher>(&self, _: &mut T) {
213 unreachable!()
215 }
216}
217
218#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
219enum AddressKind {
220 Ref(BorrowKind),
221 Address(RawPtrKind),
222}
223
224#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
225enum AddressBase {
226 Local(Local),
228 Deref(VnIndex),
230}
231
232#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
233enum Value<'a, 'tcx> {
234 Opaque(VnOpaque),
237 Argument(VnOpaque),
239 Constant {
241 value: Const<'tcx>,
242 disambiguator: Option<VnOpaque>,
246 },
247
248 Aggregate(VariantIdx, &'a [VnIndex]),
252 Union(FieldIdx, VnIndex),
254 RawPtr {
256 pointer: VnIndex,
258 metadata: VnIndex,
260 },
261 Repeat(VnIndex, ty::Const<'tcx>),
263 Address {
265 base: AddressBase,
266 projection: &'a [ProjectionElem<VnIndex, Ty<'tcx>>],
269 kind: AddressKind,
270 provenance: VnOpaque,
272 },
273
274 Projection(VnIndex, ProjectionElem<VnIndex, ()>),
277 Discriminant(VnIndex),
279
280 RuntimeChecks(RuntimeChecks),
282 UnaryOp(UnOp, VnIndex),
283 BinaryOp(BinOp, VnIndex, VnIndex),
284 Cast {
285 kind: CastKind,
286 value: VnIndex,
287 },
288}
289
290struct ValueSet<'a, 'tcx> {
296 indices: HashTable<VnIndex>,
297 hashes: IndexVec<VnIndex, u64>,
298 values: IndexVec<VnIndex, Value<'a, 'tcx>>,
299 types: IndexVec<VnIndex, Ty<'tcx>>,
300}
301
302impl<'a, 'tcx> ValueSet<'a, 'tcx> {
303 fn new(num_values: usize) -> ValueSet<'a, 'tcx> {
304 ValueSet {
305 indices: HashTable::with_capacity(num_values),
306 hashes: IndexVec::with_capacity(num_values),
307 values: IndexVec::with_capacity(num_values),
308 types: IndexVec::with_capacity(num_values),
309 }
310 }
311
312 #[inline]
315 fn insert_unique(
316 &mut self,
317 ty: Ty<'tcx>,
318 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
319 ) -> VnIndex {
320 let value = value(VnOpaque);
321
322 debug_assert!(match value {
323 Value::Opaque(_) | Value::Argument(_) | Value::Address { .. } => true,
324 Value::Constant { disambiguator, .. } => disambiguator.is_some(),
325 _ => false,
326 });
327
328 let index = self.hashes.push(0);
329 let _index = self.types.push(ty);
330 debug_assert_eq!(index, _index);
331 let _index = self.values.push(value);
332 debug_assert_eq!(index, _index);
333 index
334 }
335
336 #[allow(rustc::disallowed_pass_by_ref)] fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> (VnIndex, bool) {
340 debug_assert!(match value {
341 Value::Opaque(_) | Value::Address { .. } => false,
342 Value::Constant { disambiguator, .. } => disambiguator.is_none(),
343 _ => true,
344 });
345
346 let hash: u64 = {
347 let mut h = FxHasher::default();
348 value.hash(&mut h);
349 ty.hash(&mut h);
350 h.finish()
351 };
352
353 let eq = |index: &VnIndex| self.values[*index] == value && self.types[*index] == ty;
354 let hasher = |index: &VnIndex| self.hashes[*index];
355 match self.indices.entry(hash, eq, hasher) {
356 Entry::Occupied(entry) => {
357 let index = *entry.get();
358 (index, false)
359 }
360 Entry::Vacant(entry) => {
361 let index = self.hashes.push(hash);
362 entry.insert(index);
363 let _index = self.values.push(value);
364 debug_assert_eq!(index, _index);
365 let _index = self.types.push(ty);
366 debug_assert_eq!(index, _index);
367 (index, true)
368 }
369 }
370 }
371
372 #[inline]
374 fn value(&self, index: VnIndex) -> Value<'a, 'tcx> {
375 self.values[index]
376 }
377
378 #[inline]
380 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
381 self.types[index]
382 }
383}
384
385struct VnState<'body, 'a, 'tcx> {
386 tcx: TyCtxt<'tcx>,
387 ecx: InterpCx<'tcx, DummyMachine>,
388 local_decls: &'body LocalDecls<'tcx>,
389 is_coroutine: bool,
390 locals: IndexVec<Local, Option<VnIndex>>,
392 rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
395 values: ValueSet<'a, 'tcx>,
396 evaluated: IndexVec<VnIndex, Option<Option<&'a OpTy<'tcx>>>>,
401 ssa: &'body SsaLocals,
402 dominators: Dominators<BasicBlock>,
403 reused_locals: DenseBitSet<Local>,
404 arena: &'a DroplessArena,
405}
406
407impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> {
408 fn new(
409 tcx: TyCtxt<'tcx>,
410 body: &Body<'tcx>,
411 typing_env: ty::TypingEnv<'tcx>,
412 ssa: &'body SsaLocals,
413 dominators: Dominators<BasicBlock>,
414 local_decls: &'body LocalDecls<'tcx>,
415 arena: &'a DroplessArena,
416 ) -> Self {
417 let num_values =
422 2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
423 + 4 * body.basic_blocks.len();
424 VnState {
425 tcx,
426 ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
427 local_decls,
428 is_coroutine: body.coroutine.is_some(),
429 locals: IndexVec::from_elem(None, local_decls),
430 rev_locals: IndexVec::with_capacity(num_values),
431 values: ValueSet::new(num_values),
432 evaluated: IndexVec::with_capacity(num_values),
433 ssa,
434 dominators,
435 reused_locals: DenseBitSet::new_empty(local_decls.len()),
436 arena,
437 }
438 }
439
440 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
441 self.ecx.typing_env()
442 }
443
444 fn insert_unique(
445 &mut self,
446 ty: Ty<'tcx>,
447 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
448 ) -> VnIndex {
449 let index = self.values.insert_unique(ty, value);
450 let _index = self.evaluated.push(None);
451 debug_assert_eq!(index, _index);
452 let _index = self.rev_locals.push(SmallVec::new());
453 debug_assert_eq!(index, _index);
454 index
455 }
456
457 #[instrument(level = "trace", skip(self), ret)]
458 fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
459 let (index, new) = self.values.insert(ty, value);
460 if new {
461 let _index = self.evaluated.push(None);
463 debug_assert_eq!(index, _index);
464 let _index = self.rev_locals.push(SmallVec::new());
465 debug_assert_eq!(index, _index);
466 }
467 index
468 }
469
470 #[instrument(level = "trace", skip(self), ret)]
473 fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
474 let index = self.insert_unique(ty, Value::Opaque);
475 self.evaluated[index] = Some(None);
476 index
477 }
478
479 #[instrument(level = "trace", skip(self), ret)]
480 fn new_argument(&mut self, ty: Ty<'tcx>) -> VnIndex {
481 let index = self.insert_unique(ty, Value::Argument);
482 self.evaluated[index] = Some(None);
483 index
484 }
485
486 #[instrument(level = "trace", skip(self), ret)]
488 fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
489 let pty = place.ty(self.local_decls, self.tcx).ty;
490 let ty = match kind {
491 AddressKind::Ref(bk) => {
492 Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
493 }
494 AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
495 };
496
497 let mut projection = place.projection.iter();
498 let base = if place.is_indirect_first_projection() {
499 let base = self.locals[place.local]?;
500 projection.next();
502 AddressBase::Deref(base)
503 } else if self.ssa.is_ssa(place.local) {
504 AddressBase::Local(place.local)
506 } else {
507 return None;
508 };
509 let projection =
511 projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
512 let projection = self.arena.try_alloc_from_iter(projection).ok()?;
513
514 let index = self.insert_unique(ty, |provenance| Value::Address {
515 base,
516 projection,
517 kind,
518 provenance,
519 });
520 Some(index)
521 }
522
523 #[instrument(level = "trace", skip(self), ret)]
524 fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
525 if is_deterministic(value) {
526 let constant = Value::Constant { value, disambiguator: None };
528 self.insert(value.ty(), constant)
529 } else {
530 self.insert_unique(value.ty(), |disambiguator| Value::Constant {
533 value,
534 disambiguator: Some(disambiguator),
535 })
536 }
537 }
538
539 #[inline]
540 fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
541 self.values.value(index)
542 }
543
544 #[inline]
545 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
546 self.values.ty(index)
547 }
548
549 #[instrument(level = "trace", skip(self))]
551 fn assign(&mut self, local: Local, value: VnIndex) {
552 debug_assert!(self.ssa.is_ssa(local));
553 self.locals[local] = Some(value);
554 self.rev_locals[value].push(local);
555 }
556
557 fn insert_bool(&mut self, flag: bool) -> VnIndex {
558 let value = Const::from_bool(self.tcx, flag);
560 debug_assert!(is_deterministic(value));
561 self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
562 }
563
564 fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
565 let value = Const::from_scalar(self.tcx, scalar, ty);
567 debug_assert!(is_deterministic(value));
568 self.insert(ty, Value::Constant { value, disambiguator: None })
569 }
570
571 fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
572 self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
573 }
574
575 #[instrument(level = "trace", skip(self), ret)]
576 fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
577 use Value::*;
578 let ty = self.ty(value);
579 let ty = if !self.is_coroutine || ty.is_scalar() {
581 self.ecx.layout_of(ty).ok()?
582 } else {
583 return None;
584 };
585 let op = match self.get(value) {
586 _ if ty.is_zst() => ImmTy::uninit(ty).into(),
587
588 Opaque(_) | Argument(_) => return None,
589 RuntimeChecks(..) => return None,
591
592 Repeat(value, _count) => {
597 let value = self.eval_to_const(value)?;
598 if value.is_immediate_uninit() {
599 ImmTy::uninit(ty).into()
600 } else {
601 return None;
602 }
603 }
604 Constant { ref value, disambiguator: _ } => {
605 self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
606 }
607 Aggregate(variant, ref fields) => {
608 let fields =
609 fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
610 let variant = if ty.ty.is_enum() { Some(variant) } else { None };
611 let (BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) = ty.backend_repr
612 else {
613 return None;
614 };
615 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
616 let variant_dest = if let Some(variant) = variant {
617 self.ecx.project_downcast(&dest, variant).discard_err()?
618 } else {
619 dest.clone()
620 };
621 for (field_index, op) in fields.into_iter().enumerate() {
622 let field_dest = self
623 .ecx
624 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
625 .discard_err()?;
626 self.ecx.copy_op(op, &field_dest).discard_err()?;
627 }
628 self.ecx
629 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
630 .discard_err()?;
631 self.ecx
632 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
633 .discard_err()?;
634 dest.into()
635 }
636 Union(active_field, field) => {
637 let field = self.eval_to_const(field)?;
638 if field.layout.layout.is_zst() {
639 ImmTy::from_immediate(Immediate::Uninit, ty).into()
640 } else if matches!(
641 ty.backend_repr,
642 BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)
643 ) {
644 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
645 let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
646 self.ecx.copy_op(field, &field_dest).discard_err()?;
647 self.ecx
648 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
649 .discard_err()?;
650 dest.into()
651 } else {
652 return None;
653 }
654 }
655 RawPtr { pointer, metadata } => {
656 let pointer = self.eval_to_const(pointer)?;
657 let metadata = self.eval_to_const(metadata)?;
658
659 let data = self.ecx.read_pointer(pointer).discard_err()?;
661 let meta = if metadata.layout.is_zst() {
662 MemPlaceMeta::None
663 } else {
664 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
665 };
666 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
667 ImmTy::from_immediate(ptr_imm, ty).into()
668 }
669
670 Projection(base, elem) => {
671 let base = self.eval_to_const(base)?;
672 let elem = elem.try_map(|_| None, |()| ty.ty)?;
675 self.ecx.project(base, elem).discard_err()?
676 }
677 Address { base, projection, .. } => {
678 debug_assert!(!projection.contains(&ProjectionElem::Deref));
679 let pointer = match base {
680 AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
681 AddressBase::Local(_) => return None,
683 };
684 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
685 for elem in projection {
686 let elem = elem.try_map(|_| None, |ty| ty)?;
689 mplace = self.ecx.project(&mplace, elem).discard_err()?;
690 }
691 let pointer = mplace.to_ref(&self.ecx);
692 ImmTy::from_immediate(pointer, ty).into()
693 }
694
695 Discriminant(base) => {
696 let base = self.eval_to_const(base)?;
697 let variant = self.ecx.read_discriminant(base).discard_err()?;
698 let discr_value =
699 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
700 discr_value.into()
701 }
702 UnaryOp(un_op, operand) => {
703 let operand = self.eval_to_const(operand)?;
704 let operand = self.ecx.read_immediate(operand).discard_err()?;
705 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
706 val.into()
707 }
708 BinaryOp(bin_op, lhs, rhs) => {
709 let lhs = self.eval_to_const(lhs)?;
710 let rhs = self.eval_to_const(rhs)?;
711 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
712 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
713 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
714 val.into()
715 }
716 Cast { kind, value } => match kind {
717 CastKind::IntToInt | CastKind::IntToFloat => {
718 let value = self.eval_to_const(value)?;
719 let value = self.ecx.read_immediate(value).discard_err()?;
720 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
721 res.into()
722 }
723 CastKind::FloatToFloat | CastKind::FloatToInt => {
724 let value = self.eval_to_const(value)?;
725 let value = self.ecx.read_immediate(value).discard_err()?;
726 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
727 res.into()
728 }
729 CastKind::Transmute | CastKind::Subtype => {
730 let value = self.eval_to_const(value)?;
731 if value.as_mplace_or_imm().is_right() {
736 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
737 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
738 s1.size(&self.ecx) == s2.size(&self.ecx)
739 && !matches!(s1.primitive(), Primitive::Pointer(..))
740 }
741 (BackendRepr::ScalarPair(a1, b1), BackendRepr::ScalarPair(a2, b2)) => {
742 a1.size(&self.ecx) == a2.size(&self.ecx)
743 && b1.size(&self.ecx) == b2.size(&self.ecx)
744 && b1.align(&self.ecx) == b2.align(&self.ecx)
746 && !matches!(a1.primitive(), Primitive::Pointer(..))
748 && !matches!(b1.primitive(), Primitive::Pointer(..))
749 }
750 _ => false,
751 };
752 if !can_transmute {
753 return None;
754 }
755 }
756 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
757 }
758 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
759 let src = self.eval_to_const(value)?;
760 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
761 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
762 self.ecx
763 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
764 .discard_err()?;
765 dest.into()
766 }
767 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
768 let src = self.eval_to_const(value)?;
769 let src = self.ecx.read_immediate(src).discard_err()?;
770 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
771 ret.into()
772 }
773 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
774 let src = self.eval_to_const(value)?;
775 let src = self.ecx.read_immediate(src).discard_err()?;
776 ImmTy::from_immediate(*src, ty).into()
777 }
778 _ => return None,
779 },
780 };
781 Some(op)
782 }
783
784 fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
785 if let Some(op) = self.evaluated[index] {
786 return op;
787 }
788 let op = self.eval_to_const_inner(index);
789 self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
790 self.evaluated[index].unwrap()
791 }
792
793 #[instrument(level = "trace", skip(self), ret)]
795 fn dereference_address(
796 &mut self,
797 base: AddressBase,
798 projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
799 ) -> Option<VnIndex> {
800 let (mut place_ty, mut value) = match base {
801 AddressBase::Local(local) => {
803 let local = self.locals[local]?;
804 let place_ty = PlaceTy::from_ty(self.ty(local));
805 (place_ty, local)
806 }
807 AddressBase::Deref(reborrow) => {
809 let place_ty = PlaceTy::from_ty(self.ty(reborrow));
810 self.project(place_ty, reborrow, ProjectionElem::Deref)?
811 }
812 };
813 for &proj in projection {
814 (place_ty, value) = self.project(place_ty, value, proj)?;
815 }
816 Some(value)
817 }
818
819 #[instrument(level = "trace", skip(self), ret)]
820 fn project(
821 &mut self,
822 place_ty: PlaceTy<'tcx>,
823 value: VnIndex,
824 proj: ProjectionElem<VnIndex, Ty<'tcx>>,
825 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
826 let projection_ty = place_ty.projection_ty(self.tcx, proj);
827 let proj = match proj {
828 ProjectionElem::Deref => {
829 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
830 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
831 {
832 if let Value::Address { base, projection, .. } = self.get(value)
833 && let Some(value) = self.dereference_address(base, projection)
834 {
835 return Some((projection_ty, value));
836 }
837 if projection_ty.ty.is_ref() {
847 return None;
848 }
849
850 let deref = self
853 .insert(projection_ty.ty, Value::Projection(value, ProjectionElem::Deref));
854 return Some((projection_ty, deref));
855 } else {
856 return None;
857 }
858 }
859 ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
860 ProjectionElem::Field(f, _) => match self.get(value) {
861 Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
862 Value::Union(active, field) if active == f => return Some((projection_ty, field)),
863 Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
864 if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
865 && written_variant == read_variant =>
881 {
882 return Some((projection_ty, fields[f.as_usize()]));
883 }
884 _ => ProjectionElem::Field(f, ()),
885 },
886 ProjectionElem::Index(idx) => {
887 if let Value::Repeat(inner, _) = self.get(value) {
888 return Some((projection_ty, inner));
889 }
890 ProjectionElem::Index(idx)
891 }
892 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
893 match self.get(value) {
894 Value::Repeat(inner, _) => {
895 return Some((projection_ty, inner));
896 }
897 Value::Aggregate(_, operands) => {
898 let offset = if from_end {
899 operands.len() - offset as usize
900 } else {
901 offset as usize
902 };
903 let value = operands.get(offset).copied()?;
904 return Some((projection_ty, value));
905 }
906 _ => {}
907 };
908 ProjectionElem::ConstantIndex { offset, min_length, from_end }
909 }
910 ProjectionElem::Subslice { from, to, from_end } => {
911 ProjectionElem::Subslice { from, to, from_end }
912 }
913 ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
914 ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
915 };
916
917 let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
918 Some((projection_ty, value))
919 }
920
921 #[instrument(level = "trace", skip(self))]
923 fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
924 if place.is_indirect_first_projection()
927 && let Some(base) = self.locals[place.local]
928 && let Some(new_local) = self.try_as_local(base, location)
929 && place.local != new_local
930 {
931 place.local = new_local;
932 self.reused_locals.insert(new_local);
933 }
934
935 let mut projection = Cow::Borrowed(&place.projection[..]);
936
937 for i in 0..projection.len() {
938 let elem = projection[i];
939 if let ProjectionElem::Index(idx_local) = elem
940 && let Some(idx) = self.locals[idx_local]
941 {
942 if let Some(offset) = self.eval_to_const(idx)
943 && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
944 && let Some(min_length) = offset.checked_add(1)
945 {
946 projection.to_mut()[i] =
947 ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
948 } else if let Some(new_idx_local) = self.try_as_local(idx, location)
949 && idx_local != new_idx_local
950 {
951 projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
952 self.reused_locals.insert(new_idx_local);
953 }
954 }
955 }
956
957 if Cow::is_owned(&projection) {
958 place.projection = self.tcx.mk_place_elems(&projection);
959 }
960
961 trace!(?place);
962 }
963
964 #[instrument(level = "trace", skip(self), ret)]
967 fn compute_place_value(
968 &mut self,
969 place: Place<'tcx>,
970 location: Location,
971 ) -> Result<VnIndex, PlaceRef<'tcx>> {
972 let mut place_ref = place.as_ref();
975
976 let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
978 let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
980 for (index, proj) in place.projection.iter().enumerate() {
981 if let Some(local) = self.try_as_local(value, location) {
982 place_ref = PlaceRef { local, projection: &place.projection[index..] };
986 }
987
988 let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
989 return Err(place_ref);
990 };
991 let Some(ty_and_value) = self.project(place_ty, value, proj) else {
992 return Err(place_ref);
993 };
994 (place_ty, value) = ty_and_value;
995 }
996
997 Ok(value)
998 }
999
1000 #[instrument(level = "trace", skip(self), ret)]
1003 fn simplify_place_value(
1004 &mut self,
1005 place: &mut Place<'tcx>,
1006 location: Location,
1007 ) -> Option<VnIndex> {
1008 self.simplify_place_projection(place, location);
1009
1010 match self.compute_place_value(*place, location) {
1011 Ok(value) => {
1012 if let Some(new_place) = self.try_as_place(value, location, true)
1013 && (new_place.local != place.local
1014 || new_place.projection.len() < place.projection.len())
1015 {
1016 *place = new_place;
1017 self.reused_locals.insert(new_place.local);
1018 }
1019 Some(value)
1020 }
1021 Err(place_ref) => {
1022 if place_ref.local != place.local
1023 || place_ref.projection.len() < place.projection.len()
1024 {
1025 *place = place_ref.project_deeper(&[], self.tcx);
1027 self.reused_locals.insert(place_ref.local);
1028 }
1029 None
1030 }
1031 }
1032 }
1033
1034 #[instrument(level = "trace", skip(self), ret)]
1035 fn simplify_operand(
1036 &mut self,
1037 operand: &mut Operand<'tcx>,
1038 location: Location,
1039 ) -> Option<VnIndex> {
1040 let value = match *operand {
1041 Operand::RuntimeChecks(c) => self.insert(self.tcx.types.bool, Value::RuntimeChecks(c)),
1042 Operand::Constant(ref constant) => self.insert_constant(constant.const_),
1043 Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
1044 self.simplify_place_value(place, location)?
1045 }
1046 };
1047 if let Some(const_) = self.try_as_constant(value) {
1048 *operand = Operand::Constant(Box::new(const_));
1049 } else if let Value::RuntimeChecks(c) = self.get(value) {
1050 *operand = Operand::RuntimeChecks(c);
1051 }
1052 Some(value)
1053 }
1054
1055 #[instrument(level = "trace", skip(self), ret)]
1056 fn simplify_rvalue(
1057 &mut self,
1058 lhs: &Place<'tcx>,
1059 rvalue: &mut Rvalue<'tcx>,
1060 location: Location,
1061 ) -> Option<VnIndex> {
1062 let value = match *rvalue {
1063 Rvalue::Use(ref mut operand) => return self.simplify_operand(operand, location),
1065
1066 Rvalue::Repeat(ref mut op, amount) => {
1068 let op = self.simplify_operand(op, location)?;
1069 Value::Repeat(op, amount)
1070 }
1071 Rvalue::Aggregate(..) => return self.simplify_aggregate(rvalue, location),
1072 Rvalue::Ref(_, borrow_kind, ref mut place) => {
1073 self.simplify_place_projection(place, location);
1074 return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1075 }
1076 Rvalue::RawPtr(mutbl, ref mut place) => {
1077 self.simplify_place_projection(place, location);
1078 return self.new_pointer(*place, AddressKind::Address(mutbl));
1079 }
1080 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1081 let value = self.simplify_operand(op, location)?;
1082 Value::Cast { kind: CastKind::Transmute, value }
1083 }
1084
1085 Rvalue::Cast(ref mut kind, ref mut value, to) => {
1087 return self.simplify_cast(kind, value, to, location);
1088 }
1089 Rvalue::BinaryOp(op, box (ref mut lhs, ref mut rhs)) => {
1090 return self.simplify_binary(op, lhs, rhs, location);
1091 }
1092 Rvalue::UnaryOp(op, ref mut arg_op) => {
1093 return self.simplify_unary(op, arg_op, location);
1094 }
1095 Rvalue::Discriminant(ref mut place) => {
1096 let place = self.simplify_place_value(place, location)?;
1097 if let Some(discr) = self.simplify_discriminant(place) {
1098 return Some(discr);
1099 }
1100 Value::Discriminant(place)
1101 }
1102
1103 Rvalue::ThreadLocalRef(..) => return None,
1105 Rvalue::CopyForDeref(_) => {
1106 bug!("forbidden in runtime MIR: {rvalue:?}")
1107 }
1108 };
1109 let ty = rvalue.ty(self.local_decls, self.tcx);
1110 Some(self.insert(ty, value))
1111 }
1112
1113 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1114 let enum_ty = self.ty(place);
1115 if enum_ty.is_enum()
1116 && let Value::Aggregate(variant, _) = self.get(place)
1117 {
1118 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1119 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1120 }
1121
1122 None
1123 }
1124
1125 fn try_as_place_elem(
1126 &mut self,
1127 ty: Ty<'tcx>,
1128 proj: ProjectionElem<VnIndex, ()>,
1129 loc: Location,
1130 ) -> Option<PlaceElem<'tcx>> {
1131 proj.try_map(
1132 |value| {
1133 let local = self.try_as_local(value, loc)?;
1134 self.reused_locals.insert(local);
1135 Some(local)
1136 },
1137 |()| ty,
1138 )
1139 }
1140
1141 fn simplify_aggregate_to_copy(
1142 &mut self,
1143 ty: Ty<'tcx>,
1144 variant_index: VariantIdx,
1145 fields: &[VnIndex],
1146 ) -> Option<VnIndex> {
1147 let Some(&first_field) = fields.first() else { return None };
1148 let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1149
1150 if fields.iter().enumerate().any(|(index, &v)| {
1152 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1153 && copy_from_value == pointer
1154 && from_index.index() == index
1155 {
1156 return false;
1157 }
1158 true
1159 }) {
1160 return None;
1161 }
1162
1163 let mut copy_from_local_value = copy_from_value;
1164 if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1165 && let ProjectionElem::Downcast(_, read_variant) = proj
1166 {
1167 if variant_index == read_variant {
1168 copy_from_local_value = pointer;
1170 } else {
1171 return None;
1173 }
1174 }
1175
1176 if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1178 }
1179
1180 fn simplify_aggregate(
1181 &mut self,
1182 rvalue: &mut Rvalue<'tcx>,
1183 location: Location,
1184 ) -> Option<VnIndex> {
1185 let tcx = self.tcx;
1186 let ty = rvalue.ty(self.local_decls, tcx);
1187
1188 let Rvalue::Aggregate(box ref kind, ref mut field_ops) = *rvalue else { bug!() };
1189
1190 if field_ops.is_empty() {
1191 let is_zst = match *kind {
1192 AggregateKind::Array(..)
1193 | AggregateKind::Tuple
1194 | AggregateKind::Closure(..)
1195 | AggregateKind::CoroutineClosure(..) => true,
1196 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1198 AggregateKind::Coroutine(..) => false,
1200 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1201 };
1202
1203 if is_zst {
1204 return Some(self.insert_constant(Const::zero_sized(ty)));
1205 }
1206 }
1207
1208 let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1209 self.simplify_operand(op, location)
1210 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1211 }));
1212
1213 let variant_index = match *kind {
1214 AggregateKind::Array(..) | AggregateKind::Tuple => {
1215 assert!(!field_ops.is_empty());
1216 FIRST_VARIANT
1217 }
1218 AggregateKind::Closure(..)
1219 | AggregateKind::CoroutineClosure(..)
1220 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1221 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1222 AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1224 let field = *fields.first()?;
1225 return Some(self.insert(ty, Value::Union(active_field, field)));
1226 }
1227 AggregateKind::RawPtr(..) => {
1228 assert_eq!(field_ops.len(), 2);
1229 let [mut pointer, metadata] = fields.try_into().unwrap();
1230
1231 let mut was_updated = false;
1233 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1234 self.get(pointer)
1235 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1236 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1237 && from_mtbl == output_mtbl
1238 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1239 {
1240 pointer = cast_value;
1241 was_updated = true;
1242 }
1243
1244 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1245 field_ops[FieldIdx::ZERO] = op;
1246 }
1247
1248 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1249 }
1250 };
1251
1252 if ty.is_array()
1253 && fields.len() > 4
1254 && let Ok(&first) = fields.iter().all_equal_value()
1255 {
1256 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1257 if let Some(op) = self.try_as_operand(first, location) {
1258 *rvalue = Rvalue::Repeat(op, len);
1259 }
1260 return Some(self.insert(ty, Value::Repeat(first, len)));
1261 }
1262
1263 if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1264 if let Some(place) = self.try_as_place(value, location, true) {
1265 self.reused_locals.insert(place.local);
1266 *rvalue = Rvalue::Use(Operand::Copy(place));
1267 }
1268 return Some(value);
1269 }
1270
1271 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1272 }
1273
1274 #[instrument(level = "trace", skip(self), ret)]
1275 fn simplify_unary(
1276 &mut self,
1277 op: UnOp,
1278 arg_op: &mut Operand<'tcx>,
1279 location: Location,
1280 ) -> Option<VnIndex> {
1281 let mut arg_index = self.simplify_operand(arg_op, location)?;
1282 let arg_ty = self.ty(arg_index);
1283 let ret_ty = op.ty(self.tcx, arg_ty);
1284
1285 if op == UnOp::PtrMetadata {
1288 let mut was_updated = false;
1289 loop {
1290 arg_index = match self.get(arg_index) {
1291 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1300 if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1301 {
1302 inner
1303 }
1304
1305 Value::Cast {
1307 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1308 value: from,
1309 } if let Some(from) = self.ty(from).builtin_deref(true)
1310 && let ty::Array(_, len) = from.kind()
1311 && let Some(to) = self.ty(arg_index).builtin_deref(true)
1312 && let ty::Slice(..) = to.kind() =>
1313 {
1314 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1315 }
1316
1317 Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1319 if projection.is_empty() =>
1320 {
1321 reborrowed
1322 }
1323
1324 _ => break,
1325 };
1326 was_updated = true;
1327 }
1328
1329 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1330 *arg_op = op;
1331 }
1332 }
1333
1334 let value = match (op, self.get(arg_index)) {
1335 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1336 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1337 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1338 Value::BinaryOp(BinOp::Ne, lhs, rhs)
1339 }
1340 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1341 Value::BinaryOp(BinOp::Eq, lhs, rhs)
1342 }
1343 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1344 (
1346 UnOp::PtrMetadata,
1347 Value::Cast {
1348 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1349 value: inner,
1350 },
1351 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1352 && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1353 {
1354 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1355 }
1356 _ => Value::UnaryOp(op, arg_index),
1357 };
1358 Some(self.insert(ret_ty, value))
1359 }
1360
1361 #[instrument(level = "trace", skip(self), ret)]
1362 fn simplify_binary(
1363 &mut self,
1364 op: BinOp,
1365 lhs_operand: &mut Operand<'tcx>,
1366 rhs_operand: &mut Operand<'tcx>,
1367 location: Location,
1368 ) -> Option<VnIndex> {
1369 let lhs = self.simplify_operand(lhs_operand, location);
1370 let rhs = self.simplify_operand(rhs_operand, location);
1371
1372 let mut lhs = lhs?;
1375 let mut rhs = rhs?;
1376
1377 let lhs_ty = self.ty(lhs);
1378
1379 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1382 && lhs_ty.is_any_ptr()
1383 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1384 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1385 && let lhs_from = self.ty(lhs_value)
1386 && lhs_from == self.ty(rhs_value)
1387 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1388 {
1389 lhs = lhs_value;
1390 rhs = rhs_value;
1391 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1392 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1393 {
1394 *lhs_operand = lhs_op;
1395 *rhs_operand = rhs_op;
1396 }
1397 }
1398
1399 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1400 return Some(value);
1401 }
1402 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1403 let value = Value::BinaryOp(op, lhs, rhs);
1404 Some(self.insert(ty, value))
1405 }
1406
1407 fn simplify_binary_inner(
1408 &mut self,
1409 op: BinOp,
1410 lhs_ty: Ty<'tcx>,
1411 lhs: VnIndex,
1412 rhs: VnIndex,
1413 ) -> Option<VnIndex> {
1414 let reasonable_ty =
1416 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1417 if !reasonable_ty {
1418 return None;
1419 }
1420
1421 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1422
1423 let mut as_bits = |value: VnIndex| {
1424 let constant = self.eval_to_const(value)?;
1425 if layout.backend_repr.is_scalar() {
1426 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1427 scalar.to_bits(constant.layout.size).discard_err()
1428 } else {
1429 None
1431 }
1432 };
1433
1434 use Either::{Left, Right};
1436 let a = as_bits(lhs).map_or(Right(lhs), Left);
1437 let b = as_bits(rhs).map_or(Right(rhs), Left);
1438
1439 let result = match (op, a, b) {
1440 (
1442 BinOp::Add
1443 | BinOp::AddWithOverflow
1444 | BinOp::AddUnchecked
1445 | BinOp::BitOr
1446 | BinOp::BitXor,
1447 Left(0),
1448 Right(p),
1449 )
1450 | (
1451 BinOp::Add
1452 | BinOp::AddWithOverflow
1453 | BinOp::AddUnchecked
1454 | BinOp::BitOr
1455 | BinOp::BitXor
1456 | BinOp::Sub
1457 | BinOp::SubWithOverflow
1458 | BinOp::SubUnchecked
1459 | BinOp::Offset
1460 | BinOp::Shl
1461 | BinOp::Shr,
1462 Right(p),
1463 Left(0),
1464 )
1465 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1466 | (
1467 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1468 Right(p),
1469 Left(1),
1470 ) => p,
1471 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1473 if ones == layout.size.truncate(u128::MAX)
1474 || (layout.ty.is_bool() && ones == 1) =>
1475 {
1476 p
1477 }
1478 (
1480 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1481 _,
1482 Left(0),
1483 )
1484 | (BinOp::Rem, _, Left(1))
1485 | (
1486 BinOp::Mul
1487 | BinOp::MulWithOverflow
1488 | BinOp::MulUnchecked
1489 | BinOp::Div
1490 | BinOp::Rem
1491 | BinOp::BitAnd
1492 | BinOp::Shl
1493 | BinOp::Shr,
1494 Left(0),
1495 _,
1496 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1497 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1499 if ones == layout.size.truncate(u128::MAX)
1500 || (layout.ty.is_bool() && ones == 1) =>
1501 {
1502 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1503 }
1504 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1506 if a == b =>
1507 {
1508 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1509 }
1510 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1515 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1516 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1517 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1518 _ => return None,
1519 };
1520
1521 if op.is_overflowing() {
1522 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1523 let false_val = self.insert_bool(false);
1524 Some(self.insert_tuple(ty, &[result, false_val]))
1525 } else {
1526 Some(result)
1527 }
1528 }
1529
1530 fn simplify_cast(
1531 &mut self,
1532 initial_kind: &mut CastKind,
1533 initial_operand: &mut Operand<'tcx>,
1534 to: Ty<'tcx>,
1535 location: Location,
1536 ) -> Option<VnIndex> {
1537 use CastKind::*;
1538 use rustc_middle::ty::adjustment::PointerCoercion::*;
1539
1540 let mut kind = *initial_kind;
1541 let mut value = self.simplify_operand(initial_operand, location)?;
1542 let mut from = self.ty(value);
1543 if from == to {
1544 return Some(value);
1545 }
1546
1547 if let CastKind::PointerCoercion(ReifyFnPointer(_) | ClosureFnPointer(_), _) = kind {
1548 return Some(self.new_opaque(to));
1551 }
1552
1553 let mut was_ever_updated = false;
1554 loop {
1555 let mut was_updated_this_iteration = false;
1556
1557 if let Transmute = kind
1562 && from.is_raw_ptr()
1563 && to.is_raw_ptr()
1564 && self.pointers_have_same_metadata(from, to)
1565 {
1566 kind = PtrToPtr;
1567 was_updated_this_iteration = true;
1568 }
1569
1570 if let PtrToPtr = kind
1573 && let Value::RawPtr { pointer, .. } = self.get(value)
1574 && let ty::RawPtr(to_pointee, _) = to.kind()
1575 && to_pointee.is_sized(self.tcx, self.typing_env())
1576 {
1577 from = self.ty(pointer);
1578 value = pointer;
1579 was_updated_this_iteration = true;
1580 if from == to {
1581 return Some(pointer);
1582 }
1583 }
1584
1585 if let Transmute = kind
1588 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1589 && let Some((field_idx, field_ty)) =
1590 self.value_is_all_in_one_field(from, variant_idx)
1591 {
1592 from = field_ty;
1593 value = field_values[field_idx.as_usize()];
1594 was_updated_this_iteration = true;
1595 if field_ty == to {
1596 return Some(value);
1597 }
1598 }
1599
1600 if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1602 let inner_from = self.ty(inner_value);
1603 let new_kind = match (inner_kind, kind) {
1604 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1608 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1612 Some(Transmute)
1613 }
1614 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1617 Some(Transmute)
1618 }
1619 (Transmute, Transmute)
1622 if !self.transmute_may_have_niche_of_interest_to_backend(
1623 inner_from, from, to,
1624 ) =>
1625 {
1626 Some(Transmute)
1627 }
1628 _ => None,
1629 };
1630 if let Some(new_kind) = new_kind {
1631 kind = new_kind;
1632 from = inner_from;
1633 value = inner_value;
1634 was_updated_this_iteration = true;
1635 if inner_from == to {
1636 return Some(inner_value);
1637 }
1638 }
1639 }
1640
1641 if was_updated_this_iteration {
1642 was_ever_updated = true;
1643 } else {
1644 break;
1645 }
1646 }
1647
1648 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1649 *initial_operand = op;
1650 *initial_kind = kind;
1651 }
1652
1653 Some(self.insert(to, Value::Cast { kind, value }))
1654 }
1655
1656 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1657 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1658 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1659 if left_meta_ty == right_meta_ty {
1660 true
1661 } else if let Ok(left) = self
1662 .tcx
1663 .try_normalize_erasing_regions(self.typing_env(), Unnormalized::new_wip(left_meta_ty))
1664 && let Ok(right) = self.tcx.try_normalize_erasing_regions(
1665 self.typing_env(),
1666 Unnormalized::new_wip(right_meta_ty),
1667 )
1668 {
1669 left == right
1670 } else {
1671 false
1672 }
1673 }
1674
1675 fn transmute_may_have_niche_of_interest_to_backend(
1682 &self,
1683 from_ty: Ty<'tcx>,
1684 middle_ty: Ty<'tcx>,
1685 to_ty: Ty<'tcx>,
1686 ) -> bool {
1687 let Ok(middle_layout) = self.ecx.layout_of(middle_ty) else {
1688 return true;
1690 };
1691
1692 if middle_layout.uninhabited {
1693 return true;
1694 }
1695
1696 match middle_layout.backend_repr {
1697 BackendRepr::Scalar(mid) => {
1698 if mid.is_always_valid(&self.ecx) {
1699 false
1702 } else if let Ok(from_layout) = self.ecx.layout_of(from_ty)
1703 && !from_layout.uninhabited
1704 && from_layout.size == middle_layout.size
1705 && let BackendRepr::Scalar(from_a) = from_layout.backend_repr
1706 && let mid_range = mid.valid_range(&self.ecx)
1707 && let from_range = from_a.valid_range(&self.ecx)
1708 && mid_range.contains_range(from_range, middle_layout.size)
1709 {
1710 false
1716 } else if let Ok(to_layout) = self.ecx.layout_of(to_ty)
1717 && !to_layout.uninhabited
1718 && to_layout.size == middle_layout.size
1719 && let BackendRepr::Scalar(to_a) = to_layout.backend_repr
1720 && let mid_range = mid.valid_range(&self.ecx)
1721 && let to_range = to_a.valid_range(&self.ecx)
1722 && mid_range.contains_range(to_range, middle_layout.size)
1723 {
1724 false
1730 } else {
1731 true
1732 }
1733 }
1734 BackendRepr::ScalarPair(a, b) => {
1735 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1736 }
1737 BackendRepr::SimdVector { .. }
1738 | BackendRepr::SimdScalableVector { .. }
1739 | BackendRepr::Memory { .. } => false,
1740 }
1741 }
1742
1743 fn value_is_all_in_one_field(
1744 &self,
1745 ty: Ty<'tcx>,
1746 variant: VariantIdx,
1747 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1748 if let Ok(layout) = self.ecx.layout_of(ty)
1749 && let abi::Variants::Single { index } = layout.variants
1750 && index == variant
1751 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1752 && layout.size == field_layout.size
1753 {
1754 Some((field_idx, field_layout.ty))
1758 } else if let ty::Adt(adt, args) = ty.kind()
1759 && adt.is_struct()
1760 && adt.repr().transparent()
1761 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1762 {
1763 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args)))
1764 } else {
1765 None
1766 }
1767 }
1768}
1769
1770fn is_deterministic(c: Const<'_>) -> bool {
1779 if c.ty().is_primitive() {
1781 return true;
1782 }
1783
1784 match c {
1785 Const::Ty(..) => false,
1789 Const::Unevaluated(..) => false,
1791 Const::Val(..) => true,
1795 }
1796}
1797
1798fn may_have_provenance(tcx: TyCtxt<'_>, value: ConstValue, size: Size) -> bool {
1801 match value {
1802 ConstValue::ZeroSized | ConstValue::Scalar(Scalar::Int(_)) => return false,
1803 ConstValue::Scalar(Scalar::Ptr(..)) | ConstValue::Slice { .. } => return true,
1804 ConstValue::Indirect { alloc_id, offset } => !tcx
1805 .global_alloc(alloc_id)
1806 .unwrap_memory()
1807 .inner()
1808 .provenance()
1809 .range_empty(AllocRange::from(offset..offset + size), &tcx),
1810 }
1811}
1812
1813fn op_to_prop_const<'tcx>(
1814 ecx: &mut InterpCx<'tcx, DummyMachine>,
1815 op: &OpTy<'tcx>,
1816) -> Option<ConstValue> {
1817 if op.layout.is_unsized() {
1819 return None;
1820 }
1821
1822 if op.layout.is_zst() {
1824 return Some(ConstValue::ZeroSized);
1825 }
1826
1827 if !op.is_immediate_uninit()
1832 && !matches!(op.layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..))
1833 {
1834 return None;
1835 }
1836
1837 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1839 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1840 {
1841 if !scalar.try_to_scalar_int().is_ok() {
1842 return None;
1846 }
1847 return Some(ConstValue::Scalar(scalar));
1848 }
1849
1850 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1853 let (size, _align) = ecx.size_and_align_of_val(&mplace).discard_err()??;
1854
1855 let alloc_ref = ecx.get_ptr_alloc(mplace.ptr(), size).discard_err()??;
1859 if alloc_ref.has_provenance() {
1860 return None;
1861 }
1862
1863 let pointer = mplace.ptr().into_pointer_or_addr().ok()?;
1864 let (prov, offset) = pointer.prov_and_relative_offset();
1865 let alloc_id = prov.alloc_id();
1866 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1867
1868 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1872 && alloc.inner().align >= op.layout.align.abi
1875 {
1876 return Some(ConstValue::Indirect { alloc_id, offset });
1877 }
1878 }
1879
1880 let alloc_id =
1882 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1883 Some(ConstValue::Indirect { alloc_id, offset: Size::ZERO })
1884}
1885
1886impl<'tcx> VnState<'_, '_, 'tcx> {
1887 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1890 if let Some(const_) = self.try_as_constant(index) {
1891 Some(Operand::Constant(Box::new(const_)))
1892 } else if let Value::RuntimeChecks(c) = self.get(index) {
1893 Some(Operand::RuntimeChecks(c))
1894 } else if let Some(place) = self.try_as_place(index, location, false) {
1895 self.reused_locals.insert(place.local);
1896 Some(Operand::Copy(place))
1897 } else {
1898 None
1899 }
1900 }
1901
1902 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1904 let value = self.get(index);
1905
1906 if let Value::Constant { value, disambiguator: None } = value
1908 && let Const::Val(..) = value
1909 {
1910 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1911 }
1912
1913 if let Some(value) = self.try_as_evaluated_constant(index) {
1914 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1915 }
1916
1917 if let Value::Constant { value, disambiguator: None } = value {
1919 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1920 }
1921
1922 None
1923 }
1924
1925 fn try_as_evaluated_constant(&mut self, index: VnIndex) -> Option<Const<'tcx>> {
1926 let op = self.eval_to_const(index)?;
1927 if op.layout.is_unsized() {
1928 return None;
1930 }
1931
1932 let value = op_to_prop_const(&mut self.ecx, op)?;
1933
1934 if may_have_provenance(self.tcx, value, op.layout.size) {
1938 return None;
1939 }
1940
1941 Some(Const::Val(value, op.layout.ty))
1942 }
1943
1944 #[instrument(level = "trace", skip(self), ret)]
1948 fn try_as_place(
1949 &mut self,
1950 mut index: VnIndex,
1951 loc: Location,
1952 allow_complex_projection: bool,
1953 ) -> Option<Place<'tcx>> {
1954 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
1955 loop {
1956 if let Some(local) = self.try_as_local(index, loc) {
1957 projection.reverse();
1958 let place =
1959 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
1960 return Some(place);
1961 } else if projection.last() == Some(&PlaceElem::Deref) {
1962 return None;
1966 } else if let Value::Projection(pointer, proj) = self.get(index)
1967 && (allow_complex_projection || proj.is_stable_offset())
1968 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
1969 {
1970 if proj == PlaceElem::Deref {
1971 match self.get(pointer) {
1974 Value::Argument(_)
1975 if let Some(Mutability::Not) = self.ty(pointer).ref_mutability() => {}
1976 _ => {
1977 return None;
1978 }
1979 }
1980 }
1981 projection.push(proj);
1982 index = pointer;
1983 } else {
1984 return None;
1985 }
1986 }
1987 }
1988
1989 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
1992 let other = self.rev_locals.get(index)?;
1993 other
1994 .iter()
1995 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
1996 .copied()
1997 }
1998}
1999
2000impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
2001 fn tcx(&self) -> TyCtxt<'tcx> {
2002 self.tcx
2003 }
2004
2005 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
2006 self.simplify_place_projection(place, location);
2007 self.super_place(place, context, location);
2008 }
2009
2010 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
2011 self.simplify_operand(operand, location);
2012 self.super_operand(operand, location);
2013 }
2014
2015 fn visit_assign(
2016 &mut self,
2017 lhs: &mut Place<'tcx>,
2018 rvalue: &mut Rvalue<'tcx>,
2019 location: Location,
2020 ) {
2021 self.simplify_place_projection(lhs, location);
2022
2023 let value = self.simplify_rvalue(lhs, rvalue, location);
2024 if let Some(value) = value {
2025 if let Some(const_) = self.try_as_constant(value) {
2026 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)));
2027 } else if let Some(place) = self.try_as_place(value, location, false)
2028 && *rvalue != Rvalue::Use(Operand::Move(place))
2029 && *rvalue != Rvalue::Use(Operand::Copy(place))
2030 {
2031 *rvalue = Rvalue::Use(Operand::Copy(place));
2032 self.reused_locals.insert(place.local);
2033 }
2034 }
2035
2036 if let Some(local) = lhs.as_local()
2037 && self.ssa.is_ssa(local)
2038 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
2039 && self.local_decls[local].ty == rvalue_ty
2042 {
2043 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
2044 self.assign(local, value);
2045 }
2046 }
2047
2048 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
2049 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
2050 if let Some(local) = destination.as_local()
2051 && self.ssa.is_ssa(local)
2052 {
2053 let ty = self.local_decls[local].ty;
2054 let opaque = self.new_opaque(ty);
2055 self.assign(local, opaque);
2056 }
2057 }
2058 self.super_terminator(terminator, location);
2059 }
2060}
2061
2062struct StorageRemover<'a, 'tcx> {
2063 tcx: TyCtxt<'tcx>,
2064 reused_locals: &'a DenseBitSet<Local>,
2065 storage_to_remove: &'a DenseBitSet<Local>,
2066}
2067
2068impl<'a, 'tcx> MutVisitor<'tcx> for StorageRemover<'a, 'tcx> {
2069 fn tcx(&self) -> TyCtxt<'tcx> {
2070 self.tcx
2071 }
2072
2073 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
2074 if let Operand::Move(place) = *operand
2075 && !place.is_indirect_first_projection()
2076 && self.reused_locals.contains(place.local)
2077 {
2078 *operand = Operand::Copy(place);
2079 }
2080 }
2081
2082 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
2083 match stmt.kind {
2084 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
2086 if self.storage_to_remove.contains(l) =>
2087 {
2088 stmt.make_nop(true)
2089 }
2090 _ => self.super_statement(stmt, loc),
2091 }
2092 }
2093}
2094
2095struct StorageChecker<'a, 'tcx> {
2096 reused_locals: &'a DenseBitSet<Local>,
2097 storage_to_remove: DenseBitSet<Local>,
2098 maybe_uninit: ResultsCursor<'a, 'tcx, MaybeUninitializedLocals>,
2099}
2100
2101impl<'a, 'tcx> Visitor<'tcx> for StorageChecker<'a, 'tcx> {
2102 fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
2103 match context {
2104 PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
2109 | PlaceContext::MutatingUse(MutatingUseContext::Call)
2110 | PlaceContext::MutatingUse(MutatingUseContext::Store)
2111 | PlaceContext::MutatingUse(MutatingUseContext::Yield)
2112 | PlaceContext::NonUse(_) => {
2113 return;
2114 }
2115 PlaceContext::MutatingUse(_) | PlaceContext::NonMutatingUse(_) => {}
2117 }
2118
2119 if !self.reused_locals.contains(local) || self.storage_to_remove.contains(local) {
2121 return;
2122 }
2123
2124 self.maybe_uninit.seek_before_primary_effect(location);
2125
2126 if self.maybe_uninit.get().contains(local) {
2127 debug!(
2128 ?location,
2129 ?local,
2130 "local is reused and is maybe uninit at this location, marking it for storage statement removal"
2131 );
2132 self.storage_to_remove.insert(local);
2133 }
2134 }
2135}