Skip to content

Commit 138926b

Browse files
committed
Auto merge of rust-lang#128299 - DianQK:clone-copy, r=<try>
Simplify the canonical clone method and the copy-like forms to copy Fixes rust-lang#128081. r? `@cjgillot`
2 parents 9649706 + 5b984a0 commit 138926b

File tree

48 files changed

+2046
-293
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+2046
-293
lines changed

compiler/rustc_mir_transform/src/gvn.rs

+97-1
Original file line numberDiff line numberDiff line change
@@ -876,6 +876,95 @@ impl<'body, 'tcx> VnState<'body, 'tcx> {
876876
None
877877
}
878878

879+
fn try_as_place_elem(
880+
&mut self,
881+
proj: ProjectionElem<VnIndex, Ty<'tcx>>,
882+
loc: Location,
883+
) -> Option<PlaceElem<'tcx>> {
884+
Some(match proj {
885+
ProjectionElem::Deref => ProjectionElem::Deref,
886+
ProjectionElem::Field(idx, ty) => ProjectionElem::Field(idx, ty),
887+
ProjectionElem::Index(idx) => {
888+
let Some(local) = self.try_as_local(idx, loc) else {
889+
return None;
890+
};
891+
self.reused_locals.insert(local);
892+
ProjectionElem::Index(local)
893+
}
894+
ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
895+
ProjectionElem::ConstantIndex { offset, min_length, from_end }
896+
}
897+
ProjectionElem::Subslice { from, to, from_end } => {
898+
ProjectionElem::Subslice { from, to, from_end }
899+
}
900+
ProjectionElem::Downcast(symbol, idx) => ProjectionElem::Downcast(symbol, idx),
901+
ProjectionElem::OpaqueCast(idx) => ProjectionElem::OpaqueCast(idx),
902+
ProjectionElem::Subtype(idx) => ProjectionElem::Subtype(idx),
903+
})
904+
}
905+
906+
fn simplify_aggregate_to_copy(
907+
&mut self,
908+
rvalue: &mut Rvalue<'tcx>,
909+
location: Location,
910+
fields: &[VnIndex],
911+
variant_index: VariantIdx,
912+
) -> Option<VnIndex> {
913+
let Some(&first_field) = fields.first() else {
914+
return None;
915+
};
916+
let Value::Projection(copy_from_value, _) = *self.get(first_field) else {
917+
return None;
918+
};
919+
// All fields must correspond one-to-one and come from the same aggregate value.
920+
if fields.iter().enumerate().any(|(index, &v)| {
921+
if let Value::Projection(pointer, ProjectionElem::Field(from_index, _)) = *self.get(v)
922+
&& copy_from_value == pointer
923+
&& from_index.index() == index
924+
{
925+
return false;
926+
}
927+
true
928+
}) {
929+
return None;
930+
}
931+
932+
let mut copy_from_local_value = copy_from_value;
933+
if let Value::Projection(pointer, proj) = *self.get(copy_from_value)
934+
&& let ProjectionElem::Downcast(_, read_variant) = proj
935+
{
936+
if variant_index == read_variant {
937+
// When copying a variant, there is no need to downcast.
938+
copy_from_local_value = pointer;
939+
} else {
940+
// The copied variant must be identical.
941+
return None;
942+
}
943+
}
944+
945+
let tcx = self.tcx;
946+
let mut projection = SmallVec::<[PlaceElem<'tcx>; 1]>::new();
947+
loop {
948+
if let Some(local) = self.try_as_local(copy_from_local_value, location) {
949+
projection.reverse();
950+
let place = Place { local, projection: tcx.mk_place_elems(projection.as_slice()) };
951+
if rvalue.ty(self.local_decls, tcx) == place.ty(self.local_decls, tcx).ty {
952+
self.reused_locals.insert(local);
953+
*rvalue = Rvalue::Use(Operand::Copy(place));
954+
return Some(copy_from_value);
955+
}
956+
return None;
957+
} else if let Value::Projection(pointer, proj) = *self.get(copy_from_local_value)
958+
&& let Some(proj) = self.try_as_place_elem(proj, location)
959+
{
960+
projection.push(proj);
961+
copy_from_local_value = pointer;
962+
} else {
963+
return None;
964+
}
965+
}
966+
}
967+
879968
fn simplify_aggregate(
880969
&mut self,
881970
rvalue: &mut Rvalue<'tcx>,
@@ -972,6 +1061,13 @@ impl<'body, 'tcx> VnState<'body, 'tcx> {
9721061
}
9731062
}
9741063

1064+
if let AggregateTy::Def(_, _) = ty
1065+
&& let Some(value) =
1066+
self.simplify_aggregate_to_copy(rvalue, location, &fields, variant_index)
1067+
{
1068+
return Some(value);
1069+
}
1070+
9751071
Some(self.insert(Value::Aggregate(ty, variant_index, fields)))
9761072
}
9771073

