-
Notifications
You must be signed in to change notification settings - Fork 13.6k
librustc_mir: Implement def-use chains and trivial copy propagation on MIR. #36388
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -187,6 +187,32 @@ impl<'tcx> Mir<'tcx> { | |
self.var_decls.len() + | ||
self.temp_decls.len() + 1 | ||
} | ||
|
||
pub fn format_local(&self, local: Local) -> String { | ||
let mut index = local.index(); | ||
index = match index.checked_sub(self.arg_decls.len()) { | ||
None => return format!("{:?}", Arg::new(index)), | ||
Some(index) => index, | ||
}; | ||
index = match index.checked_sub(self.var_decls.len()) { | ||
None => return format!("{:?}", Var::new(index)), | ||
Some(index) => index, | ||
}; | ||
index = match index.checked_sub(self.temp_decls.len()) { | ||
None => return format!("{:?}", Temp::new(index)), | ||
Some(index) => index, | ||
}; | ||
debug_assert!(index == 0); | ||
return "ReturnPointer".to_string() | ||
} | ||
|
||
/// Changes a statement to a nop. This is both faster than deleting instructions and avoids | ||
/// invalidating statement indices in `Location`s. | ||
pub fn make_statement_nop(&mut self, location: Location) { | ||
let block = &mut self[location.block]; | ||
debug_assert!(location.statement_index < block.statements.len()); | ||
block.statements[location.statement_index].make_nop() | ||
} | ||
} | ||
|
||
impl<'tcx> Index<BasicBlock> for Mir<'tcx> { | ||
|
@@ -686,6 +712,14 @@ pub struct Statement<'tcx> { | |
pub kind: StatementKind<'tcx>, | ||
} | ||
|
||
impl<'tcx> Statement<'tcx> { | ||
/// Changes a statement to a nop. This is both faster than deleting instructions and avoids | ||
/// invalidating statement indices in `Location`s. | ||
pub fn make_nop(&mut self) { | ||
self.kind = StatementKind::Nop | ||
} | ||
} | ||
|
||
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)] | ||
pub enum StatementKind<'tcx> { | ||
/// Write the RHS Rvalue to the LHS Lvalue. | ||
|
@@ -699,6 +733,9 @@ pub enum StatementKind<'tcx> { | |
|
||
/// End the current live range for the storage of the local. | ||
StorageDead(Lvalue<'tcx>), | ||
|
||
/// No-op. Useful for deleting instructions without affecting statement indices. | ||
Nop, | ||
} | ||
|
||
impl<'tcx> Debug for Statement<'tcx> { | ||
|
@@ -711,6 +748,7 @@ impl<'tcx> Debug for Statement<'tcx> { | |
SetDiscriminant{lvalue: ref lv, variant_index: index} => { | ||
write!(fmt, "discriminant({:?}) = {:?}", lv, index) | ||
} | ||
Nop => write!(fmt, "nop"), | ||
} | ||
} | ||
} | ||
|
@@ -824,6 +862,24 @@ impl<'tcx> Lvalue<'tcx> { | |
elem: elem, | ||
})) | ||
} | ||
|
||
pub fn from_local(mir: &Mir<'tcx>, local: Local) -> Lvalue<'tcx> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Several people wanted this already, I'm surprised it wasn't already in. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I still thing we should combine args/vars/temps into one array (locals), but I haven't gotten around to playing with that.... |
||
let mut index = local.index(); | ||
index = match index.checked_sub(mir.arg_decls.len()) { | ||
None => return Lvalue::Arg(Arg(index as u32)), | ||
Some(index) => index, | ||
}; | ||
index = match index.checked_sub(mir.var_decls.len()) { | ||
None => return Lvalue::Var(Var(index as u32)), | ||
Some(index) => index, | ||
}; | ||
index = match index.checked_sub(mir.temp_decls.len()) { | ||
None => return Lvalue::Temp(Temp(index as u32)), | ||
Some(index) => index, | ||
}; | ||
debug_assert!(index == 0); | ||
Lvalue::ReturnPointer | ||
} | ||
} | ||
|
||
impl<'tcx> Debug for Lvalue<'tcx> { | ||
|
@@ -1258,3 +1314,13 @@ impl fmt::Debug for Location { | |
write!(fmt, "{:?}[{}]", self.block, self.statement_index) | ||
} | ||
} | ||
|
||
impl Location { | ||
pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool { | ||
if self.block == other.block { | ||
self.statement_index <= other.statement_index | ||
} else { | ||
dominators.is_dominated_by(other.block, self.block) | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -150,7 +150,7 @@ macro_rules! make_mir_visitor { | |
|
||
fn visit_lvalue(&mut self, | ||
lvalue: & $($mutability)* Lvalue<'tcx>, | ||
context: LvalueContext, | ||
context: LvalueContext<'tcx>, | ||
location: Location) { | ||
self.super_lvalue(lvalue, context, location); | ||
} | ||
|
@@ -346,6 +346,7 @@ macro_rules! make_mir_visitor { | |
StatementKind::StorageDead(ref $($mutability)* lvalue) => { | ||
self.visit_lvalue(lvalue, LvalueContext::StorageDead, location); | ||
} | ||
StatementKind::Nop => {} | ||
} | ||
} | ||
|
||
|
@@ -580,7 +581,7 @@ macro_rules! make_mir_visitor { | |
|
||
fn super_lvalue(&mut self, | ||
lvalue: & $($mutability)* Lvalue<'tcx>, | ||
context: LvalueContext, | ||
context: LvalueContext<'tcx>, | ||
location: Location) { | ||
match *lvalue { | ||
Lvalue::Var(_) | | ||
|
@@ -605,7 +606,12 @@ macro_rules! make_mir_visitor { | |
ref $($mutability)* base, | ||
ref $($mutability)* elem, | ||
} = *proj; | ||
self.visit_lvalue(base, LvalueContext::Projection, location); | ||
let context = if context.is_mutating_use() { | ||
LvalueContext::Projection(Mutability::Mut) | ||
} else { | ||
LvalueContext::Projection(Mutability::Not) | ||
}; | ||
self.visit_lvalue(base, context, location); | ||
self.visit_projection_elem(elem, context, location); | ||
} | ||
|
||
|
@@ -750,6 +756,21 @@ macro_rules! make_mir_visitor { | |
|
||
fn super_const_usize(&mut self, _substs: & $($mutability)* ConstUsize) { | ||
} | ||
|
||
// Convenience methods | ||
|
||
fn visit_location(&mut self, mir: & $($mutability)* Mir<'tcx>, location: Location) { | ||
let basic_block = & $($mutability)* mir[location.block]; | ||
if basic_block.statements.len() == location.statement_index { | ||
if let Some(ref $($mutability)* terminator) = basic_block.terminator { | ||
self.visit_terminator(location.block, terminator, location) | ||
} | ||
} else { | ||
let statement = & $($mutability)* | ||
basic_block.statements[location.statement_index]; | ||
self.visit_statement(location.block, statement, location) | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
@@ -774,8 +795,20 @@ pub enum LvalueContext<'tcx> { | |
// Being borrowed | ||
Borrow { region: &'tcx Region, kind: BorrowKind }, | ||
|
||
// Used as base for another lvalue, e.g. `x` in `x.y` | ||
Projection, | ||
// Used as base for another lvalue, e.g. `x` in `x.y`. | ||
// | ||
// The `Mutability` argument specifies whether the projection is being performed in order to | ||
// (potentially) mutate the lvalue. For example, the projection `x.y` is marked as a mutation | ||
// in these cases: | ||
// | ||
// x.y = ...; | ||
// f(&mut x.y); | ||
// | ||
// But not in these cases: | ||
// | ||
// z = x.y; | ||
// f(&x.y); | ||
Projection(Mutability), | ||
|
||
// Consumed as part of an operand | ||
Consume, | ||
|
@@ -784,3 +817,69 @@ pub enum LvalueContext<'tcx> { | |
StorageLive, | ||
StorageDead, | ||
} | ||
|
||
impl<'tcx> LvalueContext<'tcx> { | ||
/// Returns true if this lvalue context represents a drop. | ||
pub fn is_drop(&self) -> bool { | ||
match *self { | ||
LvalueContext::Drop => true, | ||
_ => false, | ||
} | ||
} | ||
|
||
/// Returns true if this lvalue context represents a storage live or storage dead marker. | ||
pub fn is_storage_marker(&self) -> bool { | ||
match *self { | ||
LvalueContext::StorageLive | LvalueContext::StorageDead => true, | ||
_ => false, | ||
} | ||
} | ||
|
||
/// Returns true if this lvalue context represents a storage live marker. | ||
pub fn is_storage_live_marker(&self) -> bool { | ||
match *self { | ||
LvalueContext::StorageLive => true, | ||
_ => false, | ||
} | ||
} | ||
|
||
/// Returns true if this lvalue context represents a storage dead marker. | ||
pub fn is_storage_dead_marker(&self) -> bool { | ||
match *self { | ||
LvalueContext::StorageDead => true, | ||
_ => false, | ||
} | ||
} | ||
|
||
/// Returns true if this lvalue context represents a use that potentially changes the value. | ||
pub fn is_mutating_use(&self) -> bool { | ||
match *self { | ||
LvalueContext::Store | LvalueContext::Call | | ||
LvalueContext::Borrow { kind: BorrowKind::Mut, .. } | | ||
LvalueContext::Projection(Mutability::Mut) | | ||
LvalueContext::Drop => true, | ||
LvalueContext::Inspect | | ||
LvalueContext::Borrow { kind: BorrowKind::Shared, .. } | | ||
LvalueContext::Borrow { kind: BorrowKind::Unique, .. } | | ||
LvalueContext::Projection(Mutability::Not) | LvalueContext::Consume | | ||
LvalueContext::StorageLive | LvalueContext::StorageDead => false, | ||
} | ||
} | ||
|
||
/// Returns true if this lvalue context represents a use that does not change the value. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Aren't you directly interested in |
||
pub fn is_nonmutating_use(&self) -> bool { | ||
match *self { | ||
LvalueContext::Inspect | LvalueContext::Borrow { kind: BorrowKind::Shared, .. } | | ||
LvalueContext::Borrow { kind: BorrowKind::Unique, .. } | | ||
LvalueContext::Projection(Mutability::Not) | LvalueContext::Consume => true, | ||
LvalueContext::Borrow { kind: BorrowKind::Mut, .. } | LvalueContext::Store | | ||
LvalueContext::Call | LvalueContext::Projection(Mutability::Mut) | | ||
LvalueContext::Drop | LvalueContext::StorageLive | LvalueContext::StorageDead => false, | ||
} | ||
} | ||
|
||
pub fn is_use(&self) -> bool { | ||
self.is_mutating_use() || self.is_nonmutating_use() | ||
} | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -389,7 +389,8 @@ fn drop_flag_effects_for_location<'a, 'tcx, F>( | |
|moi| callback(moi, DropFlagState::Present)) | ||
} | ||
repr::StatementKind::StorageLive(_) | | ||
repr::StatementKind::StorageDead(_) => {} | ||
repr::StatementKind::StorageDead(_) | | ||
repr::StatementKind::Nop => {} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you split the addition of |
||
}, | ||
None => { | ||
debug!("drop_flag_effects: replace {:?}", block.terminator()); | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,197 @@ | ||
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this is more of a "mention analysis" than a proper def-use chain, which is more of a concept with SSA. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hmm. So I've never heard of 'mention analysis' and I don't think that def-use chains are linked to SSA (e.g., this paper suggests that they appear in the original dragon book from 1986 -- though I am not at home so I can't check myself). That said, I did find that this code seemed to overload There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've never seen the term "mention analysis" before. Google for "mention analysis data flow" brings up nothing. Where have you heard of this? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's a flow-insensitive analysis that creates a map between each local and its mentions (not an official term - this looks like too much of a triviality for papers). A def-use analysis on non-SSA is typically the flow-sensitive RDA/reaching-definition-analysis. |
||
// file at the top-level directory of this distribution and at | ||
// http://rust-lang.org/COPYRIGHT. | ||
// | ||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | ||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | ||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | ||
// option. This file may not be copied, modified, or distributed | ||
// except according to those terms. | ||
|
||
//! Def-use analysis. | ||
use rustc::mir::repr::{Local, Location, Lvalue, Mir}; | ||
use rustc::mir::visit::{LvalueContext, MutVisitor, Visitor}; | ||
use rustc_data_structures::indexed_vec::{Idx, IndexVec}; | ||
use std::marker::PhantomData; | ||
use std::mem; | ||
|
||
pub struct DefUseAnalysis<'tcx> { | ||
info: IndexVec<Local, Info<'tcx>>, | ||
mir_summary: MirSummary, | ||
} | ||
|
||
#[derive(Clone)] | ||
pub struct Info<'tcx> { | ||
pub defs_and_uses: Vec<Use<'tcx>>, | ||
} | ||
|
||
#[derive(Clone)] | ||
pub struct Use<'tcx> { | ||
pub context: LvalueContext<'tcx>, | ||
pub location: Location, | ||
} | ||
|
||
impl<'tcx> DefUseAnalysis<'tcx> { | ||
pub fn new(mir: &Mir<'tcx>) -> DefUseAnalysis<'tcx> { | ||
DefUseAnalysis { | ||
info: IndexVec::from_elem_n(Info::new(), mir.count_locals()), | ||
mir_summary: MirSummary::new(mir), | ||
} | ||
} | ||
|
||
pub fn analyze(&mut self, mir: &Mir<'tcx>) { | ||
let mut finder = DefUseFinder { | ||
info: mem::replace(&mut self.info, IndexVec::new()), | ||
mir_summary: self.mir_summary, | ||
}; | ||
finder.visit_mir(mir); | ||
self.info = finder.info | ||
} | ||
|
||
pub fn local_info(&self, local: Local) -> &Info<'tcx> { | ||
&self.info[local] | ||
} | ||
|
||
pub fn local_info_mut(&mut self, local: Local) -> &mut Info<'tcx> { | ||
&mut self.info[local] | ||
} | ||
|
||
fn mutate_defs_and_uses<F>(&self, local: Local, mir: &mut Mir<'tcx>, mut callback: F) | ||
where F: for<'a> FnMut(&'a mut Lvalue<'tcx>, | ||
LvalueContext<'tcx>, | ||
Location) { | ||
for lvalue_use in &self.info[local].defs_and_uses { | ||
MutateUseVisitor::new(local, | ||
&mut callback, | ||
self.mir_summary, | ||
mir).visit_location(mir, lvalue_use.location) | ||
} | ||
} | ||
|
||
/// FIXME(pcwalton): This should update the def-use chains. | ||
pub fn replace_all_defs_and_uses_with(&self, | ||
local: Local, | ||
mir: &mut Mir<'tcx>, | ||
new_lvalue: Lvalue<'tcx>) { | ||
self.mutate_defs_and_uses(local, mir, |lvalue, _, _| *lvalue = new_lvalue.clone()) | ||
} | ||
} | ||
|
||
struct DefUseFinder<'tcx> { | ||
info: IndexVec<Local, Info<'tcx>>, | ||
mir_summary: MirSummary, | ||
} | ||
|
||
impl<'tcx> DefUseFinder<'tcx> { | ||
fn lvalue_mut_info(&mut self, lvalue: &Lvalue<'tcx>) -> Option<&mut Info<'tcx>> { | ||
let info = &mut self.info; | ||
self.mir_summary.local_index(lvalue).map(move |local| &mut info[local]) | ||
} | ||
} | ||
|
||
impl<'tcx> Visitor<'tcx> for DefUseFinder<'tcx> { | ||
fn visit_lvalue(&mut self, | ||
lvalue: &Lvalue<'tcx>, | ||
context: LvalueContext<'tcx>, | ||
location: Location) { | ||
if let Some(ref mut info) = self.lvalue_mut_info(lvalue) { | ||
info.defs_and_uses.push(Use { | ||
context: context, | ||
location: location, | ||
}) | ||
} | ||
self.super_lvalue(lvalue, context, location) | ||
} | ||
} | ||
|
||
impl<'tcx> Info<'tcx> { | ||
fn new() -> Info<'tcx> { | ||
Info { | ||
defs_and_uses: vec![], | ||
} | ||
} | ||
|
||
pub fn def_count(&self) -> usize { | ||
self.defs_and_uses.iter().filter(|lvalue_use| lvalue_use.context.is_mutating_use()).count() | ||
} | ||
|
||
pub fn def_count_not_including_drop(&self) -> usize { | ||
self.defs_and_uses.iter().filter(|lvalue_use| { | ||
lvalue_use.context.is_mutating_use() && !lvalue_use.context.is_drop() | ||
}).count() | ||
} | ||
|
||
pub fn use_count(&self) -> usize { | ||
self.defs_and_uses.iter().filter(|lvalue_use| { | ||
lvalue_use.context.is_nonmutating_use() | ||
}).count() | ||
} | ||
} | ||
|
||
struct MutateUseVisitor<'tcx, F> { | ||
query: Local, | ||
callback: F, | ||
mir_summary: MirSummary, | ||
phantom: PhantomData<&'tcx ()>, | ||
} | ||
|
||
impl<'tcx, F> MutateUseVisitor<'tcx, F> { | ||
fn new(query: Local, callback: F, mir_summary: MirSummary, _: &Mir<'tcx>) | ||
-> MutateUseVisitor<'tcx, F> | ||
where F: for<'a> FnMut(&'a mut Lvalue<'tcx>, LvalueContext<'tcx>, Location) { | ||
MutateUseVisitor { | ||
query: query, | ||
callback: callback, | ||
mir_summary: mir_summary, | ||
phantom: PhantomData, | ||
} | ||
} | ||
} | ||
|
||
impl<'tcx, F> MutVisitor<'tcx> for MutateUseVisitor<'tcx, F> | ||
where F: for<'a> FnMut(&'a mut Lvalue<'tcx>, LvalueContext<'tcx>, Location) { | ||
fn visit_lvalue(&mut self, | ||
lvalue: &mut Lvalue<'tcx>, | ||
context: LvalueContext<'tcx>, | ||
location: Location) { | ||
if self.mir_summary.local_index(lvalue) == Some(self.query) { | ||
(self.callback)(lvalue, context, location) | ||
} | ||
self.super_lvalue(lvalue, context, location) | ||
} | ||
} | ||
|
||
/// A small structure that enables various metadata of the MIR to be queried | ||
/// without a reference to the MIR itself. | ||
#[derive(Clone, Copy)] | ||
struct MirSummary { | ||
arg_count: usize, | ||
var_count: usize, | ||
temp_count: usize, | ||
} | ||
|
||
impl MirSummary { | ||
fn new(mir: &Mir) -> MirSummary { | ||
MirSummary { | ||
arg_count: mir.arg_decls.len(), | ||
var_count: mir.var_decls.len(), | ||
temp_count: mir.temp_decls.len(), | ||
} | ||
} | ||
|
||
fn local_index<'tcx>(&self, lvalue: &Lvalue<'tcx>) -> Option<Local> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This might make a case for using these indices everywhere instead of separate arg/var/temp lvalues. |
||
match *lvalue { | ||
Lvalue::Arg(arg) => Some(Local::new(arg.index())), | ||
Lvalue::Var(var) => Some(Local::new(var.index() + self.arg_count)), | ||
Lvalue::Temp(temp) => { | ||
Some(Local::new(temp.index() + self.arg_count + self.var_count)) | ||
} | ||
Lvalue::ReturnPointer => { | ||
Some(Local::new(self.arg_count + self.var_count + self.temp_count)) | ||
} | ||
_ => None, | ||
} | ||
} | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,180 @@ | ||
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT | ||
// file at the top-level directory of this distribution and at | ||
// http://rust-lang.org/COPYRIGHT. | ||
// | ||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | ||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | ||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | ||
// option. This file may not be copied, modified, or distributed | ||
// except according to those terms. | ||
|
||
//! Trivial copy propagation pass. | ||
//! | ||
//! This uses def-use analysis to remove values that have exactly one def and one use, which must | ||
//! be an assignment. | ||
//! | ||
//! To give an example, we look for patterns that look like: | ||
//! | ||
//! DEST = SRC | ||
//! ... | ||
//! USE(DEST) | ||
//! | ||
//! where `DEST` and `SRC` are both locals of some form. We replace that with: | ||
//! | ||
//! NOP | ||
//! ... | ||
//! USE(SRC) | ||
//! | ||
//! The assignment `DEST = SRC` must be (a) the only mutation of `DEST` and (b) the only | ||
//! (non-mutating) use of `SRC`. These restrictions are conservative and may be relaxed in the | ||
//! future. | ||
use def_use::DefUseAnalysis; | ||
use rustc::mir::repr::{Local, Lvalue, Mir, Operand, Rvalue, StatementKind}; | ||
use rustc::mir::transform::{MirPass, MirSource, Pass}; | ||
use rustc::ty::TyCtxt; | ||
use rustc_data_structures::indexed_vec::Idx; | ||
|
||
pub struct CopyPropagation; | ||
|
||
impl Pass for CopyPropagation {} | ||
|
||
impl<'tcx> MirPass<'tcx> for CopyPropagation { | ||
fn run_pass<'a>(&mut self, _: TyCtxt<'a, 'tcx, 'tcx>, _: MirSource, mir: &mut Mir<'tcx>) { | ||
loop { | ||
let mut def_use_analysis = DefUseAnalysis::new(mir); | ||
def_use_analysis.analyze(mir); | ||
|
||
let mut changed = false; | ||
for dest_local_index in 0..mir.count_locals() { | ||
let dest_local = Local::new(dest_local_index); | ||
debug!("Considering destination local: {}", mir.format_local(dest_local)); | ||
|
||
let src_local; | ||
let location; | ||
{ | ||
// The destination must have exactly one def. | ||
let dest_use_info = def_use_analysis.local_info(dest_local); | ||
let dest_def_count = dest_use_info.def_count_not_including_drop(); | ||
if dest_def_count == 0 { | ||
debug!(" Can't copy-propagate local: dest {} undefined", | ||
mir.format_local(dest_local)); | ||
continue | ||
} | ||
if dest_def_count > 1 { | ||
debug!(" Can't copy-propagate local: dest {} defined {} times", | ||
mir.format_local(dest_local), | ||
dest_use_info.def_count()); | ||
continue | ||
} | ||
if dest_use_info.use_count() == 0 { | ||
debug!(" Can't copy-propagate local: dest {} unused", | ||
mir.format_local(dest_local)); | ||
continue | ||
} | ||
let dest_lvalue_def = dest_use_info.defs_and_uses.iter().filter(|lvalue_def| { | ||
lvalue_def.context.is_mutating_use() && !lvalue_def.context.is_drop() | ||
}).next().unwrap(); | ||
location = dest_lvalue_def.location; | ||
|
||
let basic_block = &mir[location.block]; | ||
let statement_index = location.statement_index; | ||
let statement = match basic_block.statements.get(statement_index) { | ||
Some(statement) => statement, | ||
None => { | ||
debug!(" Can't copy-propagate local: used in terminator"); | ||
continue | ||
} | ||
}; | ||
|
||
// That use of the source must be an assignment. | ||
let src_lvalue = match statement.kind { | ||
StatementKind::Assign( | ||
ref dest_lvalue, | ||
Rvalue::Use(Operand::Consume(ref src_lvalue))) | ||
if Some(dest_local) == mir.local_index(dest_lvalue) => { | ||
src_lvalue | ||
} | ||
_ => { | ||
debug!(" Can't copy-propagate local: source use is not an \ | ||
assignment"); | ||
continue | ||
} | ||
}; | ||
src_local = match mir.local_index(src_lvalue) { | ||
Some(src_local) => src_local, | ||
None => { | ||
debug!(" Can't copy-propagate local: source is not a local"); | ||
continue | ||
} | ||
}; | ||
|
||
// There must be exactly one use of the source used in a statement (not in a | ||
// terminator). | ||
let src_use_info = def_use_analysis.local_info(src_local); | ||
let src_use_count = src_use_info.use_count(); | ||
if src_use_count == 0 { | ||
debug!(" Can't copy-propagate local: no uses"); | ||
continue | ||
} | ||
if src_use_count != 1 { | ||
debug!(" Can't copy-propagate local: {} uses", src_use_info.use_count()); | ||
continue | ||
} | ||
|
||
// Verify that the source doesn't change in between. This is done | ||
// conservatively for now, by ensuring that the source has exactly one | ||
// mutation. The goal is to prevent things like: | ||
// | ||
// DEST = SRC; | ||
// SRC = X; | ||
// USE(DEST); | ||
// | ||
// From being misoptimized into: | ||
// | ||
// SRC = X; | ||
// USE(SRC); | ||
let src_def_count = src_use_info.def_count_not_including_drop(); | ||
if src_def_count != 1 { | ||
debug!(" Can't copy-propagate local: {} defs of src", | ||
src_use_info.def_count_not_including_drop()); | ||
continue | ||
} | ||
} | ||
|
||
// If all checks passed, then we can eliminate the destination and the assignment. | ||
// | ||
// First, remove all markers. | ||
// | ||
// FIXME(pcwalton): Don't do this. Merge live ranges instead. | ||
debug!(" Replacing all uses of {}", mir.format_local(dest_local)); | ||
for lvalue_use in &def_use_analysis.local_info(dest_local).defs_and_uses { | ||
if lvalue_use.context.is_storage_marker() { | ||
mir.make_statement_nop(lvalue_use.location) | ||
} | ||
} | ||
for lvalue_use in &def_use_analysis.local_info(src_local).defs_and_uses { | ||
if lvalue_use.context.is_storage_marker() { | ||
mir.make_statement_nop(lvalue_use.location) | ||
} | ||
} | ||
|
||
// Now replace all uses of the destination local with the source local. | ||
let src_lvalue = Lvalue::from_local(mir, src_local); | ||
def_use_analysis.replace_all_defs_and_uses_with(dest_local, mir, src_lvalue); | ||
|
||
// Finally, zap the now-useless assignment instruction. | ||
mir.make_statement_nop(location); | ||
|
||
changed = true; | ||
// FIXME(pcwalton): Update the use-def chains to delete the instructions instead of | ||
// regenerating the chains. | ||
break | ||
} | ||
if !changed { | ||
break | ||
} | ||
} | ||
} | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,4 +19,4 @@ pub mod qualify_consts; | |
pub mod dump_mir; | ||
pub mod deaggregator; | ||
pub mod instcombine; | ||
|
||
pub mod copy_prop; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -385,6 +385,7 @@ impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> { | |
} | ||
} | ||
} | ||
StatementKind::Nop => {} | ||
} | ||
} | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential point of disagreement (we already have at least one lazy patching mechanism which preserves indices).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is that one?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's in
src/librustc_borrowck/borrowck/mir/patch.rs
(because drop elaboration in there. IMOrustc_borrowck
should be replaced with a MIR version that doesn't live in arustc_borrowck
crate but that's besides the point).It doesn't have the ability to remove statements because it wasn't needed.
I'm not entirely clear on whether that functionality could be easily added. cc @arielb1