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 of `*pattern` by `target`.
62struct Replacer<'a, 'tcx> {
63    tcx: TyCtxt<'tcx>,
64    unified: DenseBitSet<Local>,
65    copy_classes: &'a IndexSlice<Local, Local>,
66}
67
68impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> {
69    fn tcx(&self) -> TyCtxt<'tcx> {
70        self.tcx
71    }
72
73    #[tracing::instrument(level = "trace", skip(self))]
74    fn visit_local(&mut self, local: &mut Local, ctxt: PlaceContext, _: Location) {
75        *local = self.copy_classes[*local];
76    }
77
78    #[tracing::instrument(level = "trace", skip(self))]
79    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) {
80        if let Operand::Move(place) = *operand
81            // A move out of a projection of a copy is equivalent to a copy of the original
82            // projection.
83            && !place.is_indirect_first_projection()
84            && self.unified.contains(place.local)
85        {
86            *operand = Operand::Copy(place);
87        }
88        self.super_operand(operand, loc);
89    }
90
91    #[tracing::instrument(level = "trace", skip(self))]
92    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
93        // When removing storage statements, we need to remove both (#107511).
94        if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
95            && self.unified.contains(l)
96        {
97            stmt.make_nop(true);
98        }
99
100        self.super_statement(stmt, loc);
101
102        // Do not leave tautological assignments around.
103        if let StatementKind::Assign(box (lhs, ref rhs)) = stmt.kind
104            && let Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)) = *rhs
105            && lhs == rhs
106        {
107            stmt.make_nop(true);
108        }
109    }
110}