@@ -1485,7 +1581,7 @@ impl<'tcx> VnState<'_, 'tcx> {
14851581
}
14861582

14871583
/// If there is a local which is assigned `index`, and its assignment strictly dominates `loc`,
1488-
/// return it.
1584+
/// return it. If you used this local, add it to `reused_locals` to remove storage statements.
14891585
fn try_as_local(&mut self, index: VnIndex, loc: Location) -> Option<Local> {
14901586
let other = self.rev_locals.get(index)?;
14911587
other

compiler/rustc_mir_transform/src/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -588,15 +588,14 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
588588
// Now, we need to shrink the generated MIR.
589589
&ref_prop::ReferencePropagation,
590590
&sroa::ScalarReplacementOfAggregates,
591-
&match_branches::MatchBranchSimplification,
592-
// inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
593591
&multiple_return_terminators::MultipleReturnTerminators,
594592
// After simplifycfg, it allows us to discover new opportunities for peephole optimizations.
595593
&instsimplify::InstSimplify::AfterSimplifyCfg,
596594
&simplify::SimplifyLocals::BeforeConstProp,
597595
&dead_store_elimination::DeadStoreElimination::Initial,
598596
&gvn::GVN,
599597
&simplify::SimplifyLocals::AfterGVN,
598+
&match_branches::MatchBranchSimplification,
600599
&dataflow_const_prop::DataflowConstProp,
601600
&single_use_consts::SingleUseConsts,
602601
&o1(simplify_branches::SimplifyConstCondition::AfterConstProp),

compiler/rustc_mir_transform/src/match_branches.rs

+210-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
1-
use std::iter;
1+
use std::{iter, usize};
22

3+
use rustc_const_eval::const_eval::mk_eval_cx_for_const_val;
4+
use rustc_index::bit_set::BitSet;
35
use rustc_index::IndexSlice;
46
use rustc_middle::mir::patch::MirPatch;
57
use rustc_middle::mir::*;
8+
use rustc_middle::ty;
69
use rustc_middle::ty::layout::{IntegerExt, TyAndLayout};
10+
use rustc_middle::ty::util::Discr;
711
use rustc_middle::ty::{ParamEnv, ScalarInt, Ty, TyCtxt};
12+
use rustc_mir_dataflow::impls::{borrowed_locals, MaybeTransitiveLiveLocals};
13+
use rustc_mir_dataflow::Analysis;
814
use rustc_target::abi::Integer;
915
use rustc_type_ir::TyKind::*;
1016

@@ -48,6 +54,10 @@ impl<'tcx> MirPass<'tcx> for MatchBranchSimplification {
4854
should_cleanup = true;
4955
continue;
5056
}
57+
if simplify_to_copy(tcx, body, bb_idx, param_env).is_some() {
58+
should_cleanup = true;
59+
continue;
60+
}
5161
}
5262

