use crate::dataflow::impls::{MaybeInitializedLocals, MaybeLiveLocals};
use crate::dataflow::Analysis;
use crate::{
transform::MirPass,
util::{dump_mir, PassWhere},
};
use itertools::Itertools;
use rustc_data_structures::unify::{InPlaceUnificationTable, UnifyKey};
use rustc_index::{
bit_set::{BitMatrix, BitSet},
vec::IndexVec,
};
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
use rustc_middle::mir::{
traversal, Body, InlineAsmOperand, Local, LocalKind, Location, Operand, Place, PlaceElem,
Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
};
use rustc_middle::ty::{self, Ty, TyCtxt};
const MAX_LOCALS: usize = 500;
const MAX_BLOCKS: usize = 250;
pub struct DestinationPropagation;
impl<'tcx> MirPass<'tcx> for DestinationPropagation {
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
if tcx.sess.opts.debugging_opts.mir_opt_level <= 1 {
return;
}
let def_id = body.source.def_id();
let candidates = find_candidates(tcx, body);
if candidates.is_empty() {
debug!("{:?}: no dest prop candidates, done", def_id);
return;
}
let mut relevant_locals = BitSet::new_empty(body.local_decls.len());
for CandidateAssignment { dest, src, loc: _ } in &candidates {
relevant_locals.insert(dest.local);
relevant_locals.insert(*src);
}
let relevant = relevant_locals.count();
debug!(
"{:?}: {} locals ({} relevant), {} blocks",
def_id,
body.local_decls.len(),
relevant,
body.basic_blocks().len()
);
if relevant > MAX_LOCALS {
warn!(
"too many candidate locals in {:?} ({}, max is {}), not optimizing",
def_id, relevant, MAX_LOCALS
);
return;
}
if body.basic_blocks().len() > MAX_BLOCKS {
warn!(
"too many blocks in {:?} ({}, max is {}), not optimizing",
def_id,
body.basic_blocks().len(),
MAX_BLOCKS
);
return;
}
let mut conflicts = Conflicts::build(tcx, body, &relevant_locals);
let mut replacements = Replacements::new(body.local_decls.len());
for candidate @ CandidateAssignment { dest, src, loc } in candidates {
if !conflicts.can_unify(dest.local, src) {
debug!("at assignment {:?}, conflict {:?} vs. {:?}", loc, dest.local, src);
continue;
}
if replacements.for_src(candidate.src).is_some() {
debug!("src {:?} already has replacement", candidate.src);
continue;
}
if !tcx.consider_optimizing(|| {
format!("DestinationPropagation {:?} {:?}", def_id, candidate)
}) {
break;
}
replacements.push(candidate);
conflicts.unify(candidate.src, candidate.dest.local);
}
replacements.flatten(tcx);
debug!("replacements {:?}", replacements.map);
Replacer { tcx, replacements, place_elem_cache: Vec::new() }.visit_body(body);
}
}
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
struct UnifyLocal(Local);
impl From<Local> for UnifyLocal {
fn from(l: Local) -> Self {
Self(l)
}
}
impl UnifyKey for UnifyLocal {
type Value = ();
fn index(&self) -> u32 {
self.0.as_u32()
}
fn from_index(u: u32) -> Self {
Self(Local::from_u32(u))
}
fn tag() -> &'static str {
"UnifyLocal"
}
}
struct Replacements<'tcx> {
map: IndexVec<Local, Option<Place<'tcx>>>,
kill: BitSet<Local>,
}
impl Replacements<'tcx> {
fn new(locals: usize) -> Self {
Self { map: IndexVec::from_elem_n(None, locals), kill: BitSet::new_empty(locals) }
}
fn push(&mut self, candidate: CandidateAssignment<'tcx>) {
trace!("Replacements::push({:?})", candidate);
let entry = &mut self.map[candidate.src];
assert!(entry.is_none());
*entry = Some(candidate.dest);
self.kill.insert(candidate.src);
self.kill.insert(candidate.dest.local);
}
fn flatten(&mut self, tcx: TyCtxt<'tcx>) {
for local in self.map.indices() {
if let Some(replacement) = self.map[local] {
let mut base = replacement.local;
let mut reversed_projection_slices = Vec::with_capacity(1);
while let Some(replacement_for_replacement) = self.map[base] {
base = replacement_for_replacement.local;
reversed_projection_slices.push(replacement_for_replacement.projection);
}
let projection: Vec<_> = reversed_projection_slices
.iter()
.rev()
.flat_map(|projs| projs.iter())
.chain(replacement.projection.iter())
.collect();
let projection = tcx.intern_place_elems(&projection);
self.map[local] = Some(Place { local: base, projection });
}
}
}
fn for_src(&self, src: Local) -> Option<Place<'tcx>> {
self.map[src]
}
}
struct Replacer<'tcx> {
tcx: TyCtxt<'tcx>,
replacements: Replacements<'tcx>,
place_elem_cache: Vec<PlaceElem<'tcx>>,
}
impl<'tcx> MutVisitor<'tcx> for Replacer<'tcx> {
fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
self.tcx
}
fn visit_local(&mut self, local: &mut Local, context: PlaceContext, location: Location) {
if context.is_use() && self.replacements.for_src(*local).is_some() {
bug!(
"use of local {:?} should have been replaced by visit_place; context={:?}, loc={:?}",
local,
context,
location,
);
}
}
fn process_projection_elem(
&mut self,
elem: PlaceElem<'tcx>,
_: Location,
) -> Option<PlaceElem<'tcx>> {
match elem {
PlaceElem::Index(local) => {
if let Some(replacement) = self.replacements.for_src(local) {
bug!(
"cannot replace {:?} with {:?} in index projection {:?}",
local,
replacement,
elem,
);
} else {
None
}
}
_ => None,
}
}
fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
if let Some(replacement) = self.replacements.for_src(place.local) {
self.place_elem_cache.clear();
self.place_elem_cache.extend(replacement.projection.iter().chain(place.projection));
let projection = self.tcx.intern_place_elems(&self.place_elem_cache);
let new_place = Place { local: replacement.local, projection };
debug!("Replacer: {:?} -> {:?}", place, new_place);
*place = new_place;
}
self.super_place(place, context, location);
}
fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
self.super_statement(statement, location);
match &statement.kind {
StatementKind::StorageDead(local) | StatementKind::StorageLive(local)
if self.replacements.kill.contains(*local) =>
{
statement.make_nop()
}
StatementKind::Assign(box (dest, rvalue)) => {
match rvalue {
Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) => {
if dest == place {
debug!("{:?} turned into self-assignment, deleting", location);
statement.make_nop();
}
}
_ => {}
}
}
_ => {}
}
}
}
struct Conflicts<'a> {
relevant_locals: &'a BitSet<Local>,
matrix: BitMatrix<Local, Local>,
unify_cache: BitSet<Local>,
unified_locals: InPlaceUnificationTable<UnifyLocal>,
}
impl Conflicts<'a> {
fn build<'tcx>(
tcx: TyCtxt<'tcx>,
body: &'_ Body<'tcx>,
relevant_locals: &'a BitSet<Local>,
) -> Self {
let conflicts = BitMatrix::from_row_n(
&BitSet::new_empty(body.local_decls.len()),
body.local_decls.len(),
);
let mut init = MaybeInitializedLocals
.into_engine(tcx, body)
.iterate_to_fixpoint()
.into_results_cursor(body);
let mut live =
MaybeLiveLocals.into_engine(tcx, body).iterate_to_fixpoint().into_results_cursor(body);
let mut reachable = None;
dump_mir(tcx, None, "DestinationPropagation-dataflow", &"", body, |pass_where, w| {
let reachable = reachable.get_or_insert_with(|| traversal::reachable_as_bitset(body));
match pass_where {
PassWhere::BeforeLocation(loc) if reachable.contains(loc.block) => {
init.seek_before_primary_effect(loc);
live.seek_after_primary_effect(loc);
writeln!(w, " // init: {:?}", init.get())?;
writeln!(w, " // live: {:?}", live.get())?;
}
PassWhere::AfterTerminator(bb) if reachable.contains(bb) => {
let loc = body.terminator_loc(bb);
init.seek_after_primary_effect(loc);
live.seek_before_primary_effect(loc);
writeln!(w, " // init: {:?}", init.get())?;
writeln!(w, " // live: {:?}", live.get())?;
}
PassWhere::BeforeBlock(bb) if reachable.contains(bb) => {
init.seek_to_block_start(bb);
live.seek_to_block_start(bb);
writeln!(w, " // init: {:?}", init.get())?;
writeln!(w, " // live: {:?}", live.get())?;
}
PassWhere::BeforeCFG | PassWhere::AfterCFG | PassWhere::AfterLocation(_) => {}
PassWhere::BeforeLocation(_) | PassWhere::AfterTerminator(_) => {
writeln!(w, " // init: <unreachable>")?;
writeln!(w, " // live: <unreachable>")?;
}
PassWhere::BeforeBlock(_) => {
writeln!(w, " // init: <unreachable>")?;
writeln!(w, " // live: <unreachable>")?;
}
}
Ok(())
});
let mut this = Self {
relevant_locals,
matrix: conflicts,
unify_cache: BitSet::new_empty(body.local_decls.len()),
unified_locals: {
let mut table = InPlaceUnificationTable::new();
for local in 0..body.local_decls.len() {
assert_eq!(table.new_key(()), UnifyLocal(Local::from_usize(local)));
}
table
},
};
let mut live_and_init_locals = Vec::new();
for (block, data) in traversal::preorder(body) {
live_and_init_locals.resize_with(data.statements.len() + 1, || {
BitSet::new_empty(body.local_decls.len())
});
for (i, statement) in data.statements.iter().enumerate() {
this.record_statement_conflicts(statement);
let loc = Location { block, statement_index: i };
init.seek_before_primary_effect(loc);
live_and_init_locals[i].clone_from(init.get());
}
this.record_terminator_conflicts(data.terminator());
let term_loc = Location { block, statement_index: data.statements.len() };
init.seek_before_primary_effect(term_loc);
live_and_init_locals[term_loc.statement_index].clone_from(init.get());
for statement_index in (0..=data.statements.len()).rev() {
let loc = Location { block, statement_index };
live.seek_after_primary_effect(loc);
live_and_init_locals[statement_index].intersect(live.get());
trace!("record conflicts at {:?}", loc);
this.record_dataflow_conflicts(&mut live_and_init_locals[statement_index]);
}
init.seek_to_block_end(block);
live.seek_to_block_end(block);
let mut conflicts = init.get().clone();
conflicts.intersect(live.get());
trace!("record conflicts at end of {:?}", block);
this.record_dataflow_conflicts(&mut conflicts);
}
this
}
fn record_dataflow_conflicts(&mut self, new_conflicts: &mut BitSet<Local>) {
new_conflicts.intersect(self.relevant_locals);
for local in new_conflicts.iter() {
self.matrix.union_row_with(&new_conflicts, local);
}
}
fn record_local_conflict(&mut self, a: Local, b: Local, why: &str) {
trace!("conflict {:?} <-> {:?} due to {}", a, b, why);
self.matrix.insert(a, b);
self.matrix.insert(b, a);
}
fn record_statement_conflicts(&mut self, stmt: &Statement<'_>) {
match &stmt.kind {
StatementKind::Assign(_) => {}
StatementKind::LlvmInlineAsm(asm) => {
for (_, input) in &*asm.inputs {
if let Some(in_place) = input.place() {
if !in_place.is_indirect() {
for out_place in &*asm.outputs {
if !out_place.is_indirect() && !in_place.is_indirect() {
self.record_local_conflict(
in_place.local,
out_place.local,
"aliasing llvm_asm! operands",
);
}
}
}
}
}
}
StatementKind::SetDiscriminant { .. }
| StatementKind::StorageLive(..)
| StatementKind::StorageDead(..)
| StatementKind::Retag(..)
| StatementKind::FakeRead(..)
| StatementKind::AscribeUserType(..)
| StatementKind::Coverage(..)
| StatementKind::Nop => {}
}
}
fn record_terminator_conflicts(&mut self, term: &Terminator<'_>) {
match &term.kind {
TerminatorKind::DropAndReplace {
place: dropped_place,
value,
target: _,
unwind: _,
} => {
if let Some(place) = value.place() {
if !place.is_indirect() && !dropped_place.is_indirect() {
self.record_local_conflict(
place.local,
dropped_place.local,
"DropAndReplace operand overlap",
);
}
}
}
TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
if let Some(place) = value.place() {
if !place.is_indirect() && !resume_arg.is_indirect() {
self.record_local_conflict(
place.local,
resume_arg.local,
"Yield operand overlap",
);
}
}
}
TerminatorKind::Call {
func,
args,
destination: Some((dest_place, _)),
cleanup: _,
from_hir_call: _,
fn_span: _,
} => {
for arg in args.iter().chain(Some(func)) {
if let Some(place) = arg.place() {
if !place.is_indirect() && !dest_place.is_indirect() {
self.record_local_conflict(
dest_place.local,
place.local,
"call dest/arg overlap",
);
}
}
}
}
TerminatorKind::InlineAsm {
template: _,
operands,
options: _,
line_spans: _,
destination: _,
} => {
for op in operands {
match op {
InlineAsmOperand::Out { reg: _, late: _, place: Some(dest_place) }
| InlineAsmOperand::InOut {
reg: _,
late: _,
in_value: _,
out_place: Some(dest_place),
} => {
for op in operands {
match op {
InlineAsmOperand::In { reg: _, value } => {
if let Some(p) = value.place() {
if !p.is_indirect() && !dest_place.is_indirect() {
self.record_local_conflict(
p.local,
dest_place.local,
"asm! operand overlap",
);
}
}
}
InlineAsmOperand::Out {
reg: _,
late: _,
place: Some(place),
} => {
if !place.is_indirect() && !dest_place.is_indirect() {
self.record_local_conflict(
place.local,
dest_place.local,
"asm! operand overlap",
);
}
}
InlineAsmOperand::InOut {
reg: _,
late: _,
in_value,
out_place,
} => {
if let Some(place) = in_value.place() {
if !place.is_indirect() && !dest_place.is_indirect() {
self.record_local_conflict(
place.local,
dest_place.local,
"asm! operand overlap",
);
}
}
if let Some(place) = out_place {
if !place.is_indirect() && !dest_place.is_indirect() {
self.record_local_conflict(
place.local,
dest_place.local,
"asm! operand overlap",
);
}
}
}
InlineAsmOperand::Out { reg: _, late: _, place: None }
| InlineAsmOperand::Const { value: _ }
| InlineAsmOperand::SymFn { value: _ }
| InlineAsmOperand::SymStatic { def_id: _ } => {}
}
}
}
InlineAsmOperand::Const { value } => {
assert!(value.place().is_none());
}
InlineAsmOperand::InOut {
reg: _,
late: _,
in_value: _,
out_place: None,
}
| InlineAsmOperand::In { reg: _, value: _ }
| InlineAsmOperand::Out { reg: _, late: _, place: None }
| InlineAsmOperand::SymFn { value: _ }
| InlineAsmOperand::SymStatic { def_id: _ } => {}
}
}
}
TerminatorKind::Goto { .. }
| TerminatorKind::Call { destination: None, .. }
| TerminatorKind::SwitchInt { .. }
| TerminatorKind::Resume
| TerminatorKind::Abort
| TerminatorKind::Return
| TerminatorKind::Unreachable
| TerminatorKind::Drop { .. }
| TerminatorKind::Assert { .. }
| TerminatorKind::GeneratorDrop
| TerminatorKind::FalseEdge { .. }
| TerminatorKind::FalseUnwind { .. } => {}
}
}
fn can_unify(&mut self, a: Local, b: Local) -> bool {
let a = self.unified_locals.find(a).0;
let b = self.unified_locals.find(b).0;
if a == b {
return false;
}
if self.matrix.contains(a, b) {
return false;
}
true
}
fn unify(&mut self, a: Local, b: Local) {
trace!("unify({:?}, {:?})", a, b);
let a = self.unified_locals.find(a).0;
let b = self.unified_locals.find(b).0;
assert_ne!(a, b);
trace!("roots: a={:?}, b={:?}", a, b);
trace!("{:?} conflicts: {:?}", a, self.matrix.iter(a).format(", "));
trace!("{:?} conflicts: {:?}", b, self.matrix.iter(b).format(", "));
self.unified_locals.union(a, b);
let root = self.unified_locals.find(a).0;
assert!(root == a || root == b);
self.unify_cache.clear();
for conflicts_with_a in self.matrix.iter(a) {
self.unify_cache.insert(conflicts_with_a);
}
for conflicts_with_b in self.matrix.iter(b) {
self.unify_cache.insert(conflicts_with_b);
}
for conflicts_with_a_or_b in self.unify_cache.iter() {
self.matrix.insert(conflicts_with_a_or_b, a);
self.matrix.insert(conflicts_with_a_or_b, b);
}
self.matrix.union_rows(a, b);
self.matrix.union_rows(b, a);
}
}
#[derive(Debug, Copy, Clone)]
struct CandidateAssignment<'tcx> {
dest: Place<'tcx>,
src: Local,
loc: Location,
}
fn find_candidates<'a, 'tcx>(
tcx: TyCtxt<'tcx>,
body: &'a Body<'tcx>,
) -> Vec<CandidateAssignment<'tcx>> {
let mut visitor = FindAssignments {
tcx,
body,
candidates: Vec::new(),
ever_borrowed_locals: ever_borrowed_locals(body),
locals_used_as_array_index: locals_used_as_array_index(body),
};
visitor.visit_body(body);
visitor.candidates
}
struct FindAssignments<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
body: &'a Body<'tcx>,
candidates: Vec<CandidateAssignment<'tcx>>,
ever_borrowed_locals: BitSet<Local>,
locals_used_as_array_index: BitSet<Local>,
}
impl<'a, 'tcx> Visitor<'tcx> for FindAssignments<'a, 'tcx> {
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
if let StatementKind::Assign(box (
dest,
Rvalue::Use(Operand::Copy(src) | Operand::Move(src)),
)) = &statement.kind
{
if dest.is_indirect() {
return;
}
if !src.projection.is_empty() {
return;
}
if is_local_required(src.local, self.body) {
return;
}
if self.ever_borrowed_locals.contains(dest.local)
|| self.ever_borrowed_locals.contains(src.local)
{
return;
}
assert_ne!(dest.local, src.local, "self-assignments are UB");
if self.locals_used_as_array_index.contains(src.local) {
return;
}
let is_union = |ty: Ty<'_>| {
if let ty::Adt(def, _) = ty.kind() {
if def.is_union() {
return true;
}
}
false
};
let mut place_ty = PlaceTy::from_ty(self.body.local_decls[dest.local].ty);
if is_union(place_ty.ty) {
return;
}
for elem in dest.projection {
if let PlaceElem::Index(_) = elem {
return;
}
place_ty = place_ty.projection_ty(self.tcx, elem);
if is_union(place_ty.ty) {
return;
}
}
self.candidates.push(CandidateAssignment {
dest: *dest,
src: src.local,
loc: location,
});
}
}
}
fn is_local_required(local: Local, body: &Body<'_>) -> bool {
match body.local_kind(local) {
LocalKind::Arg | LocalKind::ReturnPointer => true,
LocalKind::Var | LocalKind::Temp => false,
}
}
fn ever_borrowed_locals(body: &Body<'_>) -> BitSet<Local> {
let mut visitor = BorrowCollector { locals: BitSet::new_empty(body.local_decls.len()) };
visitor.visit_body(body);
visitor.locals
}
struct BorrowCollector {
locals: BitSet<Local>,
}
impl<'tcx> Visitor<'tcx> for BorrowCollector {
fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
self.super_rvalue(rvalue, location);
match rvalue {
Rvalue::AddressOf(_, borrowed_place) | Rvalue::Ref(_, _, borrowed_place) => {
if !borrowed_place.is_indirect() {
self.locals.insert(borrowed_place.local);
}
}
Rvalue::Cast(..)
| Rvalue::Use(..)
| Rvalue::Repeat(..)
| Rvalue::Len(..)
| Rvalue::BinaryOp(..)
| Rvalue::CheckedBinaryOp(..)
| Rvalue::NullaryOp(..)
| Rvalue::UnaryOp(..)
| Rvalue::Discriminant(..)
| Rvalue::Aggregate(..)
| Rvalue::ThreadLocalRef(..) => {}
}
}
fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
self.super_terminator(terminator, location);
match terminator.kind {
TerminatorKind::Drop { place: dropped_place, .. }
| TerminatorKind::DropAndReplace { place: dropped_place, .. } => {
self.locals.insert(dropped_place.local);
}
TerminatorKind::Abort
| TerminatorKind::Assert { .. }
| TerminatorKind::Call { .. }
| TerminatorKind::FalseEdge { .. }
| TerminatorKind::FalseUnwind { .. }
| TerminatorKind::GeneratorDrop
| TerminatorKind::Goto { .. }
| TerminatorKind::Resume
| TerminatorKind::Return
| TerminatorKind::SwitchInt { .. }
| TerminatorKind::Unreachable
| TerminatorKind::Yield { .. }
| TerminatorKind::InlineAsm { .. } => {}
}
}
}
fn locals_used_as_array_index(body: &Body<'_>) -> BitSet<Local> {
let mut visitor = IndexCollector { locals: BitSet::new_empty(body.local_decls.len()) };
visitor.visit_body(body);
visitor.locals
}
struct IndexCollector {
locals: BitSet<Local>,
}
impl<'tcx> Visitor<'tcx> for IndexCollector {
fn visit_projection_elem(
&mut self,
local: Local,
proj_base: &[PlaceElem<'tcx>],
elem: PlaceElem<'tcx>,
context: PlaceContext,
location: Location,
) {
if let PlaceElem::Index(i) = elem {
self.locals.insert(i);
}
self.super_projection_elem(local, proj_base, elem, context, location);
}
}