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 rustc_mir_dataflow::{Analysis, ResultsCursor};
7use tracing::{debug, instrument};
8
9use crate::ssa::{MaybeUninitializedLocals, SsaLocals};
10
11/// Unify locals that copy each other.
12///
13/// We consider patterns of the form
14///   _a = rvalue
15///   _b = move? _a
16///   _c = move? _a
17///   _d = move? _c
18/// where each of the locals is only assigned once.
19///
20/// We want to replace all those locals by `_a` (the "head"), either copied or moved.
21pub(super) struct CopyProp;
22
23impl<'tcx> crate::MirPass<'tcx> for CopyProp {
24    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
25        sess.mir_opt_level() >= 1
26    }
27
28    #[instrument(level = "trace", skip(self, tcx, body))]
29    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
30        debug!(def_id = ?body.source.def_id());
31
32        let typing_env = body.typing_env(tcx);
33        let ssa = SsaLocals::new(tcx, body, typing_env);
34
35        debug!(borrowed_locals = ?ssa.borrowed_locals());
36        debug!(copy_classes = ?ssa.copy_classes());
37
38        let mut any_replacement = false;
39        // Locals that participate in copy propagation either as a source or a destination.
40        let mut unified = DenseBitSet::new_empty(body.local_decls.len());
41
42        for (local, &head) in ssa.copy_classes().iter_enumerated() {
43            if local != head {
44                any_replacement = true;
45                unified.insert(head);
46                unified.insert(local);
47            }
48        }
49
50        if !any_replacement {
51            return;
52        }
53
54        // When emitting storage statements, we want to retain the head locals' storage statements,
55        // as this enables better optimizations. For each local use location, we mark the head for storage removal
56        // only if the head might be uninitialized at that point, or if the local is borrowed
57        // (since we cannot easily determine when it's used).
58        let storage_to_remove = if tcx.sess.emit_lifetime_markers() {
59            let mut storage_to_remove = DenseBitSet::new_empty(body.local_decls.len());
60
61            // If the local is borrowed, we cannot easily determine if it is used, so we have to remove the storage statements.
62            let borrowed_locals = ssa.borrowed_locals();
63
64            for (local, &head) in ssa.copy_classes().iter_enumerated() {
65                if local != head && borrowed_locals.contains(local) {
66                    storage_to_remove.insert(head);
67                }
68            }
69
70            let maybe_uninit = MaybeUninitializedLocals
71                .iterate_to_fixpoint(tcx, body, Some("mir_opt::copy_prop"))
72                .into_results_cursor(body);
73
74            let mut storage_checker = StorageChecker {
75                maybe_uninit,
76                copy_classes: ssa.copy_classes(),
77                storage_to_remove,
78            };
79
80            for (bb, data) in traversal::reachable(body) {
81                storage_checker.visit_basic_block_data(bb, data);
82            }
83
84            Some(storage_checker.storage_to_remove)
85        } else {
86            None
87        };
88
89        // If None, remove the storage statements of all the unified locals.
90        let storage_to_remove = storage_to_remove.as_ref().unwrap_or(&unified);
91        debug!(?storage_to_remove);
92
93        Replacer { tcx, copy_classes: ssa.copy_classes(), unified: &unified, storage_to_remove }
94            .visit_body_preserves_cfg(body);
95
96        crate::simplify::remove_unused_definitions(body);
97    }
98
99    fn is_required(&self) -> bool {
100        false
101    }
102}
103
104/// Utility to help performing substitution: for all key-value pairs in `copy_classes`,
105/// all occurrences of the key get replaced by the value.
106struct Replacer<'a, 'tcx> {
107    tcx: TyCtxt<'tcx>,
108    unified: &'a DenseBitSet<Local>,
109    storage_to_remove: &'a DenseBitSet<Local>,
110    copy_classes: &'a IndexSlice<Local, Local>,
111}
112
113impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> {
114    fn tcx(&self) -> TyCtxt<'tcx> {
115        self.tcx
116    }
117
118    #[tracing::instrument(level = "trace", skip(self))]
119    fn visit_local(&mut self, local: &mut Local, ctxt: PlaceContext, _: Location) {
120        let new_local = self.copy_classes[*local];
121        match ctxt {
122            // Do not modify the local in storage statements.
123            PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead) => {}
124            // We access the value.
125            _ => *local = new_local,
126        }
127    }
128
129    #[tracing::instrument(level = "trace", skip(self))]
130    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) {
131        if let Operand::Move(place) = *operand
132            // A move out of a projection of a copy is equivalent to a copy of the original
133            // projection.
134            && !place.is_indirect_first_projection()
135            && self.unified.contains(place.local)
136        {
137            *operand = Operand::Copy(place);
138        }
139        self.super_operand(operand, loc);
140    }
141
142    #[tracing::instrument(level = "trace", skip(self))]
143    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, loc: Location) {
144        // When removing storage statements, we need to remove both (#107511).
145        if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
146            && self.storage_to_remove.contains(l)
147        {
148            stmt.make_nop(true);
149        }
150
151        self.super_statement(stmt, loc);
152
153        // Do not leave tautological assignments around.
154        if let StatementKind::Assign(box (lhs, ref rhs)) = stmt.kind
155            && let Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)) = *rhs
156            && lhs == rhs
157        {
158            stmt.make_nop(true);
159        }
160    }
161}
162
163// Marks heads of copy classes that are maybe uninitialized at the location of a local
164// as needing storage statement removal.
165struct StorageChecker<'a, 'tcx> {
166    maybe_uninit: ResultsCursor<'a, 'tcx, MaybeUninitializedLocals>,
167    copy_classes: &'a IndexSlice<Local, Local>,
168    storage_to_remove: DenseBitSet<Local>,
169}
170
171impl<'a, 'tcx> Visitor<'tcx> for StorageChecker<'a, 'tcx> {
172    fn visit_local(&mut self, local: Local, context: PlaceContext, loc: Location) {
173        if !context.is_use() {
174            return;
175        }
176
177        let head = self.copy_classes[local];
178
179        // If the local is the head, or if we already marked it for deletion, we do not need to check it.
180        if head == local || self.storage_to_remove.contains(head) {
181            return;
182        }
183
184        self.maybe_uninit.seek_before_primary_effect(loc);
185
186        if self.maybe_uninit.get().contains(head) {
187            debug!(
188                ?loc,
189                ?context,
190                ?local,
191                ?head,
192                "local's head is maybe uninit at this location, marking head for storage statement removal"
193            );
194            self.storage_to_remove.insert(head);
195        }
196    }
197}