Skip to main content

rustc_mir_transform/
copy_prop.rs

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};
7
8use crate::ssa::SsaLocals;
9
10/// 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 `copy _a`.
20pub(super) struct CopyProp;
21
22impl<'tcx> crate::MirPass<'tcx> for CopyProp {
23    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
24        sess.mir_opt_level() >= 1
25    }
26
27    #[instrument(level = "trace", skip(self, tcx, body))]
28    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
29        debug!(def_id = ?body.source.def_id());
30
31        let typing_env = body.typing_env(tcx);
32        let ssa = SsaLocals::new(tcx, body, typing_env);
33        debug!(borrowed_locals = ?ssa.borrowed_locals());
34        debug!(copy_classes = ?ssa.copy_classes());
35
36        let mut any_replacement = false;
37        // Locals that participate in copy propagation either as a source or a destination.
38        let mut unified = DenseBitSet::new_empty(body.local_decls.len());
39        for (local, &head) in ssa.copy_classes().iter_enumerated() {
40            if local != head {
41                any_replacement = true;
42                unified.insert(head);
43                unified.insert(local);
44            }
45        }
46
47        if !any_replacement {
48            return;
49        }
50
51        Replacer { tcx, copy_classes: ssa.copy_classes(), unified }.visit_body_preserves_cfg(body);
52
53        crate::simplify::remove_unused_definitions(body);
54    }
55
56    fn is_required(&self) -> bool {
57        false
58    }
59}
60
61/// Utility to help performing substitution: for all key-value pairs in `copy_classes`,
62/// all occurrences of the key get replaced by the value.
63struct Replacer<'a, 'tcx> {
64    tcx: TyCtxt<'tcx>,
65    unified: DenseBitSet<Local>,
66    copy_classes: &'a IndexSlice<Local, Local>,
67}
68
69impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> {
70    fn tcx(&self) -> TyCtxt<'tcx> {
71        self.tcx
72    }
73
74    #[tracing::instrument(level = "trace", skip(self))]
75    fn visit_local(&mut self, local: &mut Local, ctxt: PlaceContext, _: Location) {
76        *local = self.copy_classes[*local];
77    }
78
79    #[tracing::instrument(level = "trace", skip(self))]
80    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) {
81        if let Operand::Move(place) = *operand
82            // A move out of a projection of a copy is equivalent to a copy of the original
83            // projection.
84            && !place.is_indirect_first_projection()
85            && self.unified.contains(place.local)
86        {
87            *operand = Operand::Copy(place);
88        }
89        self.super_operand(operand, loc);
90    }
91
92    #[tracing::instrument(level = "trace", skip(self))]
93    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
94        // When removing storage statements, we need to remove both (#107511).
95        if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
96            && self.unified.contains(l)
97        {
98            stmt.make_nop(true);
99        }
100
101        self.super_statement(stmt, loc);
102
103        // Do not leave tautological assignments around.
104        if let StatementKind::Assign(box (lhs, ref rhs)) = stmt.kind
105            && let Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)) = *rhs
106            && lhs == rhs
107        {
108            stmt.make_nop(true);
109        }
110    }
111}