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::mir::interpret::{AllocRange, GlobalAlloc};
115use rustc_middle::mir::visit::*;
116use rustc_middle::mir::*;
117use rustc_middle::ty::layout::HasTypingEnv;
118use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
119use rustc_mir_dataflow::{Analysis, ResultsCursor};
120use rustc_span::{DUMMY_SP, bug};
121use smallvec::SmallVec;
122use tracing::{debug, instrument, trace};
123
124use crate::PassPolicy;
125use crate::ssa::{MaybeUninitializedLocals, SsaLocals};
126
127pub(super) struct GVN;
128
129impl<'tcx> crate::MirPass<'tcx> for GVN {
130 fn policy(&self, ctx: &crate::PassCtx<'_>) -> PassPolicy {
131 PassPolicy::optional(ctx.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
190newtype_index! {
191 #[debug_format = "_v{}"]
193 struct VnIndex {}
194}
195
196#[derive(Copy, Clone, Debug, Eq)]
200struct VnOpaque;
201impl PartialEq for VnOpaque {
202 fn eq(&self, _: &VnOpaque) -> bool {
203 unreachable!()
205 }
206}
207impl Hash for VnOpaque {
208 fn hash<T: Hasher>(&self, _: &mut T) {
209 unreachable!()
211 }
212}
213
214#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
215enum AddressKind {
216 Ref(BorrowKind),
217 Address(RawPtrKind),
218}
219
220#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
221enum AddressBase {
222 Local(Local),
224 Deref(VnIndex),
226}
227
228#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
229enum Value<'a, 'tcx> {
230 Opaque(VnOpaque),
233 Argument(VnOpaque),
235 Constant {
237 value: Const<'tcx>,
238 disambiguator: Option<VnOpaque>,
242 },
243
244 Aggregate(VariantIdx, &'a [VnIndex]),
248 Union(FieldIdx, VnIndex),
250 RawPtr {
252 pointer: VnIndex,
254 metadata: VnIndex,
256 },
257 Repeat(VnIndex, ty::Const<'tcx>),
259 Address {
261 base: AddressBase,
262 projection: &'a [ProjectionElem<VnIndex, Ty<'tcx>>],
265 kind: AddressKind,
266 provenance: VnOpaque,
268 },
269
270 Projection(VnIndex, ProjectionElem<VnIndex, ()>),
273 Discriminant(VnIndex),
275
276 RuntimeChecks(RuntimeChecks),
278 UnaryOp(UnOp, VnIndex),
279 BinaryOp(BinOp, VnIndex, VnIndex),
280 Cast {
281 kind: CastKind,
282 value: VnIndex,
283 },
284}
285
286struct ValueSet<'a, 'tcx> {
292 indices: HashTable<VnIndex>,
293 hashes: IndexVec<VnIndex, u64>,
294 values: IndexVec<VnIndex, Value<'a, 'tcx>>,
295 types: IndexVec<VnIndex, Ty<'tcx>>,
296}
297
298impl<'a, 'tcx> ValueSet<'a, 'tcx> {
299 fn new(num_values: usize) -> ValueSet<'a, 'tcx> {
300 ValueSet {
301 indices: HashTable::with_capacity(num_values),
302 hashes: IndexVec::with_capacity(num_values),
303 values: IndexVec::with_capacity(num_values),
304 types: IndexVec::with_capacity(num_values),
305 }
306 }
307
308 #[inline]
311 fn insert_unique(
312 &mut self,
313 ty: Ty<'tcx>,
314 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
315 ) -> VnIndex {
316 let value = value(VnOpaque);
317
318 debug_assert!(match value {
319 Value::Opaque(_) | Value::Argument(_) | Value::Address { .. } => true,
320 Value::Constant { disambiguator, .. } => disambiguator.is_some(),
321 _ => false,
322 });
323
324 let index = self.hashes.push(0);
325 let _index = self.types.push(ty);
326 debug_assert_eq!(index, _index);
327 let _index = self.values.push(value);
328 debug_assert_eq!(index, _index);
329 index
330 }
331
332 #[allow(rustc::disallowed_pass_by_ref)] fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> (VnIndex, bool) {
336 debug_assert!(match value {
337 Value::Opaque(_) | Value::Address { .. } => false,
338 Value::Constant { disambiguator, .. } => disambiguator.is_none(),
339 _ => true,
340 });
341
342 let hash: u64 = {
343 let mut h = FxHasher::default();
344 value.hash(&mut h);
345 ty.hash(&mut h);
346 h.finish()
347 };
348
349 let eq = |index: &VnIndex| self.values[*index] == value && self.types[*index] == ty;
350 let hasher = |index: &VnIndex| self.hashes[*index];
351 match self.indices.entry(hash, eq, hasher) {
352 Entry::Occupied(entry) => {
353 let index = *entry.get();
354 (index, false)
355 }
356 Entry::Vacant(entry) => {
357 let index = self.hashes.push(hash);
358 entry.insert(index);
359 let _index = self.values.push(value);
360 debug_assert_eq!(index, _index);
361 let _index = self.types.push(ty);
362 debug_assert_eq!(index, _index);
363 (index, true)
364 }
365 }
366 }
367
368 #[inline]
370 fn value(&self, index: VnIndex) -> Value<'a, 'tcx> {
371 self.values[index]
372 }
373
374 #[inline]
376 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
377 self.types[index]
378 }
379}
380
381struct VnState<'body, 'a, 'tcx> {
382 tcx: TyCtxt<'tcx>,
383 ecx: InterpCx<'tcx, DummyMachine>,
384 local_decls: &'body LocalDecls<'tcx>,
385 is_coroutine: bool,
386 locals: IndexVec<Local, Option<VnIndex>>,
388 rev_locals: IndexVec<VnIndex, SmallVec<[Local; 1]>>,
391 values: ValueSet<'a, 'tcx>,
392 evaluated: IndexVec<VnIndex, Option<Option<&'a OpTy<'tcx>>>>,
397 ssa: &'body SsaLocals,
398 dominators: Dominators<BasicBlock>,
399 reused_locals: DenseBitSet<Local>,
400 arena: &'a DroplessArena,
401}
402
403impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> {
404 fn new(
405 tcx: TyCtxt<'tcx>,
406 body: &Body<'tcx>,
407 typing_env: ty::TypingEnv<'tcx>,
408 ssa: &'body SsaLocals,
409 dominators: Dominators<BasicBlock>,
410 local_decls: &'body LocalDecls<'tcx>,
411 arena: &'a DroplessArena,
412 ) -> Self {
413 let num_values =
418 2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::<usize>()
419 + 4 * body.basic_blocks.len();
420 VnState {
421 tcx,
422 ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
423 local_decls,
424 is_coroutine: body.coroutine.is_some(),
425 locals: IndexVec::from_elem(None, local_decls),
426 rev_locals: IndexVec::with_capacity(num_values),
427 values: ValueSet::new(num_values),
428 evaluated: IndexVec::with_capacity(num_values),
429 ssa,
430 dominators,
431 reused_locals: DenseBitSet::new_empty(local_decls.len()),
432 arena,
433 }
434 }
435
436 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
437 self.ecx.typing_env()
438 }
439
440 fn insert_unique(
441 &mut self,
442 ty: Ty<'tcx>,
443 value: impl FnOnce(VnOpaque) -> Value<'a, 'tcx>,
444 ) -> VnIndex {
445 let index = self.values.insert_unique(ty, value);
446 let _index = self.evaluated.push(None);
447 debug_assert_eq!(index, _index);
448 let _index = self.rev_locals.push(SmallVec::new());
449 debug_assert_eq!(index, _index);
450 index
451 }
452
453 #[instrument(level = "trace", skip(self), ret)]
454 fn insert(&mut self, ty: Ty<'tcx>, value: Value<'a, 'tcx>) -> VnIndex {
455 let (index, new) = self.values.insert(ty, value);
456 if new {
457 let _index = self.evaluated.push(None);
459 debug_assert_eq!(index, _index);
460 let _index = self.rev_locals.push(SmallVec::new());
461 debug_assert_eq!(index, _index);
462 }
463 index
464 }
465
466 #[instrument(level = "trace", skip(self), ret)]
469 fn new_opaque(&mut self, ty: Ty<'tcx>) -> VnIndex {
470 let index = self.insert_unique(ty, Value::Opaque);
471 self.evaluated[index] = Some(None);
472 index
473 }
474
475 #[instrument(level = "trace", skip(self), ret)]
476 fn new_argument(&mut self, ty: Ty<'tcx>) -> VnIndex {
477 let index = self.insert_unique(ty, Value::Argument);
478 self.evaluated[index] = Some(None);
479 index
480 }
481
482 #[instrument(level = "trace", skip(self), ret)]
484 fn new_pointer(&mut self, place: Place<'tcx>, kind: AddressKind) -> Option<VnIndex> {
485 let pty = place.ty(self.local_decls, self.tcx).ty;
486 let ty = match kind {
487 AddressKind::Ref(bk) => {
488 Ty::new_ref(self.tcx, self.tcx.lifetimes.re_erased, pty, bk.to_mutbl_lossy())
489 }
490 AddressKind::Address(mutbl) => Ty::new_ptr(self.tcx, pty, mutbl.to_mutbl_lossy()),
491 };
492
493 let mut projection = place.projection.iter();
494 let base = if place.is_indirect_first_projection() {
495 let base = self.locals[place.local]?;
496 projection.next();
498 AddressBase::Deref(base)
499 } else if self.ssa.is_ssa(place.local) {
500 AddressBase::Local(place.local)
502 } else {
503 return None;
504 };
505 let projection =
507 projection.map(|proj| proj.try_map(|index| self.locals[index], |ty| ty).ok_or(()));
508 let projection = self.arena.try_alloc_from_iter(projection).ok()?;
509
510 let index = self.insert_unique(ty, |provenance| Value::Address {
511 base,
512 projection,
513 kind,
514 provenance,
515 });
516 Some(index)
517 }
518
519 #[instrument(level = "trace", skip(self), ret)]
520 fn insert_constant(&mut self, value: Const<'tcx>) -> VnIndex {
521 if is_deterministic(value) {
522 let constant = Value::Constant { value, disambiguator: None };
524 self.insert(value.ty(), constant)
525 } else {
526 self.insert_unique(value.ty(), |disambiguator| Value::Constant {
529 value,
530 disambiguator: Some(disambiguator),
531 })
532 }
533 }
534
535 #[inline]
536 fn get(&self, index: VnIndex) -> Value<'a, 'tcx> {
537 self.values.value(index)
538 }
539
540 #[inline]
541 fn ty(&self, index: VnIndex) -> Ty<'tcx> {
542 self.values.ty(index)
543 }
544
545 #[instrument(level = "trace", skip(self))]
547 fn assign(&mut self, local: Local, value: VnIndex) {
548 debug_assert!(self.ssa.is_ssa(local));
549 self.locals[local] = Some(value);
550 self.rev_locals[value].push(local);
551 }
552
553 fn insert_bool(&mut self, flag: bool) -> VnIndex {
554 let value = Const::from_bool(self.tcx, flag);
556 debug_assert!(is_deterministic(value));
557 self.insert(self.tcx.types.bool, Value::Constant { value, disambiguator: None })
558 }
559
560 fn insert_scalar(&mut self, ty: Ty<'tcx>, scalar: Scalar) -> VnIndex {
561 let value = Const::from_scalar(self.tcx, scalar, ty);
563 debug_assert!(is_deterministic(value));
564 self.insert(ty, Value::Constant { value, disambiguator: None })
565 }
566
567 fn insert_tuple(&mut self, ty: Ty<'tcx>, values: &[VnIndex]) -> VnIndex {
568 self.insert(ty, Value::Aggregate(VariantIdx::ZERO, self.arena.alloc_slice(values)))
569 }
570
571 #[instrument(level = "trace", skip(self), ret)]
572 fn eval_to_const_inner(&mut self, value: VnIndex) -> Option<OpTy<'tcx>> {
573 use Value::*;
574 let ty = self.ty(value);
575 let ty = if !self.is_coroutine || ty.is_scalar() {
577 self.ecx.layout_of(ty).ok()?
578 } else {
579 return None;
580 };
581 let op = match self.get(value) {
582 _ if ty.is_zst() => ImmTy::uninit(ty).into(),
583
584 Opaque(_) | Argument(_) => return None,
585 RuntimeChecks(..) => return None,
587
588 Repeat(value, _count) => {
593 let value = self.eval_to_const(value)?;
594 if value.is_immediate_uninit() {
595 ImmTy::uninit(ty).into()
596 } else {
597 return None;
598 }
599 }
600 Constant { ref value, disambiguator: _ } => {
601 self.ecx.eval_mir_constant(value, DUMMY_SP, None).discard_err()?
602 }
603 Aggregate(variant, ref fields) => {
604 let fields =
605 fields.iter().map(|&f| self.eval_to_const(f)).collect::<Option<Vec<_>>>()?;
606 let variant = if ty.ty.is_enum() { Some(variant) } else { None };
607 let (BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) = ty.backend_repr
608 else {
609 return None;
610 };
611 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
612 let variant_dest = if let Some(variant) = variant {
613 self.ecx.project_downcast(&dest, variant).discard_err()?
614 } else {
615 dest.clone()
616 };
617 for (field_index, op) in fields.into_iter().enumerate() {
618 let field_dest = self
619 .ecx
620 .project_field(&variant_dest, FieldIdx::from_usize(field_index))
621 .discard_err()?;
622 self.ecx.copy_op(op, &field_dest).discard_err()?;
623 }
624 self.ecx
625 .write_discriminant(variant.unwrap_or(FIRST_VARIANT), &dest)
626 .discard_err()?;
627 self.ecx
628 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
629 .discard_err()?;
630 dest.into()
631 }
632 Union(active_field, field) => {
633 let field = self.eval_to_const(field)?;
634 if field.layout.layout.is_zst() {
635 ImmTy::from_immediate(Immediate::Uninit, ty).into()
636 } else if matches!(
637 ty.backend_repr,
638 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
639 ) {
640 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
641 let field_dest = self.ecx.project_field(&dest, active_field).discard_err()?;
642 self.ecx.copy_op(field, &field_dest).discard_err()?;
643 self.ecx
644 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
645 .discard_err()?;
646 dest.into()
647 } else {
648 return None;
649 }
650 }
651 RawPtr { pointer, metadata } => {
652 let pointer = self.eval_to_const(pointer)?;
653 let metadata = self.eval_to_const(metadata)?;
654
655 let data = self.ecx.read_pointer(pointer).discard_err()?;
657 let meta = if metadata.layout.is_zst() {
658 MemPlaceMeta::None
659 } else {
660 MemPlaceMeta::Meta(self.ecx.read_scalar(metadata).discard_err()?)
661 };
662 let ptr_imm = Immediate::new_pointer_with_meta(data, meta, &self.ecx);
663 ImmTy::from_immediate(ptr_imm, ty).into()
664 }
665
666 Projection(base, elem) => {
667 let base = self.eval_to_const(base)?;
668 let elem = elem.try_map(|_| None, |()| ty.ty)?;
671 self.ecx.project(base, elem).discard_err()?
672 }
673 Address { base, projection, .. } => {
674 debug_assert!(!projection.contains(&ProjectionElem::Deref));
675 let pointer = match base {
676 AddressBase::Deref(pointer) => self.eval_to_const(pointer)?,
677 AddressBase::Local(_) => return None,
679 };
680 let mut mplace = self.ecx.deref_pointer(pointer).discard_err()?;
681 for elem in projection {
682 let elem = elem.try_map(|_| None, |ty| ty)?;
685 mplace = self.ecx.project(&mplace, elem).discard_err()?;
686 }
687 let pointer = mplace.to_ref(&self.ecx);
688 ImmTy::from_immediate(pointer, ty).into()
689 }
690
691 Discriminant(base) => {
692 let base = self.eval_to_const(base)?;
693 let variant = self.ecx.read_discriminant(base).discard_err()?;
694 let discr_value =
695 self.ecx.discriminant_for_variant(base.layout.ty, variant).discard_err()?;
696 discr_value.into()
697 }
698 UnaryOp(un_op, operand) => {
699 let operand = self.eval_to_const(operand)?;
700 let operand = self.ecx.read_immediate(operand).discard_err()?;
701 let val = self.ecx.unary_op(un_op, &operand).discard_err()?;
702 val.into()
703 }
704 BinaryOp(bin_op, lhs, rhs) => {
705 let lhs = self.eval_to_const(lhs)?;
706 let rhs = self.eval_to_const(rhs)?;
707 let lhs = self.ecx.read_immediate(lhs).discard_err()?;
708 let rhs = self.ecx.read_immediate(rhs).discard_err()?;
709 let val = self.ecx.binary_op(bin_op, &lhs, &rhs).discard_err()?;
710 val.into()
711 }
712 Cast { kind, value } => match kind {
713 CastKind::IntToInt | CastKind::IntToFloat => {
714 let value = self.eval_to_const(value)?;
715 let value = self.ecx.read_immediate(value).discard_err()?;
716 let res = self.ecx.int_to_int_or_float(&value, ty).discard_err()?;
717 res.into()
718 }
719 CastKind::FloatToFloat | CastKind::FloatToInt => {
720 let value = self.eval_to_const(value)?;
721 let value = self.ecx.read_immediate(value).discard_err()?;
722 let res = self.ecx.float_to_float_or_int(&value, ty).discard_err()?;
723 res.into()
724 }
725 CastKind::Transmute | CastKind::Subtype => {
726 let value = self.eval_to_const(value)?;
727 if value.is_immediate_uninit() {
728 return Some(ImmTy::uninit(ty).into());
729 }
730 if value.as_mplace_or_imm().is_right() {
735 let can_transmute = match (value.layout.backend_repr, ty.backend_repr) {
736 (BackendRepr::Scalar(s1), BackendRepr::Scalar(s2)) => {
737 s1.size(&self.ecx) == s2.size(&self.ecx)
738 && !matches!(s1.primitive(), Primitive::Pointer(..))
739 }
740 (
741 BackendRepr::ScalarPair { a: a1, b: b1, b_offset: b1_offset },
742 BackendRepr::ScalarPair { a: a2, b: b2, b_offset: b2_offset },
743 ) => {
744 a1.size(&self.ecx) == a2.size(&self.ecx)
745 && b1.size(&self.ecx) == b2.size(&self.ecx)
746 && b1_offset == b2_offset
749 && !matches!(a1.primitive(), Primitive::Pointer(..))
751 && !matches!(b1.primitive(), Primitive::Pointer(..))
752 }
753 _ => false,
754 };
755 if !can_transmute {
756 return None;
757 }
758 }
759 value.offset(Size::ZERO, ty, &self.ecx).discard_err()?
760 }
761 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => {
762 let src = self.eval_to_const(value)?;
763 let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?;
764 self.ecx.unsize_into(src, ty, &dest).discard_err()?;
765 self.ecx
766 .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id())
767 .discard_err()?;
768 dest.into()
769 }
770 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
771 let src = self.eval_to_const(value)?;
772 let src = self.ecx.read_immediate(src).discard_err()?;
773 let ret = self.ecx.ptr_to_ptr(&src, ty).discard_err()?;
774 ret.into()
775 }
776 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => {
777 let src = self.eval_to_const(value)?;
778 let src = self.ecx.read_immediate(src).discard_err()?;
779 ImmTy::from_immediate(*src, ty).into()
780 }
781 _ => return None,
782 },
783 };
784 Some(op)
785 }
786
787 fn eval_to_const(&mut self, index: VnIndex) -> Option<&'a OpTy<'tcx>> {
788 if let Some(op) = self.evaluated[index] {
789 return op;
790 }
791 let op = self.eval_to_const_inner(index);
792 self.evaluated[index] = Some(self.arena.alloc(op).as_ref());
793 self.evaluated[index].unwrap()
794 }
795
796 #[instrument(level = "trace", skip(self), ret)]
798 fn dereference_address(
799 &mut self,
800 base: AddressBase,
801 projection: &[ProjectionElem<VnIndex, Ty<'tcx>>],
802 ) -> Option<VnIndex> {
803 let (mut place_ty, mut value) = match base {
804 AddressBase::Local(local) => {
806 let local = self.locals[local]?;
807 let place_ty = PlaceTy::from_ty(self.ty(local));
808 (place_ty, local)
809 }
810 AddressBase::Deref(reborrow) => {
812 let place_ty = PlaceTy::from_ty(self.ty(reborrow));
813 self.project(place_ty, reborrow, ProjectionElem::Deref)?
814 }
815 };
816 for &proj in projection {
817 (place_ty, value) = self.project(place_ty, value, proj)?;
818 }
819 Some(value)
820 }
821
822 #[instrument(level = "trace", skip(self), ret)]
823 fn project(
824 &mut self,
825 place_ty: PlaceTy<'tcx>,
826 value: VnIndex,
827 proj: ProjectionElem<VnIndex, Ty<'tcx>>,
828 ) -> Option<(PlaceTy<'tcx>, VnIndex)> {
829 let projection_ty = place_ty.projection_ty(self.tcx, proj);
830 let proj = match proj {
831 ProjectionElem::Deref => {
832 if let Some(Mutability::Not) = place_ty.ty.ref_mutability()
833 && projection_ty.ty.is_freeze(self.tcx, self.typing_env())
834 {
835 if let Value::Address { base, projection, .. } = self.get(value)
836 && let Some(value) = self.dereference_address(base, projection)
837 {
838 return Some((projection_ty, value));
839 }
840 if self.ty_may_have_ref(projection_ty.ty) {
854 return None;
855 }
856
857 let deref = self
860 .insert(projection_ty.ty, Value::Projection(value, ProjectionElem::Deref));
861 return Some((projection_ty, deref));
862 } else {
863 return None;
864 }
865 }
866 ProjectionElem::PhantomDeref => bug!("PhantomDeref in GVN"),
867 ProjectionElem::Downcast(name, index) => ProjectionElem::Downcast(name, index),
868 ProjectionElem::Field(f, _) => match self.get(value) {
869 Value::Aggregate(_, fields) => return Some((projection_ty, fields[f.as_usize()])),
870 Value::Union(active, field) if active == f => return Some((projection_ty, field)),
871 Value::Projection(outer_value, ProjectionElem::Downcast(_, read_variant))
872 if let Value::Aggregate(written_variant, fields) = self.get(outer_value)
873 && written_variant == read_variant =>
889 {
890 return Some((projection_ty, fields[f.as_usize()]));
891 }
892 _ => ProjectionElem::Field(f, ()),
893 },
894 ProjectionElem::Index(idx) => {
895 if let Value::Repeat(inner, _) = self.get(value) {
896 return Some((projection_ty, inner));
897 }
898 ProjectionElem::Index(idx)
899 }
900 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
901 match self.get(value) {
902 Value::Repeat(inner, _) => {
903 return Some((projection_ty, inner));
904 }
905 Value::Aggregate(_, operands) => {
906 let offset = if from_end {
907 operands.len() - offset as usize
908 } else {
909 offset as usize
910 };
911 let value = operands.get(offset).copied()?;
912 return Some((projection_ty, value));
913 }
914 _ => {}
915 };
916 ProjectionElem::ConstantIndex { offset, min_length, from_end }
917 }
918 ProjectionElem::Subslice { from, to, from_end } => {
919 ProjectionElem::Subslice { from, to, from_end }
920 }
921 ProjectionElem::OpaqueCast(_) => ProjectionElem::OpaqueCast(()),
922 ProjectionElem::UnwrapUnsafeBinder(_) => ProjectionElem::UnwrapUnsafeBinder(()),
923 };
924
925 let value = self.insert(projection_ty.ty, Value::Projection(value, proj));
926 Some((projection_ty, value))
927 }
928
929 #[instrument(level = "trace", skip(self))]
931 fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) {
932 if place.is_indirect_first_projection()
935 && let Some(base) = self.locals[place.local]
936 && let Some(new_local) = self.try_as_local(base, location)
937 && place.local != new_local
938 {
939 place.local = new_local;
940 self.reused_locals.insert(new_local);
941 }
942
943 let mut projection = Cow::Borrowed(&place.projection[..]);
944
945 for i in 0..projection.len() {
946 let elem = projection[i];
947 if let ProjectionElem::Index(idx_local) = elem
948 && let Some(idx) = self.locals[idx_local]
949 {
950 if let Some(offset) = self.eval_to_const(idx)
951 && let Some(offset) = self.ecx.read_target_usize(offset).discard_err()
952 && let Some(min_length) = offset.checked_add(1)
953 {
954 projection.to_mut()[i] =
955 ProjectionElem::ConstantIndex { offset, min_length, from_end: false };
956 } else if let Some(new_idx_local) = self.try_as_local(idx, location)
957 && idx_local != new_idx_local
958 {
959 projection.to_mut()[i] = ProjectionElem::Index(new_idx_local);
960 self.reused_locals.insert(new_idx_local);
961 }
962 }
963 }
964
965 if Cow::is_owned(&projection) {
966 place.projection = self.tcx.mk_place_elems(&projection);
967 }
968
969 trace!(?place);
970 }
971
972 #[instrument(level = "trace", skip(self), ret)]
975 fn compute_place_value(
976 &mut self,
977 place: Place<'tcx>,
978 location: Location,
979 ) -> Result<VnIndex, PlaceRef<'tcx>> {
980 let mut place_ref = place.as_ref();
983
984 let Some(mut value) = self.locals[place.local] else { return Err(place_ref) };
986 let mut place_ty = PlaceTy::from_ty(self.local_decls[place.local].ty);
988 for (index, proj) in place.projection.iter().enumerate() {
989 if let Some(local) = self.try_as_local(value, location) {
990 place_ref = PlaceRef { local, projection: &place.projection[index..] };
994 }
995
996 let Some(proj) = proj.try_map(|value| self.locals[value], |ty| ty) else {
997 return Err(place_ref);
998 };
999 let Some(ty_and_value) = self.project(place_ty, value, proj) else {
1000 return Err(place_ref);
1001 };
1002 (place_ty, value) = ty_and_value;
1003 }
1004
1005 Ok(value)
1006 }
1007
1008 #[instrument(level = "trace", skip(self), ret)]
1011 fn simplify_place_value(
1012 &mut self,
1013 place: &mut Place<'tcx>,
1014 location: Location,
1015 ) -> Option<VnIndex> {
1016 self.simplify_place_projection(place, location);
1017
1018 match self.compute_place_value(*place, location) {
1019 Ok(value) => {
1020 if let Some(new_place) = self.try_as_place(value, location, true)
1021 && (new_place.local != place.local
1022 || new_place.projection.len() < place.projection.len())
1023 {
1024 *place = new_place;
1025 self.reused_locals.insert(new_place.local);
1026 }
1027 Some(value)
1028 }
1029 Err(place_ref) => {
1030 if place_ref.local != place.local
1031 || place_ref.projection.len() < place.projection.len()
1032 {
1033 *place = place_ref.project_deeper(&[], self.tcx);
1035 self.reused_locals.insert(place_ref.local);
1036 }
1037 None
1038 }
1039 }
1040 }
1041
1042 #[instrument(level = "trace", skip(self), ret)]
1043 fn simplify_operand(
1044 &mut self,
1045 operand: &mut Operand<'tcx>,
1046 location: Location,
1047 ) -> Option<VnIndex> {
1048 let value = match *operand {
1049 Operand::RuntimeChecks(c) => self.insert(self.tcx.types.bool, Value::RuntimeChecks(c)),
1050 Operand::Constant(ref constant) => self.insert_constant(constant.const_),
1051 Operand::Copy(ref mut place) | Operand::Move(ref mut place) => {
1052 self.simplify_place_value(place, location)?
1053 }
1054 };
1055 if let Some(const_) = self.try_as_constant(value) {
1056 *operand = Operand::Constant(Box::new(const_));
1057 } else if let Value::RuntimeChecks(c) = self.get(value) {
1058 *operand = Operand::RuntimeChecks(c);
1059 }
1060 Some(value)
1061 }
1062
1063 #[instrument(level = "trace", skip(self), ret)]
1064 fn simplify_rvalue(
1065 &mut self,
1066 rvalue: &mut Rvalue<'tcx>,
1067 location: Location,
1068 ) -> Option<VnIndex> {
1069 let value = match *rvalue {
1070 Rvalue::Use(ref mut operand, _) => return self.simplify_operand(operand, location),
1072
1073 Rvalue::Repeat(ref mut op, amount) => {
1075 let op = self.simplify_operand(op, location)?;
1076 Value::Repeat(op, amount)
1077 }
1078 Rvalue::Aggregate(..) => return self.simplify_aggregate(rvalue, location),
1079 Rvalue::Ref(_, borrow_kind, ref mut place) => {
1080 self.simplify_place_projection(place, location);
1081 return self.new_pointer(*place, AddressKind::Ref(borrow_kind));
1082 }
1083 Rvalue::Reborrow(_, mutbl, place) => {
1084 if mutbl == Mutability::Mut {
1085 let mut operand = Operand::Copy(place);
1087 let val = self.simplify_operand(&mut operand, location);
1088 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1090 return val;
1091 } else {
1092 return None;
1096 }
1097 }
1098 Rvalue::RawPtr(mutbl, ref mut place) => {
1099 self.simplify_place_projection(place, location);
1100 return self.new_pointer(*place, AddressKind::Address(mutbl));
1101 }
1102 Rvalue::WrapUnsafeBinder(ref mut op, _) => {
1103 let value = self.simplify_operand(op, location)?;
1104 Value::Cast { kind: CastKind::Transmute, value }
1105 }
1106
1107 Rvalue::Cast(ref mut kind, ref mut value, to) => {
1109 return self.simplify_cast(kind, value, to, location);
1110 }
1111 Rvalue::BinaryOp(op, (ref mut lhs, ref mut rhs)) => {
1112 return self.simplify_binary(op, lhs, rhs, location);
1113 }
1114 Rvalue::UnaryOp(op, ref mut arg_op) => {
1115 return self.simplify_unary(op, arg_op, location);
1116 }
1117 Rvalue::Discriminant(ref mut place) => {
1118 let place = self.simplify_place_value(place, location)?;
1119 if let Some(discr) = self.simplify_discriminant(place) {
1120 return Some(discr);
1121 }
1122 Value::Discriminant(place)
1123 }
1124
1125 Rvalue::ThreadLocalRef(..) => return None,
1127 Rvalue::CopyForDeref(_) => {
1128 bug!("forbidden in runtime MIR: {rvalue:?}")
1129 }
1130 };
1131 let ty = rvalue.ty(self.local_decls, self.tcx);
1132 Some(self.insert(ty, value))
1133 }
1134
1135 fn simplify_discriminant(&mut self, place: VnIndex) -> Option<VnIndex> {
1136 let enum_ty = self.ty(place);
1137 if enum_ty.is_enum()
1138 && let Value::Aggregate(variant, _) = self.get(place)
1139 {
1140 let discr = self.ecx.discriminant_for_variant(enum_ty, variant).discard_err()?;
1141 return Some(self.insert_scalar(discr.layout.ty, discr.to_scalar()));
1142 }
1143
1144 None
1145 }
1146
1147 fn try_as_place_elem(
1148 &mut self,
1149 ty: Ty<'tcx>,
1150 proj: ProjectionElem<VnIndex, ()>,
1151 loc: Location,
1152 ) -> Option<PlaceElem<'tcx>> {
1153 proj.try_map(
1154 |value| {
1155 let local = self.try_as_local(value, loc)?;
1156 self.reused_locals.insert(local);
1157 Some(local)
1158 },
1159 |()| ty,
1160 )
1161 }
1162
1163 fn simplify_aggregate_to_copy(
1164 &mut self,
1165 ty: Ty<'tcx>,
1166 variant_index: VariantIdx,
1167 fields: &[VnIndex],
1168 ) -> Option<VnIndex> {
1169 let Some(&first_field) = fields.first() else { return None };
1170 let Value::Projection(copy_from_value, _) = self.get(first_field) else { return None };
1171
1172 if fields.iter().enumerate().any(|(index, &v)| {
1174 if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = self.get(v)
1175 && copy_from_value == pointer
1176 && from_index.index() == index
1177 {
1178 return false;
1179 }
1180 true
1181 }) {
1182 return None;
1183 }
1184
1185 let mut copy_from_local_value = copy_from_value;
1186 if let Value::Projection(pointer, proj) = self.get(copy_from_value)
1187 && let ProjectionElem::Downcast(_, read_variant) = proj
1188 {
1189 if variant_index == read_variant {
1190 copy_from_local_value = pointer;
1192 } else {
1193 return None;
1195 }
1196 }
1197
1198 if self.ty(copy_from_local_value) == ty { Some(copy_from_local_value) } else { None }
1200 }
1201
1202 fn simplify_aggregate(
1203 &mut self,
1204 rvalue: &mut Rvalue<'tcx>,
1205 location: Location,
1206 ) -> Option<VnIndex> {
1207 let tcx = self.tcx;
1208 let ty = rvalue.ty(self.local_decls, tcx);
1209
1210 let Rvalue::Aggregate(ref kind, ref mut field_ops) = *rvalue else { bug!() };
1211
1212 if field_ops.is_empty() {
1213 let is_zst = match *kind {
1214 AggregateKind::Array(..)
1215 | AggregateKind::Tuple
1216 | AggregateKind::Closure(..)
1217 | AggregateKind::CoroutineClosure(..) => true,
1218 AggregateKind::Adt(did, ..) => tcx.def_kind(did) != DefKind::Enum,
1220 AggregateKind::Coroutine(..) => false,
1222 AggregateKind::RawPtr(..) => bug!("MIR for RawPtr aggregate must have 2 fields"),
1223 };
1224
1225 if is_zst {
1226 return Some(self.insert_constant(Const::zero_sized(ty)));
1227 }
1228 }
1229
1230 let fields = self.arena.alloc_from_iter(field_ops.iter_mut().map(|op| {
1231 self.simplify_operand(op, location)
1232 .unwrap_or_else(|| self.new_opaque(op.ty(self.local_decls, self.tcx)))
1233 }));
1234
1235 let variant_index = match *kind {
1236 AggregateKind::Array(..) | AggregateKind::Tuple => {
1237 assert!(!field_ops.is_empty());
1238 FIRST_VARIANT
1239 }
1240 AggregateKind::Closure(..)
1241 | AggregateKind::CoroutineClosure(..)
1242 | AggregateKind::Coroutine(..) => FIRST_VARIANT,
1243 AggregateKind::Adt(_, variant_index, _, _, None) => variant_index,
1244 AggregateKind::Adt(_, _, _, _, Some(active_field)) => {
1246 let field = *fields.first()?;
1247 return Some(self.insert(ty, Value::Union(active_field, field)));
1248 }
1249 AggregateKind::RawPtr(..) => {
1250 assert_eq!(field_ops.len(), 2);
1251 let [mut pointer, metadata] = fields.try_into().unwrap();
1252
1253 let mut was_updated = false;
1255 while let Value::Cast { kind: CastKind::PtrToPtr, value: cast_value } =
1256 self.get(pointer)
1257 && let ty::RawPtr(from_pointee_ty, from_mtbl) = self.ty(cast_value).kind()
1258 && let ty::RawPtr(_, output_mtbl) = ty.kind()
1259 && from_mtbl == output_mtbl
1260 && from_pointee_ty.is_sized(self.tcx, self.typing_env())
1261 {
1262 pointer = cast_value;
1263 was_updated = true;
1264 }
1265
1266 if was_updated && let Some(op) = self.try_as_operand(pointer, location) {
1267 field_ops[FieldIdx::ZERO] = op;
1268 }
1269
1270 return Some(self.insert(ty, Value::RawPtr { pointer, metadata }));
1271 }
1272 };
1273
1274 if ty.is_array()
1275 && fields.len() > 4
1276 && let Ok(&first) = fields.iter().all_equal_value()
1277 {
1278 let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
1279 if let Some(op) = self.try_as_operand(first, location) {
1280 *rvalue = Rvalue::Repeat(op, len);
1281 }
1282 return Some(self.insert(ty, Value::Repeat(first, len)));
1283 }
1284
1285 if let Some(value) = self.simplify_aggregate_to_copy(ty, variant_index, &fields) {
1286 if let Some(place) = self.try_as_place(value, location, true) {
1287 self.reused_locals.insert(place.local);
1288 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
1290 }
1291 return Some(value);
1292 }
1293
1294 Some(self.insert(ty, Value::Aggregate(variant_index, fields)))
1295 }
1296
1297 #[instrument(level = "trace", skip(self), ret)]
1298 fn simplify_unary(
1299 &mut self,
1300 op: UnOp,
1301 arg_op: &mut Operand<'tcx>,
1302 location: Location,
1303 ) -> Option<VnIndex> {
1304 let mut arg_index = self.simplify_operand(arg_op, location)?;
1305 let arg_ty = self.ty(arg_index);
1306 let ret_ty = op.ty(self.tcx, arg_ty);
1307
1308 if op == UnOp::PtrMetadata {
1311 let mut was_updated = false;
1312 loop {
1313 arg_index = match self.get(arg_index) {
1314 Value::Cast { kind: CastKind::PtrToPtr, value: inner }
1323 if self.pointers_have_same_metadata(self.ty(inner), arg_ty) =>
1324 {
1325 inner
1326 }
1327
1328 Value::Cast {
1330 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1331 value: from,
1332 } if let Some(from) = self.ty(from).builtin_deref(true)
1333 && let ty::Array(_, len) = from.kind()
1334 && let Some(to) = self.ty(arg_index).builtin_deref(true)
1335 && let ty::Slice(..) = to.kind() =>
1336 {
1337 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1338 }
1339
1340 Value::Address { base: AddressBase::Deref(reborrowed), projection, .. }
1342 if projection.is_empty() =>
1343 {
1344 reborrowed
1345 }
1346
1347 _ => break,
1348 };
1349 was_updated = true;
1350 }
1351
1352 if was_updated && let Some(op) = self.try_as_operand(arg_index, location) {
1353 *arg_op = op;
1354 }
1355 }
1356
1357 let value = match (op, self.get(arg_index)) {
1358 (UnOp::Not, Value::UnaryOp(UnOp::Not, inner)) => return Some(inner),
1359 (UnOp::Neg, Value::UnaryOp(UnOp::Neg, inner)) => return Some(inner),
1360 (UnOp::Not, Value::BinaryOp(BinOp::Eq, lhs, rhs)) => {
1361 Value::BinaryOp(BinOp::Ne, lhs, rhs)
1362 }
1363 (UnOp::Not, Value::BinaryOp(BinOp::Ne, lhs, rhs)) => {
1364 Value::BinaryOp(BinOp::Eq, lhs, rhs)
1365 }
1366 (UnOp::PtrMetadata, Value::RawPtr { metadata, .. }) => return Some(metadata),
1367 (
1369 UnOp::PtrMetadata,
1370 Value::Cast {
1371 kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
1372 value: inner,
1373 },
1374 ) if let ty::Slice(..) = arg_ty.builtin_deref(true).unwrap().kind()
1375 && let ty::Array(_, len) = self.ty(inner).builtin_deref(true).unwrap().kind() =>
1376 {
1377 return Some(self.insert_constant(Const::Ty(self.tcx.types.usize, *len)));
1378 }
1379 _ => Value::UnaryOp(op, arg_index),
1380 };
1381 Some(self.insert(ret_ty, value))
1382 }
1383
1384 #[instrument(level = "trace", skip(self), ret)]
1385 fn simplify_binary(
1386 &mut self,
1387 op: BinOp,
1388 lhs_operand: &mut Operand<'tcx>,
1389 rhs_operand: &mut Operand<'tcx>,
1390 location: Location,
1391 ) -> Option<VnIndex> {
1392 let lhs = self.simplify_operand(lhs_operand, location);
1393 let rhs = self.simplify_operand(rhs_operand, location);
1394
1395 let mut lhs = lhs?;
1398 let mut rhs = rhs?;
1399
1400 let lhs_ty = self.ty(lhs);
1401
1402 if let BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge = op
1405 && lhs_ty.is_any_ptr()
1406 && let Value::Cast { kind: CastKind::PtrToPtr, value: lhs_value } = self.get(lhs)
1407 && let Value::Cast { kind: CastKind::PtrToPtr, value: rhs_value } = self.get(rhs)
1408 && let lhs_from = self.ty(lhs_value)
1409 && lhs_from == self.ty(rhs_value)
1410 && self.pointers_have_same_metadata(lhs_from, lhs_ty)
1411 {
1412 lhs = lhs_value;
1413 rhs = rhs_value;
1414 if let Some(lhs_op) = self.try_as_operand(lhs, location)
1415 && let Some(rhs_op) = self.try_as_operand(rhs, location)
1416 {
1417 *lhs_operand = lhs_op;
1418 *rhs_operand = rhs_op;
1419 }
1420 }
1421
1422 if let Some(value) = self.simplify_binary_inner(op, lhs_ty, lhs, rhs) {
1423 return Some(value);
1424 }
1425 let ty = op.ty(self.tcx, lhs_ty, self.ty(rhs));
1426 let value = Value::BinaryOp(op, lhs, rhs);
1427 Some(self.insert(ty, value))
1428 }
1429
1430 fn simplify_binary_inner(
1431 &mut self,
1432 op: BinOp,
1433 lhs_ty: Ty<'tcx>,
1434 lhs: VnIndex,
1435 rhs: VnIndex,
1436 ) -> Option<VnIndex> {
1437 let reasonable_ty =
1439 lhs_ty.is_integral() || lhs_ty.is_bool() || lhs_ty.is_char() || lhs_ty.is_any_ptr();
1440 if !reasonable_ty {
1441 return None;
1442 }
1443
1444 let layout = self.ecx.layout_of(lhs_ty).ok()?;
1445
1446 let mut as_bits = |value: VnIndex| {
1447 let constant = self.eval_to_const(value)?;
1448 if layout.backend_repr.is_scalar() {
1449 let scalar = self.ecx.read_scalar(constant).discard_err()?;
1450 scalar.to_bits(constant.layout.size).discard_err()
1451 } else {
1452 None
1454 }
1455 };
1456
1457 use Either::{Left, Right};
1459 let a = as_bits(lhs).map_or(Right(lhs), Left);
1460 let b = as_bits(rhs).map_or(Right(rhs), Left);
1461
1462 let result = match (op, a, b) {
1463 (
1465 BinOp::Add
1466 | BinOp::AddWithOverflow
1467 | BinOp::AddUnchecked
1468 | BinOp::BitOr
1469 | BinOp::BitXor,
1470 Left(0),
1471 Right(p),
1472 )
1473 | (
1474 BinOp::Add
1475 | BinOp::AddWithOverflow
1476 | BinOp::AddUnchecked
1477 | BinOp::BitOr
1478 | BinOp::BitXor
1479 | BinOp::Sub
1480 | BinOp::SubWithOverflow
1481 | BinOp::SubUnchecked
1482 | BinOp::Offset
1483 | BinOp::Shl
1484 | BinOp::Shr,
1485 Right(p),
1486 Left(0),
1487 )
1488 | (BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked, Left(1), Right(p))
1489 | (
1490 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::Div,
1491 Right(p),
1492 Left(1),
1493 ) => p,
1494 (BinOp::BitAnd, Right(p), Left(ones)) | (BinOp::BitAnd, Left(ones), Right(p))
1496 if ones == layout.size.truncate(u128::MAX)
1497 || (layout.ty.is_bool() && ones == 1) =>
1498 {
1499 p
1500 }
1501 (
1503 BinOp::Mul | BinOp::MulWithOverflow | BinOp::MulUnchecked | BinOp::BitAnd,
1504 _,
1505 Left(0),
1506 )
1507 | (BinOp::Rem, _, Left(1))
1508 | (
1509 BinOp::Mul
1510 | BinOp::MulWithOverflow
1511 | BinOp::MulUnchecked
1512 | BinOp::Div
1513 | BinOp::Rem
1514 | BinOp::BitAnd
1515 | BinOp::Shl
1516 | BinOp::Shr,
1517 Left(0),
1518 _,
1519 ) => self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size)),
1520 (BinOp::BitOr, _, Left(ones)) | (BinOp::BitOr, Left(ones), _)
1522 if ones == layout.size.truncate(u128::MAX)
1523 || (layout.ty.is_bool() && ones == 1) =>
1524 {
1525 self.insert_scalar(lhs_ty, Scalar::from_uint(ones, layout.size))
1526 }
1527 (BinOp::Sub | BinOp::SubWithOverflow | BinOp::SubUnchecked | BinOp::BitXor, a, b)
1529 if a == b =>
1530 {
1531 self.insert_scalar(lhs_ty, Scalar::from_uint(0u128, layout.size))
1532 }
1533 (BinOp::Eq, Left(a), Left(b)) => self.insert_bool(a == b),
1538 (BinOp::Eq, a, b) if a == b => self.insert_bool(true),
1539 (BinOp::Ne, Left(a), Left(b)) => self.insert_bool(a != b),
1540 (BinOp::Ne, a, b) if a == b => self.insert_bool(false),
1541 _ => return None,
1542 };
1543
1544 if op.is_overflowing() {
1545 let ty = Ty::new_tup(self.tcx, &[self.ty(result), self.tcx.types.bool]);
1546 let false_val = self.insert_bool(false);
1547 Some(self.insert_tuple(ty, &[result, false_val]))
1548 } else {
1549 Some(result)
1550 }
1551 }
1552
1553 fn simplify_cast(
1554 &mut self,
1555 initial_kind: &mut CastKind,
1556 initial_operand: &mut Operand<'tcx>,
1557 to: Ty<'tcx>,
1558 location: Location,
1559 ) -> Option<VnIndex> {
1560 use CastKind::*;
1561 use rustc_middle::ty::adjustment::PointerCoercion::*;
1562
1563 let mut kind = *initial_kind;
1564 let mut value = self.simplify_operand(initial_operand, location)?;
1565 let mut from = self.ty(value);
1566 if from == to {
1567 return Some(value);
1568 }
1569
1570 if let CastKind::PointerCoercion(ReifyFnPointer(_) | ClosureFnPointer(_), _) = kind {
1571 return Some(self.new_opaque(to));
1574 }
1575
1576 let mut was_ever_updated = false;
1577 loop {
1578 let mut was_updated_this_iteration = false;
1579
1580 if let Transmute = kind
1585 && from.is_raw_ptr()
1586 && to.is_raw_ptr()
1587 && self.pointers_have_same_metadata(from, to)
1588 {
1589 kind = PtrToPtr;
1590 was_updated_this_iteration = true;
1591 }
1592
1593 if let PtrToPtr = kind
1596 && let Value::RawPtr { pointer, .. } = self.get(value)
1597 && let ty::RawPtr(to_pointee, _) = to.kind()
1598 && to_pointee.is_sized(self.tcx, self.typing_env())
1599 {
1600 from = self.ty(pointer);
1601 value = pointer;
1602 was_updated_this_iteration = true;
1603 if from == to {
1604 return Some(pointer);
1605 }
1606 }
1607
1608 if let Transmute = kind
1611 && let Value::Aggregate(variant_idx, field_values) = self.get(value)
1612 && let Some((field_idx, field_ty)) =
1613 self.value_is_all_in_one_field(from, variant_idx)
1614 {
1615 from = field_ty;
1616 value = field_values[field_idx.as_usize()];
1617 was_updated_this_iteration = true;
1618 if field_ty == to {
1619 return Some(value);
1620 }
1621 }
1622
1623 if let Value::Cast { kind: inner_kind, value: inner_value } = self.get(value) {
1625 let inner_from = self.ty(inner_value);
1626 let new_kind = match (inner_kind, kind) {
1627 (PtrToPtr, PtrToPtr) => Some(PtrToPtr),
1631 (PtrToPtr, Transmute) if self.pointers_have_same_metadata(inner_from, from) => {
1635 Some(Transmute)
1636 }
1637 (Transmute, PtrToPtr) if self.pointers_have_same_metadata(from, to) => {
1640 Some(Transmute)
1641 }
1642 (Transmute, Transmute)
1645 if !self.transmute_may_have_niche_of_interest_to_backend(
1646 inner_from, from, to,
1647 ) =>
1648 {
1649 Some(Transmute)
1650 }
1651 _ => None,
1652 };
1653 if let Some(new_kind) = new_kind {
1654 kind = new_kind;
1655 from = inner_from;
1656 value = inner_value;
1657 was_updated_this_iteration = true;
1658 if inner_from == to {
1659 return Some(inner_value);
1660 }
1661 }
1662 }
1663
1664 if was_updated_this_iteration {
1665 was_ever_updated = true;
1666 } else {
1667 break;
1668 }
1669 }
1670
1671 if was_ever_updated && let Some(op) = self.try_as_operand(value, location) {
1672 *initial_operand = op;
1673 *initial_kind = kind;
1674 }
1675
1676 Some(self.insert(to, Value::Cast { kind, value }))
1677 }
1678
1679 fn pointers_have_same_metadata(&self, left_ptr_ty: Ty<'tcx>, right_ptr_ty: Ty<'tcx>) -> bool {
1680 let left_meta_ty = left_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1681 let right_meta_ty = right_ptr_ty.pointee_metadata_ty_or_projection(self.tcx);
1682 if left_meta_ty == right_meta_ty {
1683 true
1684 } else if let Ok(left) = self
1685 .tcx
1686 .try_normalize_erasing_regions(self.typing_env(), Unnormalized::new_wip(left_meta_ty))
1687 && let Ok(right) = self.tcx.try_normalize_erasing_regions(
1688 self.typing_env(),
1689 Unnormalized::new_wip(right_meta_ty),
1690 )
1691 {
1692 left == right
1693 } else {
1694 false
1695 }
1696 }
1697
1698 fn ty_may_have_ref(&self, ty: Ty<'tcx>) -> bool {
1699 fn ty_may_have_ref_inner<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, depth: usize) -> bool {
1700 if !tcx.recursion_limit().value_within_limit(depth) {
1701 return true;
1702 }
1703 let depth = depth + 1;
1704 match ty.kind() {
1705 ty::Int(_)
1706 | ty::Uint(_)
1707 | ty::Float(_)
1708 | ty::Bool
1709 | ty::Char
1710 | ty::Str
1711 | ty::Never
1712 | ty::FnDef(..)
1713 | ty::Error(_)
1714 | ty::FnPtr(..) => false,
1715 ty::Tuple(fields) => {
1716 fields.iter().any(|field| ty_may_have_ref_inner(tcx, field, depth))
1717 }
1718 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => {
1719 ty_may_have_ref_inner(tcx, *ty, depth)
1720 }
1721 ty::Adt(adt_def, args) => {
1722 adt_def.has_param()
1723 || adt_def.has_aliases()
1724 || adt_def.all_fields().any(|field| {
1725 ty_may_have_ref_inner(
1726 tcx,
1727 field.ty(tcx, args).skip_normalization(),
1728 depth,
1729 )
1730 })
1731 }
1732 ty::Ref(..)
1733 | ty::RawPtr(_, _)
1734 | ty::Bound(..)
1735 | ty::Closure(..)
1736 | ty::CoroutineClosure(..)
1737 | ty::Dynamic(..)
1738 | ty::Foreign(_)
1739 | ty::Coroutine(..)
1740 | ty::CoroutineWitness(..)
1741 | ty::UnsafeBinder(_)
1742 | ty::Infer(_)
1743 | ty::Alias(..)
1744 | ty::Param(_)
1745 | ty::Placeholder(_) => true,
1746 }
1747 }
1748 ty_may_have_ref_inner(self.tcx, ty, 0)
1749 }
1750
1751 fn transmute_may_have_niche_of_interest_to_backend(
1758 &self,
1759 from_ty: Ty<'tcx>,
1760 middle_ty: Ty<'tcx>,
1761 to_ty: Ty<'tcx>,
1762 ) -> bool {
1763 let Ok(middle_layout) = self.ecx.layout_of(middle_ty) else {
1764 return true;
1766 };
1767
1768 if middle_layout.uninhabited {
1769 return true;
1770 }
1771
1772 match middle_layout.backend_repr {
1773 BackendRepr::Scalar(mid) => {
1774 if mid.is_always_valid(&self.ecx) {
1775 false
1778 } else if let Ok(from_layout) = self.ecx.layout_of(from_ty)
1779 && !from_layout.uninhabited
1780 && from_layout.size == middle_layout.size
1781 && let BackendRepr::Scalar(from_a) = from_layout.backend_repr
1782 && let mid_range = mid.valid_range(&self.ecx)
1783 && let from_range = from_a.valid_range(&self.ecx)
1784 && mid_range.contains_range(from_range, middle_layout.size)
1785 {
1786 false
1792 } else if let Ok(to_layout) = self.ecx.layout_of(to_ty)
1793 && !to_layout.uninhabited
1794 && to_layout.size == middle_layout.size
1795 && let BackendRepr::Scalar(to_a) = to_layout.backend_repr
1796 && let mid_range = mid.valid_range(&self.ecx)
1797 && let to_range = to_a.valid_range(&self.ecx)
1798 && mid_range.contains_range(to_range, middle_layout.size)
1799 {
1800 false
1806 } else {
1807 true
1808 }
1809 }
1810 BackendRepr::ScalarPair { a, b, b_offset: _ } => {
1811 !a.is_always_valid(&self.ecx) || !b.is_always_valid(&self.ecx)
1814 }
1815 BackendRepr::SimdVector { .. }
1816 | BackendRepr::SimdScalableVector { .. }
1817 | BackendRepr::Memory { .. } => false,
1818 }
1819 }
1820
1821 fn value_is_all_in_one_field(
1822 &self,
1823 ty: Ty<'tcx>,
1824 variant: VariantIdx,
1825 ) -> Option<(FieldIdx, Ty<'tcx>)> {
1826 if let Ok(layout) = self.ecx.layout_of(ty)
1827 && let abi::Variants::Single { index } = layout.variants
1828 && index == variant
1829 && let Some((field_idx, field_layout)) = layout.non_1zst_field(&self.ecx)
1830 && layout.size == field_layout.size
1831 {
1832 Some((field_idx, field_layout.ty))
1836 } else if let ty::Adt(adt, args) = ty.kind()
1837 && adt.is_struct()
1838 && adt.repr().transparent()
1839 && let [single_field] = adt.non_enum_variant().fields.raw.as_slice()
1840 {
1841 Some((FieldIdx::ZERO, single_field.ty(self.tcx, args).skip_norm_wip()))
1842 } else {
1843 None
1844 }
1845 }
1846}
1847
1848fn is_deterministic(c: Const<'_>) -> bool {
1857 if c.ty().is_primitive() {
1859 return true;
1860 }
1861
1862 match c {
1863 Const::Ty(..) => false,
1867 Const::Unevaluated(..) => false,
1869 Const::Val(..) => true,
1873 }
1874}
1875
1876fn may_have_provenance(tcx: TyCtxt<'_>, value: ConstValue, size: Size) -> bool {
1879 match value {
1880 ConstValue::ZeroSized | ConstValue::Scalar(Scalar::Int(_)) => return false,
1881 ConstValue::Scalar(Scalar::Ptr(..)) | ConstValue::Slice { .. } => return true,
1882 ConstValue::Indirect { alloc_id, offset } => !tcx
1883 .global_alloc(alloc_id)
1884 .unwrap_memory()
1885 .inner()
1886 .provenance()
1887 .range_empty(AllocRange::from(offset..offset + size), &tcx),
1888 }
1889}
1890
1891fn op_to_prop_const<'tcx>(
1892 ecx: &mut InterpCx<'tcx, DummyMachine>,
1893 op: &OpTy<'tcx>,
1894) -> Option<ConstValue> {
1895 if op.layout.is_unsized() {
1897 return None;
1898 }
1899
1900 if op.layout.is_zst() {
1902 return Some(ConstValue::ZeroSized);
1903 }
1904
1905 if !op.is_immediate_uninit()
1910 && !matches!(
1911 op.layout.backend_repr,
1912 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }
1913 )
1914 {
1915 return None;
1916 }
1917
1918 if let BackendRepr::Scalar(abi::Scalar::Initialized { .. }) = op.layout.backend_repr
1920 && let Some(scalar) = ecx.read_scalar(op).discard_err()
1921 {
1922 if !scalar.try_to_scalar_int().is_ok() {
1923 return None;
1927 }
1928 return Some(ConstValue::Scalar(scalar));
1929 }
1930
1931 if let Either::Left(mplace) = op.as_mplace_or_imm() {
1934 let (alloc_id, offset, _) = ecx.ptr_try_get_alloc_id(mplace.ptr(), 0).ok()?;
1935
1936 if ecx.has_provenance_in_alloc(alloc_id).discard_err()? {
1940 return None;
1941 }
1942
1943 intern_const_alloc_for_constprop(ecx, alloc_id).discard_err()?;
1944
1945 if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
1949 && alloc.inner().align >= op.layout.align.abi
1952 && offset.bytes().is_multiple_of(op.layout.align.abi.bytes())
1954 {
1955 return Some(ConstValue::Indirect { alloc_id, offset });
1956 }
1957 }
1958
1959 let alloc_id =
1961 ecx.intern_with_temp_alloc(op.layout, |ecx, dest| ecx.copy_op(op, dest)).discard_err()?;
1962 Some(ConstValue::Indirect { alloc_id, offset: Size::ZERO })
1963}
1964
1965impl<'tcx> VnState<'_, '_, 'tcx> {
1966 fn try_as_operand(&mut self, index: VnIndex, location: Location) -> Option<Operand<'tcx>> {
1969 if let Some(const_) = self.try_as_constant(index) {
1970 Some(Operand::Constant(Box::new(const_)))
1971 } else if let Value::RuntimeChecks(c) = self.get(index) {
1972 Some(Operand::RuntimeChecks(c))
1973 } else if let Some(place) = self.try_as_place(index, location, false) {
1974 self.reused_locals.insert(place.local);
1975 Some(Operand::Copy(place))
1976 } else {
1977 None
1978 }
1979 }
1980
1981 fn try_as_constant(&mut self, index: VnIndex) -> Option<ConstOperand<'tcx>> {
1983 let value = self.get(index);
1984
1985 if let Value::Constant { value, disambiguator: None } = value
1987 && let Const::Val(..) = value
1988 {
1989 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1990 }
1991
1992 if let Some(value) = self.try_as_evaluated_constant(index) {
1993 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1994 }
1995
1996 if let Value::Constant { value, disambiguator: None } = value {
1998 return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value });
1999 }
2000
2001 None
2002 }
2003
2004 fn try_as_evaluated_constant(&mut self, index: VnIndex) -> Option<Const<'tcx>> {
2005 let op = self.eval_to_const(index)?;
2006 let value = op_to_prop_const(&mut self.ecx, op)?;
2007
2008 if may_have_provenance(self.tcx, value, op.layout.size) {
2012 return None;
2013 }
2014
2015 Some(Const::Val(value, op.layout.ty))
2016 }
2017
2018 #[instrument(level = "trace", skip(self), ret)]
2022 fn try_as_place(
2023 &mut self,
2024 mut index: VnIndex,
2025 loc: Location,
2026 allow_complex_projection: bool,
2027 ) -> Option<Place<'tcx>> {
2028 let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
2029 loop {
2030 if let Some(local) = self.try_as_local(index, loc) {
2031 projection.reverse();
2032 let place =
2033 Place { local, projection: self.tcx.mk_place_elems(projection.as_slice()) };
2034 return Some(place);
2035 } else if projection.last() == Some(&PlaceElem::Deref) {
2036 return None;
2040 } else if let Value::Projection(pointer, proj) = self.get(index)
2041 && (allow_complex_projection || proj.is_stable_offset())
2042 && let Some(proj) = self.try_as_place_elem(self.ty(index), proj, loc)
2043 {
2044 if proj == PlaceElem::Deref {
2045 match self.get(pointer) {
2048 Value::Argument(_)
2049 if let Some(Mutability::Not) = self.ty(pointer).ref_mutability() => {}
2050 _ => {
2051 return None;
2052 }
2053 }
2054 }
2055 projection.push(proj);
2056 index = pointer;
2057 } else {
2058 return None;
2059 }
2060 }
2061 }
2062
2063 fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
2066 let other = self.rev_locals.get(index)?;
2067 other
2068 .iter()
2069 .find(|&&other| self.ssa.assignment_dominates(&self.dominators, other, loc))
2070 .copied()
2071 }
2072}
2073
2074impl<'tcx> MutVisitor<'tcx> for VnState<'_, '_, 'tcx> {
2075 fn tcx(&self) -> TyCtxt<'tcx> {
2076 self.tcx
2077 }
2078
2079 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
2080 self.simplify_place_projection(place, location);
2081 self.super_place(place, context, location);
2082 }
2083
2084 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
2085 self.simplify_operand(operand, location);
2086 self.super_operand(operand, location);
2087 }
2088
2089 fn visit_assign(
2090 &mut self,
2091 lhs: &mut Place<'tcx>,
2092 rvalue: &mut Rvalue<'tcx>,
2093 location: Location,
2094 ) {
2095 self.simplify_place_projection(lhs, location);
2096
2097 let value = self.simplify_rvalue(rvalue, location);
2098 if let Some(value) = value {
2099 if let Some(const_) = self.try_as_constant(value) {
2101 *rvalue = Rvalue::Use(Operand::Constant(Box::new(const_)), WithRetag::Yes);
2102 } else if let Some(place) = self.try_as_place(value, location, false)
2103 && !matches!(rvalue, Rvalue::Use(Operand::Move(p) | Operand::Copy(p), _) if p == &place)
2104 {
2105 *rvalue = Rvalue::Use(Operand::Copy(place), WithRetag::Yes);
2106 self.reused_locals.insert(place.local);
2107 }
2108 }
2109
2110 if let Some(local) = lhs.as_local()
2111 && self.ssa.is_ssa(local)
2112 && let rvalue_ty = rvalue.ty(self.local_decls, self.tcx)
2113 && self.local_decls[local].ty == rvalue_ty
2116 {
2117 let value = value.unwrap_or_else(|| self.new_opaque(rvalue_ty));
2118 self.assign(local, value);
2119 }
2120 }
2121
2122 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
2123 if let Terminator { kind: TerminatorKind::Call { destination, .. }, .. } = terminator {
2124 if let Some(local) = destination.as_local()
2125 && self.ssa.is_ssa(local)
2126 {
2127 let ty = self.local_decls[local].ty;
2128 let opaque = self.new_opaque(ty);
2129 self.assign(local, opaque);
2130 }
2131 }
2132 self.super_terminator(terminator, location);
2133 }
2134}
2135
2136struct StorageRemover<'a, 'tcx> {
2137 tcx: TyCtxt<'tcx>,
2138 reused_locals: &'a DenseBitSet<Local>,
2139 storage_to_remove: &'a DenseBitSet<Local>,
2140}
2141
2142impl<'a, 'tcx> MutVisitor<'tcx> for StorageRemover<'a, 'tcx> {
2143 fn tcx(&self) -> TyCtxt<'tcx> {
2144 self.tcx
2145 }
2146
2147 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, _: Location) {
2148 if let Operand::Move(place) = *operand
2149 && !place.is_indirect_first_projection()
2150 && self.reused_locals.contains(place.local)
2151 {
2152 *operand = Operand::Copy(place);
2153 }
2154 }
2155
2156 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
2157 match stmt.kind {
2158 StatementKind::StorageLive(l) | StatementKind::StorageDead(l)
2160 if self.storage_to_remove.contains(l) =>
2161 {
2162 stmt.make_nop(true)
2163 }
2164 _ => self.super_statement(stmt, loc),
2165 }
2166 }
2167}
2168
2169struct StorageChecker<'a, 'tcx> {
2170 reused_locals: &'a DenseBitSet<Local>,
2171 storage_to_remove: DenseBitSet<Local>,
2172 maybe_uninit: ResultsCursor<'a, 'tcx, MaybeUninitializedLocals>,
2173}
2174
2175impl<'a, 'tcx> Visitor<'tcx> for StorageChecker<'a, 'tcx> {
2176 fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
2177 match context {
2178 PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
2183 | PlaceContext::MutatingUse(MutatingUseContext::Call)
2184 | PlaceContext::MutatingUse(MutatingUseContext::Store)
2185 | PlaceContext::MutatingUse(MutatingUseContext::Yield)
2186 | PlaceContext::NonUse(_) => {
2187 return;
2188 }
2189 PlaceContext::MutatingUse(_) | PlaceContext::NonMutatingUse(_) => {}
2191 }
2192
2193 if !self.reused_locals.contains(local) || self.storage_to_remove.contains(local) {
2195 return;
2196 }
2197
2198 self.maybe_uninit.seek_before_primary_effect(location);
2199
2200 if self.maybe_uninit.get().contains(local) {
2201 debug!(
2202 ?location,
2203 ?local,
2204 "local is reused and is maybe uninit at this location, marking it for storage statement removal"
2205 );
2206 self.storage_to_remove.insert(local);
2207 }
2208 }
2209}