5363
if should_cleanup {
@@ -515,3 +525,202 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp {
515525
}
516526
}
517527
}
528+
529+
/// This is primarily used to merge these copy statements that simplified the canonical enum clone method by GVN.
530+
/// The GVN simplified
531+
/// ```ignore (syntax-highlighting-only)
532+
/// match a {
533+
/// Foo::A(x) => Foo::A(*x),
534+
/// Foo::B => Foo::B
535+
/// }
536+
/// ```
537+
/// to
538+
/// ```ignore (syntax-highlighting-only)
539+
/// match a {
540+
/// Foo::A(_x) => a, // copy a
541+
/// Foo::B => Foo::B
542+
/// }
543+
/// ```
544+
/// This function will simplify into a copy statement.
545+
fn simplify_to_copy<'tcx>(
546+
tcx: TyCtxt<'tcx>,
547+
body: &mut Body<'tcx>,
548+
switch_bb_idx: BasicBlock,
549+
param_env: ParamEnv<'tcx>,
550+
) -> Option<()> {
551+
let bbs = &body.basic_blocks;
552+
// Check if the copy source matches the following pattern.
553+
// _2 = discriminant(*_1); // "*_1" is the expected the copy source.
554+
// switchInt(move _2) -> [0: bb3, 1: bb2, otherwise: bb1];
555+
let &Statement {
556+
kind: StatementKind::Assign(box (discr_place, Rvalue::Discriminant(expected_src_place))),
557+
..
558+
} = bbs[switch_bb_idx].statements.last()?
559+
else {
560+
return None;
561+
};
562+
let expected_src_ty = expected_src_place.ty(body.local_decls(), tcx);
563+
if !expected_src_ty.ty.is_enum() || expected_src_ty.variant_index.is_some() {
564+
return None;
565+
}
566+
let targets = match bbs[switch_bb_idx].terminator().kind {
567+
TerminatorKind::SwitchInt { ref discr, ref targets, .. }
568+
if discr.place() == Some(discr_place) =>
569+
{
570+
targets
571+
}
572+
_ => return None,
573+
};
574+
// We require that the possible target blocks all be distinct.
575+
if !targets.is_distinct() {
576+
return None;
577+
}
578+
if !bbs[targets.otherwise()].is_empty_unreachable() {
579+
return None;
580+
}
581+
// Check that destinations are identical, and if not, then don't optimize this block.
582+
let mut target_iter = targets.iter();
583+
let first_terminator_kind = &bbs[target_iter.next().unwrap().1].terminator().kind;
584+
if !target_iter
585+
.all(|(_, other_target)| first_terminator_kind == &bbs[other_target].terminator().kind)
586+
{
587+
return None;
588+
}
589+
590+
let borrowed_locals = borrowed_locals(body);
591+
let mut live = None;
592+
let mut expected_dest_place = None;
593+
for (index, target_bb) in targets.iter() {
594+
let stmts = &bbs[target_bb].statements;
595+
if stmts.is_empty() {
596+
return None;
597+
}
598+
if let [Statement { kind: StatementKind::Assign(box (place, rvalue)), .. }] =
599+
bbs[target_bb].statements.as_slice()
600+
{
601+
let dest_ty = place.ty(body.local_decls(), tcx);
602+
if dest_ty.ty != expected_src_ty.ty || dest_ty.variant_index.is_some() {
603+
return None;
604+
}
605+
let ty::Adt(def, _) = dest_ty.ty.kind() else {
606+
return None;
607+
};
608+
if *expected_dest_place.get_or_insert(*place) != *place {
609+
return None;
610+
}
611+
match rvalue {
612+
// Check if `_3 = const Foo::B` can be transformed to `_3 = copy *_1`.
613+
Rvalue::Use(Operand::Constant(box constant))
614+
if let Const::Val(const_, ty) = constant.const_ =>
615+
{
616+
let (ecx, op) =
617+
mk_eval_cx_for_const_val(tcx.at(constant.span), param_env, const_, ty)?;
618+
let variant = ecx.read_discriminant(&op).ok()?;
619+
if !def.variants()[variant].fields.is_empty() {
620+
return None;
621+
}
622+
let Discr { val, .. } = ty.discriminant_for_variant(tcx, variant)?;
623+
if val != index {
624+
return None;
625+
}
626+
}
627+
Rvalue::Use(Operand::Copy(src_place)) if *src_place == expected_src_place => {}
628+
// Check if `_3 = Foo::B` can be transformed to `_3 = copy *_1`.
629+
Rvalue::Aggregate(box AggregateKind::Adt(_, variant_index, _, _, None), fields)
630+
if fields.is_empty()
631+
&& let Some(Discr { val, .. }) =
632+
expected_src_ty.ty.discriminant_for_variant(tcx, *variant_index)
633+
&& val == index => {}
634+
_ => return None,
635+
}
636+
} else {
637+
// If the BB contains more than one statement, we have to check if these statements can be ignored.
638+
let mut lived_stmts: BitSet<usize> =
639+
BitSet::new_filled(bbs[target_bb].statements.len());
640+
let mut dest_place = None;
641+
for (statement_index, statement) in bbs[target_bb].statements.iter().enumerate().rev() {
642+
let loc = Location { block: target_bb, statement_index };
643+
if let StatementKind::Assign(assign) = &statement.kind {
644+
if !assign.1.is_safe_to_remove() {
645+
return None;
646+
}
647+
}
648+
match &statement.kind {
649+
StatementKind::Assign(box (place, _))
650+
| StatementKind::SetDiscriminant { place: box place, .. }
651+
| StatementKind::Deinit(box place) => {
652+
if place.is_indirect() || borrowed_locals.contains(place.local) {
653+
return None;
654+
}
655+
let live = live.get_or_insert_with(|| {
656+
MaybeTransitiveLiveLocals::new(&borrowed_locals)
657+
.into_engine(tcx, body)
658+
.iterate_to_fixpoint()
659+
.into_results_cursor(body)
660+
});
661+
live.seek_before_primary_effect(loc);
662+
if !live.get().contains(place.local) {
663+
lived_stmts.remove(statement_index);
664+
} else if matches!(
665+
&statement.kind,
666+
StatementKind::Assign(box (_, Rvalue::Use(Operand::Copy(_))))
667+
) && dest_place.is_none()
668+
{
669+
// There is only one statement that cannot be ignored that can be used as an expected copy statement.
670+
dest_place = Some(*place);
671+
} else {
672+
return None;
673+
}
674+
}
675+
StatementKind::StorageLive(_)
676+
| StatementKind::StorageDead(_)
677+
| StatementKind::Nop => (),
678+
679+
StatementKind::Retag(_, _)
680+
| StatementKind::Coverage(_)
681+
| StatementKind::Intrinsic(_)
682+
| StatementKind::ConstEvalCounter
683+
| StatementKind::PlaceMention(_)
684+
| StatementKind::FakeRead(_)
685+
| StatementKind::AscribeUserType(_, _) => {
686+
return None;
687+
}
688+
}
689+
}
690+
let dest_place = dest_place?;
691+
if *expected_dest_place.get_or_insert(dest_place) != dest_place {
692+
return None;
693+
}
694+
// We can ignore the paired StorageLive and StorageDead.
695+
let mut storage_live_locals: BitSet<Local> = BitSet::new_empty(body.local_decls.len());
696+
for stmt_index in lived_stmts.iter() {
697+
let statement = &bbs[target_bb].statements[stmt_index];
698+
match &statement.kind {
699+
StatementKind::Assign(box (place, Rvalue::Use(Operand::Copy(src_place))))
700+
if *place == dest_place && *src_place == expected_src_place => {}
701+
StatementKind::StorageLive(local)
702+
if *local != dest_place.local && storage_live_locals.insert(*local) => {}
703+
StatementKind::StorageDead(local)
704+
if *local != dest_place.local && storage_live_locals.remove(*local) => {}
705+
StatementKind::Nop => {}
706+
_ => return None,
707+
}
708+
}
709+
if !storage_live_locals.is_empty() {
710+
return None;
711+
}
712+
}
713+
}
714+
let expected_dest_place = expected_dest_place?;
715+
let statement_index = bbs[switch_bb_idx].statements.len();
716+
let parent_end = Location { block: switch_bb_idx, statement_index };
717+
let mut patch = MirPatch::new(body);
718+
patch.add_assign(
719+
parent_end,
720+
expected_dest_place,
721+
Rvalue::Use(Operand::Copy(expected_src_place)),
722+
);
723+
patch.patch_terminator(switch_bb_idx, first_terminator_kind.clone());
724+
patch.apply(body);
725+
Some(())
726+
}

0 commit comments

Comments
 (0)