1use rustc_index::IndexSlice;
2use rustc_index::bit_set::DenseBitSet;
3use rustc_middle::mir::visit::*;
4use rustc_middle::mir::*;
5use rustc_middle::ty::TyCtxt;
6use tracing::{debug, instrument};
78use crate::ssa::SsaLocals;
910/// Unify locals that copy each other.
11///
12/// We consider patterns of the form
13/// _a = rvalue
14/// _b = move? _a
15/// _c = move? _a
16/// _d = move? _c
17/// where each of the locals is only assigned once.
18///
19/// We want to replace all those locals by `_a`, either copied or moved.
20pub(super) struct CopyProp;
2122impl<'tcx> crate::MirPass<'tcx> for CopyProp {
23fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
24sess.mir_opt_level() >= 1
25}
2627#[instrument(level = "trace", skip(self, tcx, body))]
28fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
29debug!(def_id = ?body.source.def_id());
3031let typing_env = body.typing_env(tcx);
32let ssa = SsaLocals::new(tcx, body, typing_env);
3334let fully_moved = fully_moved_locals(&ssa, body);
35debug!(?fully_moved);
3637let mut storage_to_remove = DenseBitSet::new_empty(fully_moved.domain_size());
38for (local, &head) in ssa.copy_classes().iter_enumerated() {
39if local != head {
40 storage_to_remove.insert(head);
41 }
42 }
4344let any_replacement = ssa.copy_classes().iter_enumerated().any(|(l, &h)| l != h);
4546 Replacer {
47 tcx,
48 copy_classes: ssa.copy_classes(),
49 fully_moved,
50 borrowed_locals: ssa.borrowed_locals(),
51 storage_to_remove,
52 }
53 .visit_body_preserves_cfg(body);
5455if any_replacement {
56crate::simplify::remove_unused_definitions(body);
57 }
58 }
5960fn is_required(&self) -> bool {
61false
62}
63}
6465/// `SsaLocals` computed equivalence classes between locals considering copy/move assignments.
66///
67/// This function also returns whether all the `move?` in the pattern are `move` and not copies.
68/// A local which is in the bitset can be replaced by `move _a`. Otherwise, it must be
69/// replaced by `copy _a`, as we cannot move multiple times from `_a`.
70///
71/// If an operand copies `_c`, it must happen before the assignment `_d = _c`, otherwise it is UB.
72/// This means that replacing it by a copy of `_a` if ok, since this copy happens before `_c` is
73/// moved, and therefore that `_d` is moved.
74#[instrument(level = "trace", skip(ssa, body))]
75fn fully_moved_locals(ssa: &SsaLocals, body: &Body<'_>) -> DenseBitSet<Local> {
76let mut fully_moved = DenseBitSet::new_filled(body.local_decls.len());
7778for (_, rvalue, _) in ssa.assignments(body) {
79let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place))
80 | Rvalue::CopyForDeref(place)) = rvalue
81else {
82continue;
83 };
8485let Some(rhs) = place.as_local() else { continue };
86if !ssa.is_ssa(rhs) {
87continue;
88 }
8990if let Rvalue::Use(Operand::Copy(_)) | Rvalue::CopyForDeref(_) = rvalue {
91 fully_moved.remove(rhs);
92 }
93 }
9495 ssa.meet_copy_equivalence(&mut fully_moved);
9697 fully_moved
98}
99100/// Utility to help performing substitution of `*pattern` by `target`.
101struct Replacer<'a, 'tcx> {
102 tcx: TyCtxt<'tcx>,
103 fully_moved: DenseBitSet<Local>,
104 storage_to_remove: DenseBitSet<Local>,
105 borrowed_locals: &'a DenseBitSet<Local>,
106 copy_classes: &'a IndexSlice<Local, Local>,
107}
108109impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> {
110fn tcx(&self) -> TyCtxt<'tcx> {
111self.tcx
112 }
113114fn visit_local(&mut self, local: &mut Local, ctxt: PlaceContext, _: Location) {
115let new_local = self.copy_classes[*local];
116// We must not unify two locals that are borrowed. But this is fine if one is borrowed and
117 // the other is not. We chose to check the original local, and not the target. That way, if
118 // the original local is borrowed and the target is not, we do not pessimize the whole class.
119if self.borrowed_locals.contains(*local) {
120return;
121 }
122match ctxt {
123// Do not modify the local in storage statements.
124PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead) => {}
125// The local should have been marked as non-SSA.
126PlaceContext::MutatingUse(_) => assert_eq!(*local, new_local),
127// We access the value.
128_ => *local = new_local,
129 }
130 }
131132fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, loc: Location) {
133if let Some(new_projection) = self.process_projection(place.projection, loc) {
134place.projection = self.tcx().mk_place_elems(&new_projection);
135 }
136137// Any non-mutating use context is ok.
138let ctxt = PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy);
139self.visit_local(&mut place.local, ctxt, loc)
140 }
141142fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) {
143if let Operand::Move(place) = *operand144// A move out of a projection of a copy is equivalent to a copy of the original
145 // projection.
146&& !place.is_indirect_first_projection()
147 && !self.fully_moved.contains(place.local)
148 {
149*operand = Operand::Copy(place);
150 }
151self.super_operand(operand, loc);
152 }
153154fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
155// When removing storage statements, we need to remove both (#107511).
156if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
157 && self.storage_to_remove.contains(l)
158 {
159stmt.make_nop();
160return;
161 }
162163self.super_statement(stmt, loc);
164165// Do not leave tautological assignments around.
166if let StatementKind::Assign(box (lhs, ref rhs)) = stmt.kind
167 && let Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)) | Rvalue::CopyForDeref(rhs) =
168*rhs169 && lhs == rhs
170 {
171stmt.make_nop();
172 }
173 }
174}