rustc_mir_transform/
copy_prop.rs1use 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
10pub(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 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
61struct 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 && !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 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 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}