1 //! Trivial copy propagation pass.
3 //! This uses def-use analysis to remove values that have exactly one def and one use, which must
6 //! To give an example, we look for patterns that look like:
12 //! where `DEST` and `SRC` are both locals of some form. We replace that with:
18 //! The assignment `DEST = SRC` must be (a) the only mutation of `DEST` and (b) the only
19 //! (non-mutating) use of `SRC`. These restrictions are conservative and may be relaxed in the
23 Constant, Local, LocalKind, Location, Place, PlaceBase, Body, Operand, Rvalue, StatementKind
25 use rustc::mir::visit::MutVisitor;
26 use rustc::ty::TyCtxt;
27 use crate::transform::{MirPass, MirSource};
28 use crate::util::def_use::DefUseAnalysis;
30 pub struct CopyPropagation;
32 impl MirPass for CopyPropagation {
35 tcx: TyCtxt<'tcx, 'tcx>,
36 _source: MirSource<'tcx>,
37 body: &mut Body<'tcx>,
39 // We only run when the MIR optimization level is > 1.
40 // This avoids a slow pass, and messing up debug info.
41 if tcx.sess.opts.debugging_opts.mir_opt_level <= 1 {
45 let mut def_use_analysis = DefUseAnalysis::new(body);
47 def_use_analysis.analyze(body);
49 if eliminate_self_assignments(body, &def_use_analysis) {
50 def_use_analysis.analyze(body);
53 let mut changed = false;
54 for dest_local in body.local_decls.indices() {
55 debug!("Considering destination local: {:?}", dest_local);
60 // The destination must have exactly one def.
61 let dest_use_info = def_use_analysis.local_info(dest_local);
62 let dest_def_count = dest_use_info.def_count_not_including_drop();
63 if dest_def_count == 0 {
64 debug!(" Can't copy-propagate local: dest {:?} undefined",
68 if dest_def_count > 1 {
69 debug!(" Can't copy-propagate local: dest {:?} defined {} times",
71 dest_use_info.def_count());
74 if dest_use_info.use_count() == 0 {
75 debug!(" Can't copy-propagate local: dest {:?} unused",
79 // Conservatively gives up if the dest is an argument,
80 // because there may be uses of the original argument value.
81 if body.local_kind(dest_local) == LocalKind::Arg {
82 debug!(" Can't copy-propagate local: dest {:?} (argument)",
86 let dest_place_def = dest_use_info.defs_not_including_drop().next().unwrap();
87 location = dest_place_def.location;
89 let basic_block = &body[location.block];
90 let statement_index = location.statement_index;
91 let statement = match basic_block.statements.get(statement_index) {
92 Some(statement) => statement,
94 debug!(" Can't copy-propagate local: used in terminator");
99 // That use of the source must be an assignment.
100 match statement.kind {
101 StatementKind::Assign(
102 Place::Base(PlaceBase::Local(local)),
103 box Rvalue::Use(ref operand)
104 ) if local == dest_local => {
105 let maybe_action = match *operand {
106 Operand::Copy(ref src_place) |
107 Operand::Move(ref src_place) => {
108 Action::local_copy(&body, &def_use_analysis, src_place)
110 Operand::Constant(ref src_constant) => {
111 Action::constant(src_constant)
115 Some(this_action) => action = this_action,
120 debug!(" Can't copy-propagate local: source use is not an \
127 changed = action.perform(body, &def_use_analysis, dest_local, location) || changed;
128 // FIXME(pcwalton): Update the use-def chains to delete the instructions instead of
129 // regenerating the chains.
139 fn eliminate_self_assignments(
141 def_use_analysis: &DefUseAnalysis,
143 let mut changed = false;
145 for dest_local in body.local_decls.indices() {
146 let dest_use_info = def_use_analysis.local_info(dest_local);
148 for def in dest_use_info.defs_not_including_drop() {
149 let location = def.location;
150 if let Some(stmt) = body[location.block].statements.get(location.statement_index) {
152 StatementKind::Assign(
153 Place::Base(PlaceBase::Local(local)),
154 box Rvalue::Use(Operand::Copy(Place::Base(PlaceBase::Local(src_local)))),
156 StatementKind::Assign(
157 Place::Base(PlaceBase::Local(local)),
158 box Rvalue::Use(Operand::Move(Place::Base(PlaceBase::Local(src_local)))),
159 ) if local == dest_local && dest_local == src_local => {}
167 debug!("Deleting a self-assignment for {:?}", dest_local);
168 body.make_statement_nop(location);
177 PropagateLocalCopy(Local),
178 PropagateConstant(Constant<'tcx>),
181 impl<'tcx> Action<'tcx> {
182 fn local_copy(body: &Body<'tcx>, def_use_analysis: &DefUseAnalysis, src_place: &Place<'tcx>)
183 -> Option<Action<'tcx>> {
184 // The source must be a local.
185 let src_local = if let Place::Base(PlaceBase::Local(local)) = *src_place {
188 debug!(" Can't copy-propagate local: source is not a local");
192 // We're trying to copy propagate a local.
193 // There must be exactly one use of the source used in a statement (not in a terminator).
194 let src_use_info = def_use_analysis.local_info(src_local);
195 let src_use_count = src_use_info.use_count();
196 if src_use_count == 0 {
197 debug!(" Can't copy-propagate local: no uses");
200 if src_use_count != 1 {
201 debug!(" Can't copy-propagate local: {} uses", src_use_info.use_count());
205 // Verify that the source doesn't change in between. This is done conservatively for now,
206 // by ensuring that the source has exactly one mutation. The goal is to prevent things
213 // From being misoptimized into:
217 let src_def_count = src_use_info.def_count_not_including_drop();
218 // allow function arguments to be propagated
219 let is_arg = body.local_kind(src_local) == LocalKind::Arg;
220 if (is_arg && src_def_count != 0) || (!is_arg && src_def_count != 1) {
222 " Can't copy-propagate local: {} defs of src{}",
224 if is_arg { " (argument)" } else { "" },
229 Some(Action::PropagateLocalCopy(src_local))
232 fn constant(src_constant: &Constant<'tcx>) -> Option<Action<'tcx>> {
233 Some(Action::PropagateConstant((*src_constant).clone()))
237 body: &mut Body<'tcx>,
238 def_use_analysis: &DefUseAnalysis,
243 Action::PropagateLocalCopy(src_local) => {
244 // Eliminate the destination and the assignment.
246 // First, remove all markers.
248 // FIXME(pcwalton): Don't do this. Merge live ranges instead.
249 debug!(" Replacing all uses of {:?} with {:?} (local)",
252 for place_use in &def_use_analysis.local_info(dest_local).defs_and_uses {
253 if place_use.context.is_storage_marker() {
254 body.make_statement_nop(place_use.location)
257 for place_use in &def_use_analysis.local_info(src_local).defs_and_uses {
258 if place_use.context.is_storage_marker() {
259 body.make_statement_nop(place_use.location)
263 // Replace all uses of the destination local with the source local.
264 def_use_analysis.replace_all_defs_and_uses_with(dest_local, body, src_local);
266 // Finally, zap the now-useless assignment instruction.
267 debug!(" Deleting assignment");
268 body.make_statement_nop(location);
272 Action::PropagateConstant(src_constant) => {
273 // First, remove all markers.
275 // FIXME(pcwalton): Don't do this. Merge live ranges instead.
276 debug!(" Replacing all uses of {:?} with {:?} (constant)",
279 let dest_local_info = def_use_analysis.local_info(dest_local);
280 for place_use in &dest_local_info.defs_and_uses {
281 if place_use.context.is_storage_marker() {
282 body.make_statement_nop(place_use.location)
286 // Replace all uses of the destination local with the constant.
287 let mut visitor = ConstantPropagationVisitor::new(dest_local,
289 for dest_place_use in &dest_local_info.defs_and_uses {
290 visitor.visit_location(body, dest_place_use.location)
293 // Zap the assignment instruction if we eliminated all the uses. We won't have been
294 // able to do that if the destination was used in a projection, because projections
295 // must have places on their LHS.
296 let use_count = dest_local_info.use_count();
297 if visitor.uses_replaced == use_count {
298 debug!(" {} of {} use(s) replaced; deleting assignment",
299 visitor.uses_replaced,
301 body.make_statement_nop(location);
303 } else if visitor.uses_replaced == 0 {
304 debug!(" No uses replaced; not deleting assignment");
307 debug!(" {} of {} use(s) replaced; not deleting assignment",
308 visitor.uses_replaced,
317 struct ConstantPropagationVisitor<'tcx> {
319 constant: Constant<'tcx>,
320 uses_replaced: usize,
323 impl<'tcx> ConstantPropagationVisitor<'tcx> {
324 fn new(dest_local: Local, constant: Constant<'tcx>)
325 -> ConstantPropagationVisitor<'tcx> {
326 ConstantPropagationVisitor {
334 impl<'tcx> MutVisitor<'tcx> for ConstantPropagationVisitor<'tcx> {
335 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
336 self.super_operand(operand, location);
339 Operand::Copy(Place::Base(PlaceBase::Local(local))) |
340 Operand::Move(Place::Base(PlaceBase::Local(local))) if local == self.dest_local => {}
344 *operand = Operand::Constant(box self.constant.clone());
345 self.uses_replaced += 1