diff --git a/compiler/rustc_index/src/interval.rs b/compiler/rustc_index/src/interval.rs index d0dcb947c6d1c..475c81e66ab09 100644 --- a/compiler/rustc_index/src/interval.rs +++ b/compiler/rustc_index/src/interval.rs @@ -1,6 +1,7 @@ use std::iter::Step; use std::marker::PhantomData; -use std::ops::{Bound, Range, RangeBounds}; +use std::ops::{Bound, RangeBounds}; +use std::range::RangeInclusive; use smallvec::SmallVec; @@ -59,11 +60,14 @@ impl IntervalSet { } /// Iterates through intervals stored in the set, in order. - pub fn iter_intervals(&self) -> impl Iterator> + pub fn iter_intervals(&self) -> impl Iterator> where I: Step, { - self.map.iter().map(|&(start, end)| I::new(start as usize)..I::new(end as usize + 1)) + self.map.iter().map(|&(start, end)| RangeInclusive { + start: I::new(start as usize), + last: I::new(end as usize), + }) } /// Returns true if we increased the number of elements present. @@ -204,17 +208,38 @@ impl IntervalSet { needle <= *prev_end } + /// Returns whether any point in `range` is contained in the set. + pub fn intersects_range(&self, range: impl RangeBounds + Clone) -> bool { + let start = inclusive_start(range.clone()); + let Some(end) = inclusive_end(self.domain, range) else { + // empty range + return false; + }; + if start > end { + return false; + } + + // Find the last interval whose start is <= end. + let Some(last) = self.map.partition_point(|r| r.0 <= end).checked_sub(1) else { + // All ranges in the map start after the new range's end + return false; + }; + let (_, prev_end) = &self.map[last]; + start <= *prev_end + } + pub fn superset(&self, other: &IntervalSet) -> bool where I: Step, { let mut sup_iter = self.iter_intervals(); let mut current = None; - let contains = |sup: Range, sub: Range, current: &mut Option>| { - if sup.end < sub.start { - // if `sup.end == sub.start`, the next sup doesn't contain `sub.start` + let contains = |sup: RangeInclusive, + sub: RangeInclusive, + current: &mut Option>| { + if sup.last < sub.start { None // continue to the next sup - } else if sup.end >= sub.end && sup.start <= sub.start { + } else if sup.last >= sub.last && sup.start <= sub.start { *current = Some(sup); // save the current sup Some(true) } else { @@ -224,8 +249,8 @@ impl IntervalSet { other.iter_intervals().all(|sub| { current .take() - .and_then(|sup| contains(sup, sub.clone(), &mut current)) - .or_else(|| sup_iter.find_map(|sup| contains(sup, sub.clone(), &mut current))) + .and_then(|sup| contains(sup, sub, &mut current)) + .or_else(|| sup_iter.find_map(|sup| contains(sup, sub, &mut current))) .unwrap_or(false) }) } @@ -242,11 +267,11 @@ impl IntervalSet { let mut other_current = other_iter.next()?; loop { - if self_current.end <= other_current.start { + if self_current.last < other_current.start { self_current = self_iter.next()?; continue; } - if other_current.end <= self_current.start { + if other_current.last < self_current.start { other_current = other_iter.next()?; continue; } diff --git a/compiler/rustc_index/src/interval/tests.rs b/compiler/rustc_index/src/interval/tests.rs index 375af60f66207..cf3222e6c6572 100644 --- a/compiler/rustc_index/src/interval/tests.rs +++ b/compiler/rustc_index/src/interval/tests.rs @@ -5,7 +5,7 @@ fn insert_collapses() { let mut set = IntervalSet::::new(10000); set.insert_range(9831..=9837); set.insert_range(43..=9830); - assert_eq!(set.iter_intervals().collect::>(), [43..9838]); + assert_eq!(set.iter_intervals().collect::>(), [(43..=9837).into()]); } #[test] diff --git a/compiler/rustc_mir_dataflow/src/points.rs b/compiler/rustc_mir_dataflow/src/points.rs index 8568f325f1306..a4e5a3a79f04a 100644 --- a/compiler/rustc_mir_dataflow/src/points.rs +++ b/compiler/rustc_mir_dataflow/src/points.rs @@ -61,6 +61,15 @@ impl DenseLocationMap { PointIndex::new(start_index) } + /// Returns the `PointIndex` for the terminator in the given `BasicBlock`. O(1). + #[inline] + pub fn terminator(&self, block: BasicBlock) -> PointIndex { + let next_block = BasicBlock::new(block.index() + 1); + let next_start_index = + *self.statements_before_block.get(next_block).unwrap_or(&self.num_points); + PointIndex::new(next_start_index - 1) + } + /// Return the PointIndex for the block start of this index. #[inline] pub fn to_block_start(&self, index: PointIndex) -> PointIndex { diff --git a/compiler/rustc_mir_transform/src/move_elimination.rs b/compiler/rustc_mir_transform/src/move_elimination.rs index e02f1103fbf77..95a7f8cf237b5 100644 --- a/compiler/rustc_mir_transform/src/move_elimination.rs +++ b/compiler/rustc_mir_transform/src/move_elimination.rs @@ -70,10 +70,13 @@ //! as `Index` projections. These locals may only be replaced by another bare //! local. //! -//! # Storage lifetimes +//! # Storage reconstruction //! -//! The original storage markers no longer describe the merged locals, so they -//! are removed. Locals without storage markers have storage for the full function. +//! The original `StorageLive` and `StorageDead` statements no longer describe +//! the merged liveness produced by unification, so they are removed and rebuilt +//! from the liveness matrix when lifetime markers are emitted. This is done for +//! all locals, even ones that have not been merged, which has the additional +//! benefit of tightening the storage lifetime passed to LLVM. //! //! # Aliasing fixup //! @@ -101,16 +104,23 @@ //! `Discriminant`, `Ref`, and `RawPtr`, are left untouched because their //! codegen does not rely on the no-aliasing assumption. +use std::range::RangeInclusive; + use rustc_abi::{ExternAbi, FieldIdx, VariantIdx}; use rustc_const_eval::util::most_packed_projection; +use rustc_data_structures::fx::FxHashMap; use rustc_index::IndexVec; use rustc_index::bit_set::DenseBitSet; use rustc_index::interval::SparseIntervalMatrix; use rustc_middle::mir::visit::{MutVisitor, NonUseContext, PlaceContext, VisitPlacesWith, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::{Ty, TyCtxt}; -use rustc_mir_dataflow::impls::{SplitPointIndex, dump_liveness_matrix, liveness_matrix}; +use rustc_mir_dataflow::impls::{ + DefUse, SplitPointEffect, SplitPointIndex, VisitAllocatedLocalsWith, dump_liveness_matrix, + liveness_matrix, +}; use rustc_mir_dataflow::points::DenseLocationMap; +use rustc_mir_dataflow::{Analysis, Backward, GenKill, ResultsVisitor, visit_results}; use tracing::{debug, trace}; use crate::PassPolicy; @@ -154,6 +164,10 @@ impl<'tcx> crate::MirPass<'tcx> for MoveElimination { dump_liveness_matrix(tcx, body, "MoveElimination.post-liveness", &points, &liveness_matrix); + if tcx.sess.emit_lifetime_markers() { + reconstruct_storage(tcx, body, &points, &liveness_matrix); + } + apply_alias_fixup(tcx, body); } } @@ -591,6 +605,345 @@ impl<'tcx> MutVisitor<'tcx> for PlaceUpdater<'_, 'tcx> { } } +//////////////////////////////////////////////////////////////////////////////// +// Storage reconstruction + +/// Backward dataflow analysis which answers the question: from this point, is +/// there a path whose first access to a local is an initialization? +/// +/// This is used when a local is dead in a predecessor but maybe-live in its +/// successor. A `StorageLive` is inserted on that edge only if some continuation +/// initializes the local before reading it. If every continuation instead +/// reads the local first or never accesses it, `StorageLive` would be +/// unnecessary: it only allocates uninitialized storage and cannot make the +/// read valid. +/// +/// For example: +/// +/// ```text +/// bb1 bb2 +/// StorageLive(_1); _1 = ... // _1 is dead +/// _flag = true _flag = false +/// \ / +/// \ / +/// bb3 +/// switchInt(_flag) +/// / \ +/// bb4: use(_1) bb5: no use +/// ``` +/// +/// Liveness is path-insensitive, so `_1` is maybe-live in `bb3`: it is live in +/// `bb1` and `bb4`, but dead in `bb2` and `bb5`. Nevertheless, no `StorageLive` +/// is needed on `bb2 -> bb3`. The continuation to `bb5` never accesses `_1`, +/// while the continuation to `bb4` reads `_1` without initializing it first and +/// is therefore already UB. (The `_flag` assignments make that latter +/// continuation dynamically impossible, but this analysis does not need to +/// prove the correlation.) +/// +/// Live ranges which start in the middle of a block do not need this analysis: +/// such ranges always start at an initialization, so a `StorageLive` is +/// unconditionally required there. +/// +/// This analysis deliberately ignores the reconstructed `StorageDead` +/// boundaries. This can cause an initialization from a later allocation range +/// to propagate into an earlier range and result in an unnecessary +/// `StorageLive`, but cannot cause a required `StorageLive` to be omitted. +struct InitializedBeforeUse; + +impl<'tcx> Analysis<'tcx> for InitializedBeforeUse { + type Domain = DenseBitSet; + type Direction = Backward; + + const NAME: &'static str = "initialized-before-use"; + + fn bottom_value(&self, body: &Body<'tcx>) -> Self::Domain { + DenseBitSet::new_empty(body.local_decls.len()) + } + + fn initialize_start_block(&self, _body: &Body<'tcx>, _state: &mut Self::Domain) {} + + fn apply_primary_statement_effect( + &self, + state: &mut Self::Domain, + statement: &Statement<'tcx>, + location: Location, + ) { + // In backward order, process writes before reads. + VisitAllocatedLocalsWith(|local, _| state.gen_(local)).visit_statement(statement, location); + VisitPlacesWith(|place: Place<'tcx>, context| { + if matches!(DefUse::for_place(place, context), DefUse::Use) { + state.kill(place.local); + } + }) + .visit_statement(statement, location); + } + + fn apply_primary_terminator_effect( + &self, + state: &mut Self::Domain, + terminator: &Terminator<'tcx>, + location: Location, + ) { + // In backward order, process writes before reads. + VisitAllocatedLocalsWith(|local, _| state.gen_(local)) + .visit_terminator(terminator, location); + VisitPlacesWith(|place: Place<'tcx>, context| { + if matches!(DefUse::for_place(place, context), DefUse::Use) { + state.kill(place.local); + } + }) + .visit_terminator(terminator, location); + } +} + +impl InitializedBeforeUse { + /// Computes the analysis state at the start of each block. + fn compute<'tcx>( + tcx: TyCtxt<'tcx>, + body: &Body<'tcx>, + ) -> IndexVec> { + let results = + Self.iterate_to_fixpoint(tcx, body, Some("MoveElimination.initialized-before-use")); + let mut block_start = IndexVec::from_elem_n( + DenseBitSet::new_empty(body.local_decls.len()), + body.basic_blocks.len(), + ); + + struct BlockStartVisitor<'a> { + block_start: &'a mut IndexVec>, + } + + impl<'tcx> ResultsVisitor<'tcx, InitializedBeforeUse> for BlockStartVisitor<'_> { + fn visit_block_exit(&mut self, state: &DenseBitSet, block: BasicBlock) { + self.block_start[block].clone_from(state); + } + } + + visit_results( + body, + rustc_middle::mir::traversal::reachable(body).map(|(block, _)| block), + &results, + &mut BlockStartVisitor { block_start: &mut block_start }, + ); + block_start + } +} + +/// Helper function to split a critical edge if necessary. +fn get_or_split_edge<'tcx>( + patcher: &mut MirPatch<'tcx>, + body: &Body<'tcx>, + split_edges: &mut FxHashMap<(BasicBlock, BasicBlock), BasicBlock>, + pred: BasicBlock, + succ: BasicBlock, +) -> BasicBlock { + if let Some(&split_bb) = split_edges.get(&(pred, succ)) { + return split_bb; + } + let source_info = body.basic_blocks[pred].terminator().source_info; + let split_bb = patcher.new_block(BasicBlockData::new( + Some(Terminator { source_info, kind: TerminatorKind::goto(succ) }), + body.basic_blocks[succ].is_cleanup, + )); + patcher.mutate_terminator(body, pred, |kind| { + kind.successors_mut(|t| { + if *t == succ { + *t = split_bb; + } + }); + }); + split_edges.insert((pred, succ), split_bb); + split_bb +} + +/// Live range boundary within a block which indicates where a storage statement +/// should be inserted. +enum RangeBoundary { + /// The range boundary is at the given location, and storage statements + /// should be inserted before/after it. + Loc(Location), + + /// The range is live across a block edge, and storage statements should be + /// inserted in predecessor/successor blocks. + Edge(BasicBlock), +} + +/// Splits a live interval at block boundaries, returning the location at which +/// storage statements need to be inserted at the start and end of the range. +/// +/// This is needed because `SparseIntervalMatrix` coalesces numerically adjacent +/// ranges, which can span multiple basic blocks. +fn split_range_by_block( + points: &DenseLocationMap, + range: RangeInclusive, +) -> impl Iterator { + let start = points.to_location(range.start.point()); + let end = points.to_location(range.last.point()); + debug_assert!(start.block <= end.block); + + (start.block.index()..=end.block.index()).map(move |block| { + let block = BasicBlock::from_usize(block); + + // If the live range starts at the first statement's `Early` point, + // the value came from a predecessor block. A write from the first + // statement would happen at the `Late` point instead. + let start = if block != start.block + || (start.statement_index == 0 && range.start.effect() == SplitPointEffect::Early) + { + RangeBoundary::Edge(block) + } else { + RangeBoundary::Loc(start) + }; + + // We need to insert `StorageDead` after the last statement that + // uses a local. If this is a terminator then we need to instead + // insert it at the start of every successor block where the local + // is dead on entry. + let end = if block == end.block && range.last.point() != points.terminator(block) { + RangeBoundary::Loc(end) + } else { + RangeBoundary::Edge(block) + }; + (start, end) + }) +} + +/// Re-constructs storage statements for all locals. +fn reconstruct_storage<'tcx>( + tcx: TyCtxt<'tcx>, + body: &mut Body<'tcx>, + points: &DenseLocationMap, + liveness_matrix: &SparseIntervalMatrix, +) { + let initialized_before_use = InitializedBeforeUse::compute(tcx, body); + let mut patcher = MirPatch::new(body); + let mut split_edges: FxHashMap<(BasicBlock, BasicBlock), BasicBlock> = Default::default(); + let mut storage_lives = Vec::new(); + + for local in body.local_decls.indices() { + // Arguments and return values don't use storage statements. + match body.local_kind(local) { + LocalKind::Arg | LocalKind::ReturnPointer => continue, + LocalKind::Temp => {} + } + + // Ignore dead locals. + let Some(row) = liveness_matrix.row(local) else { continue }; + if row.is_empty() { + continue; + } + + let mut emit_storage_live_in_preds = + |body: &mut Body<'tcx>, + patcher: &mut MirPatch<'tcx>, + storage_lives: &mut Vec<(Location, Local)>, + local: Local, + block: BasicBlock| { + if !initialized_before_use[block].contains(local) { + // No continuation initializes the local before reading it, + // so allocating storage cannot make any such read valid. + return; + } + + for &pred in &body.basic_blocks.predecessors()[block].clone() { + // If the local is live at any point in the predecessor's + // terminator then no StorageLive is needed. + let term = points.terminator(pred); + let term_early = SplitPointIndex::new(term, SplitPointEffect::Early); + let term_late = SplitPointIndex::new(term, SplitPointEffect::Late); + if !row.intersects_range(term_early..=term_late) { + // The local must be live on at least one predecessor, + // so if this is the only one then there is nothing to + // do. + debug_assert!(body.basic_blocks.predecessors()[block].len() > 1); + + // If the predecessor block has multiple successors then + // we need to split the critical edge before inserting + // StorageLive, otherwise the local would end up live on + // paths where it is supposed to be dead. + let loc = if body.basic_blocks[pred].terminator().successors().count() > 1 { + get_or_split_edge(patcher, body, &mut split_edges, pred, block) + .start_location() + } else { + body.terminator_loc(pred) + }; + storage_lives.push((loc, local)); + } + } + }; + let emit_storage_dead_in_succs = + |body: &mut Body<'tcx>, + patcher: &mut MirPatch<'tcx>, + local: Local, + block: BasicBlock| { + for succ in body.basic_blocks[block].terminator().successors() { + if !row.contains(SplitPointIndex::new( + points.entry_point(succ), + SplitPointEffect::Early, + )) { + // We don't care about critical edges here: if the local + // is already dead in the successor then it doesn't + // matter if we emit a redundant StorageDead. + + patcher.add_statement( + succ.start_location(), + StatementKind::StorageDead(local), + ); + } + } + }; + + // Iterate through the live range of the local and insert `StorageLive` + // and `StorageDead` at the points where it transitions from dead to + // live and vice versa. + for (start, end) in + row.iter_intervals().flat_map(|range| split_range_by_block(points, range)) + { + match start { + // Live-in from predecessor blocks: emit StorageLive in + // predecessors in which it wasn't previously live. + RangeBoundary::Edge(block) => { + emit_storage_live_in_preds( + body, + &mut patcher, + &mut storage_lives, + local, + block, + ); + } + // Otherwise just add `StorageLive` before the statement that + // starts the live range. + RangeBoundary::Loc(location) => storage_lives.push((location, local)), + } + + match end { + // If the range includes the terminator then emit StorageDead in + // successors which the local is dead on entry. + RangeBoundary::Edge(block) => { + emit_storage_dead_in_succs(body, &mut patcher, local, block); + } + // Otherwise just add `StorageDead` after the statement at which + // the live range ends. + RangeBoundary::Loc(location) => { + patcher.add_statement( + location.successor_within_block(), + StatementKind::StorageDead(local), + ); + } + } + } + } + + // Queue all `StorageLive` statements after `StorageDead` so that, when + // both are inserted at the same location, `StorageDead` always precedes + // `StorageLive` to avoid false overlaps. + for (loc, local) in storage_lives { + patcher.add_statement(loc, StatementKind::StorageLive(local)); + } + + patcher.apply(body); +} + //////////////////////////////////////////////////////////////////////////////// // Aliasing assignment fixup // diff --git a/compiler/rustc_mir_transform/src/patch.rs b/compiler/rustc_mir_transform/src/patch.rs index da1077707baff..739fa5e37ab13 100644 --- a/compiler/rustc_mir_transform/src/patch.rs +++ b/compiler/rustc_mir_transform/src/patch.rs @@ -210,6 +210,21 @@ impl<'tcx> MirPatch<'tcx> { self.term_patch_map.insert(block, new); } + /// Modifies the terminator of a block, reading the existing patch if one exists or + /// cloning from the body otherwise. + pub(crate) fn mutate_terminator( + &mut self, + body: &Body<'tcx>, + bb: BasicBlock, + f: impl FnOnce(&mut TerminatorKind<'tcx>), + ) { + let kind = self + .term_patch_map + .entry(bb) + .or_insert_with(|| body.basic_blocks[bb].terminator().kind.clone()); + f(kind); + } + /// Mark given statement to be replaced by a `Nop`. /// /// This method only works on statements from the initial body, and cannot be used to remove diff --git a/tests/mir-opt/move-elimination/alias_fixup.aggregate_indirect_source_alias.MoveElimination.diff b/tests/mir-opt/move-elimination/alias_fixup.aggregate_indirect_source_alias.MoveElimination.diff index 1b4e6dbba1825..64d0fe11bfa9f 100644 --- a/tests/mir-opt/move-elimination/alias_fixup.aggregate_indirect_source_alias.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/alias_fixup.aggregate_indirect_source_alias.MoveElimination.diff @@ -14,12 +14,14 @@ - _3 = (copy (*_2), move _1); - _0 = copy _3; + (_0.1: u8) = const 1_u8; ++ StorageLive(_2); + _2 = &raw const (_0.1: u8); + StorageLive(_4); + _4 = no_retag copy (*_2); + (_0.0: u8) = no_retag move _4; + nop; + StorageDead(_4); ++ StorageDead(_2); + nop; return; } diff --git a/tests/mir-opt/move-elimination/alias_fixup.aggregate_swap.MoveElimination.diff b/tests/mir-opt/move-elimination/alias_fixup.aggregate_swap.MoveElimination.diff index d958b6d346d35..481d3ef60feb8 100644 --- a/tests/mir-opt/move-elimination/alias_fixup.aggregate_swap.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/alias_fixup.aggregate_swap.MoveElimination.diff @@ -41,15 +41,6 @@ - _7 = copy (_3.1: u8); - StorageLive(_8); - _8 = copy _7; -- StorageLive(_9); -- _9 = copy _6; -- _3 = (move _8, move _9); -- StorageDead(_9); -- StorageDead(_8); -- _0 = copy _3; -- StorageDead(_7); -- StorageDead(_6); -- StorageDead(_3); + nop; + nop; + nop; @@ -59,6 +50,9 @@ + nop; + nop; + nop; + StorageLive(_9); +- _9 = copy _6; +- _3 = (move _8, move _9); + _9 = copy (_0.0: u8); + nop; + nop; @@ -72,6 +66,12 @@ + (_0.1: u8) = no_retag move _9; + nop; + StorageDead(_10); + StorageDead(_9); +- StorageDead(_8); +- _0 = copy _3; +- StorageDead(_7); +- StorageDead(_6); +- StorageDead(_3); + nop; + nop; + nop; diff --git a/tests/mir-opt/move-elimination/alias_fixup.array_swap.MoveElimination.diff b/tests/mir-opt/move-elimination/alias_fixup.array_swap.MoveElimination.diff index f577fe6e46955..571ebeaa3de79 100644 --- a/tests/mir-opt/move-elimination/alias_fixup.array_swap.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/alias_fixup.array_swap.MoveElimination.diff @@ -23,12 +23,10 @@ - _3 = copy _1[1 of 2]; - StorageLive(_4); - _4 = copy _3; -- StorageLive(_5); ++ nop; + StorageLive(_5); - _5 = copy _2; - _1 = [move _4, move _5]; -- StorageDead(_5); -- StorageDead(_4); -+ nop; + _5 = copy _1[0 of 2]; + nop; + nop; @@ -42,6 +40,8 @@ + _1[1 of 2] = no_retag move _5; + nop; + StorageDead(_6); + StorageDead(_5); +- StorageDead(_4); + nop; + nop; _0 = copy _1; diff --git a/tests/mir-opt/move-elimination/alias_fixup.enum_alias.MoveElimination.diff b/tests/mir-opt/move-elimination/alias_fixup.enum_alias.MoveElimination.diff index 0997f614ac55e..4f84e289723dd 100644 --- a/tests/mir-opt/move-elimination/alias_fixup.enum_alias.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/alias_fixup.enum_alias.MoveElimination.diff @@ -60,15 +60,18 @@ bb2: { - _8 = discriminant(_4); ++ StorageLive(_8); + _8 = discriminant(_0); switchInt(move _8) -> [0: bb4, 1: bb5, otherwise: bb3]; } bb3: { ++ StorageDead(_8); unreachable; } bb4: { ++ StorageDead(_8); _0 = PairEnum::Empty; goto -> bb6; } @@ -80,14 +83,11 @@ - _10 = copy ((_4 as Pair).1: u8); - StorageLive(_11); - _11 = copy _10; -- StorageLive(_12); ++ StorageDead(_8); ++ nop; + StorageLive(_12); - _12 = copy _9; - _0 = PairEnum::Pair(move _11, move _12); -- StorageDead(_12); -- StorageDead(_11); -- StorageDead(_10); -- StorageDead(_9); -+ nop; + _12 = copy ((_0 as Pair).0: u8); + nop; + nop; @@ -102,6 +102,10 @@ + discriminant(_0) = 1; + nop; + StorageDead(_13); + StorageDead(_12); +- StorageDead(_11); +- StorageDead(_10); +- StorageDead(_9); + nop; + nop; + nop; diff --git a/tests/mir-opt/move-elimination/alias_fixup.mixed_aggregate_aliasing.MoveElimination.diff b/tests/mir-opt/move-elimination/alias_fixup.mixed_aggregate_aliasing.MoveElimination.diff index 0b3f73be637a0..27f6c10549040 100644 --- a/tests/mir-opt/move-elimination/alias_fixup.mixed_aggregate_aliasing.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/alias_fixup.mixed_aggregate_aliasing.MoveElimination.diff @@ -46,7 +46,8 @@ } bb3: { -- StorageLive(_6); ++ nop; + StorageLive(_6); - _6 = copy (_3.1: u8); - StorageLive(_7); - _7 = copy (_3.0: u8); @@ -55,8 +56,6 @@ - _4 = Triple(move _6, move _7, move _8); - StorageDead(_8); - StorageDead(_7); -- StorageDead(_6); -+ nop; + _6 = copy (_0.1: u8); + nop; + nop; @@ -69,6 +68,7 @@ + (_0.2: u8) = no_retag move _2; + nop; + StorageDead(_9); + StorageDead(_6); + nop; + nop; + nop; diff --git a/tests/mir-opt/move-elimination/alias_fixup.simd_alias.MoveElimination.diff b/tests/mir-opt/move-elimination/alias_fixup.simd_alias.MoveElimination.diff index 7c2b4ebfb7fca..12382bbaa4475 100644 --- a/tests/mir-opt/move-elimination/alias_fixup.simd_alias.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/alias_fixup.simd_alias.MoveElimination.diff @@ -19,19 +19,19 @@ bb0: { - StorageLive(_2); - StorageLive(_3); -- StorageLive(_4); + nop; + nop; + nop; + StorageLive(_4); _4 = [const 0_u32; 4]; - _3 = Vector(move _4); -- StorageDead(_4); ++ (_0.0: Vector) = Vector(move _4); + StorageDead(_4); - _2 = VectorUnion { vector: move _3 }; - StorageDead(_3); - StorageLive(_5); - _5 = copy _1; - switchInt(move _5) -> [0: bb2, otherwise: bb1]; -+ (_0.0: Vector) = Vector(move _4); + nop; + nop; + nop; diff --git a/tests/mir-opt/move-elimination/alias_fixup.simple_partial_alias.MoveElimination.diff b/tests/mir-opt/move-elimination/alias_fixup.simple_partial_alias.MoveElimination.diff index e548e921f3142..af47eb7347d2a 100644 --- a/tests/mir-opt/move-elimination/alias_fixup.simple_partial_alias.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/alias_fixup.simple_partial_alias.MoveElimination.diff @@ -25,23 +25,23 @@ - StorageDead(_3); - StorageLive(_4); - _4 = copy (_2.0: [u8; 4]); -- StorageLive(_5); -- _5 = copy _4; -- (_2.1: [u8; 4]) = move _5; -- StorageDead(_5); -- _0 = move _2; -- StorageDead(_4); -- StorageDead(_2); + nop; + nop; + nop; + _0 = U { a: move _1 }; + nop; + nop; + StorageLive(_5); +- _5 = copy _4; +- (_2.1: [u8; 4]) = move _5; + _5 = copy (_0.0: [u8; 4]); + nop; + nop; + (_0.1: [u8; 4]) = move _5; + StorageDead(_5); +- _0 = move _2; +- StorageDead(_4); +- StorageDead(_2); + nop; + nop; + nop; diff --git a/tests/mir-opt/move-elimination/basic.nrvo_borrowed.MoveElimination.diff b/tests/mir-opt/move-elimination/basic.nrvo_borrowed.MoveElimination.diff index 6762e06029772..8a07af2edceaf 100644 --- a/tests/mir-opt/move-elimination/basic.nrvo_borrowed.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/basic.nrvo_borrowed.MoveElimination.diff @@ -17,24 +17,28 @@ - _1 = [const 1_u8; 8]; - StorageLive(_2); - StorageLive(_3); -- StorageLive(_4); -- _4 = &mut _1; + nop; + _0 = [const 1_u8; 8]; + nop; + nop; + nop; + StorageLive(_4); +- _4 = &mut _1; + _4 = &mut _0; ++ StorageLive(_3); _3 = &mut (*_4); ++ StorageDead(_4); ++ StorageLive(_2); _2 = init(move _3) -> [return: bb1, unwind unreachable]; } bb1: { - StorageDead(_3); - StorageDead(_4); -- StorageDead(_2); + StorageDead(_2); - _0 = move _1; - StorageDead(_1); ++ StorageDead(_3); + nop; + nop; + nop; diff --git a/tests/mir-opt/move-elimination/dse.dse_guard.MoveElimination.diff b/tests/mir-opt/move-elimination/dse.dse_guard.MoveElimination.diff index 2f3019364f343..895dab2802597 100644 --- a/tests/mir-opt/move-elimination/dse.dse_guard.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/dse.dse_guard.MoveElimination.diff @@ -22,12 +22,12 @@ bb0: { - StorageLive(_1); -- StorageLive(_2); -- StorageLive(_3); -- _3 = make_fields(const 0_u8) -> [return: bb1, unwind unreachable]; + nop; + nop; + nop; + StorageLive(_2); +- StorageLive(_3); +- _3 = make_fields(const 0_u8) -> [return: bb1, unwind unreachable]; + _2 = make_fields(const 0_u8) -> [return: bb1, unwind unreachable]; } @@ -39,6 +39,7 @@ + nop; + nop; + nop; ++ StorageLive(_7); + _7 = make_fields(const 1_u8) -> [return: bb2, unwind unreachable]; } @@ -46,45 +47,49 @@ - _1 = move _4; - StorageDead(_4); - StorageLive(_5); -- StorageLive(_6); -- _6 = &raw const _1; + nop; + nop; + nop; + nop; + StorageLive(_6); +- _6 = &raw const _1; + _6 = &raw const _7; ++ StorageLive(_5); _5 = observe(move _6) -> [return: bb3, unwind unreachable]; } bb3: { - StorageDead(_6); -- StorageDead(_5); + StorageDead(_5); - StorageLive(_7); - _7 = move _1; ++ StorageDead(_6); + nop; + nop; + nop; + nop; _2 = move _7; -- StorageDead(_7); + StorageDead(_7); - StorageLive(_8); -- StorageLive(_9); + nop; + nop; + nop; + StorageLive(_9); _9 = &raw const _2; ++ StorageLive(_8); _8 = observe(move _9) -> [return: bb4, unwind unreachable]; } bb4: { - StorageDead(_9); -- StorageDead(_8); + StorageDead(_8); ++ StorageDead(_9); + nop; + nop; _0 = const (); -- StorageDead(_2); -- StorageDead(_1); + nop; + StorageDead(_2); +- StorageDead(_1); + nop; return; } diff --git a/tests/mir-opt/move-elimination/dse.rs b/tests/mir-opt/move-elimination/dse.rs index 77685fb533fdd..268b54fa96ae6 100644 --- a/tests/mir-opt/move-elimination/dse.rs +++ b/tests/mir-opt/move-elimination/dse.rs @@ -19,7 +19,9 @@ pub fn dse_guard() { // CHECK-LABEL: fn dse_guard( // CHECK: debug a => [[a:_.*]]; // CHECK: debug b => [[b:_.*]]; + // CHECK: StorageLive([[b]]); // CHECK: [[b]] = make_fields(const 0_u8) + // CHECK: StorageLive([[a]]); // CHECK: [[a]] = make_fields(const 1_u8) // CHECK: observe(move // CHECK: [[b]] = move [[a]] diff --git a/tests/mir-opt/move-elimination/exclusions.constant_index_projected.MoveElimination.diff b/tests/mir-opt/move-elimination/exclusions.constant_index_projected.MoveElimination.diff index 33b96a7981738..aff9f122c383d 100644 --- a/tests/mir-opt/move-elimination/exclusions.constant_index_projected.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/exclusions.constant_index_projected.MoveElimination.diff @@ -15,21 +15,21 @@ bb0: { - StorageLive(_2); - _2 = copy _1[0 of 2]; -- StorageLive(_3); -- StorageLive(_4); -- _4 = copy _2; -- _3 = std::hint::black_box::<[u8; 4]>(move _4) -> [return: bb1, unwind unreachable]; + nop; + nop; + nop; + nop; + nop; + StorageLive(_3); +- StorageLive(_4); +- _4 = copy _2; +- _3 = std::hint::black_box::<[u8; 4]>(move _4) -> [return: bb1, unwind unreachable]; + _3 = std::hint::black_box::<[u8; 4]>(move _1[0 of 2]) -> [return: bb1, unwind unreachable]; } bb1: { - StorageDead(_4); -- StorageDead(_3); + StorageDead(_3); + nop; + nop; _0 = const (); diff --git a/tests/mir-opt/move-elimination/exclusions.index_local_not_projected.MoveElimination.diff b/tests/mir-opt/move-elimination/exclusions.index_local_not_projected.MoveElimination.diff index 4cdc1d24ee427..6aa7c42a2ba08 100644 --- a/tests/mir-opt/move-elimination/exclusions.index_local_not_projected.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/exclusions.index_local_not_projected.MoveElimination.diff @@ -7,9 +7,13 @@ let mut _3: usize; bb0: { ++ StorageLive(_2); _2 = const 2_usize; ++ StorageLive(_3); _3 = copy _1[_2]; ++ StorageDead(_3); _0 = [copy _2]; ++ StorageDead(_2); return; } } diff --git a/tests/mir-opt/move-elimination/exclusions.overlapping_lifetimes.MoveElimination.diff b/tests/mir-opt/move-elimination/exclusions.overlapping_lifetimes.MoveElimination.diff index ddf8630091e4b..51db7a9e85374 100644 --- a/tests/mir-opt/move-elimination/exclusions.overlapping_lifetimes.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/exclusions.overlapping_lifetimes.MoveElimination.diff @@ -28,28 +28,31 @@ - StorageLive(_2); - _2 = make_fields(const 0_u8) -> [return: bb1, unwind unreachable]; + nop; ++ StorageLive(_10); + _10 = make_fields(const 0_u8) -> [return: bb1, unwind unreachable]; } bb1: { - StorageLive(_3); - StorageLive(_4); -- StorageLive(_5); -- _5 = &raw const _2; + nop; + nop; + nop; + StorageLive(_5); +- _5 = &raw const _2; + _5 = &raw const _10; ++ StorageLive(_4); _4 = observe(move _5) -> [return: bb2, unwind unreachable]; } bb2: { - StorageDead(_5); -- StorageDead(_4); + StorageDead(_4); - StorageLive(_6); - StorageLive(_7); - _7 = copy _1; - switchInt(move _7) -> [0: bb5, otherwise: bb3]; ++ StorageDead(_5); + nop; + nop; + nop; @@ -77,8 +80,11 @@ + nop; + nop; + _0 = move _10; ++ StorageDead(_10); + nop; ++ StorageLive(_6); _6 = const (); ++ StorageDead(_6); goto -> bb6; } @@ -86,12 +92,14 @@ - StorageLive(_10); - _10 = move _2; - _3 = move _10; -- StorageDead(_10); + nop; + nop; + _0 = move _10; + StorageDead(_10); + nop; ++ StorageLive(_6); _6 = const (); ++ StorageDead(_6); goto -> bb6; } @@ -99,22 +107,24 @@ - StorageDead(_7); - StorageDead(_6); - StorageLive(_11); -- StorageLive(_12); -- _12 = &raw const _3; + nop; + nop; + nop; + nop; + StorageLive(_12); +- _12 = &raw const _3; + _12 = &raw const _0; ++ StorageLive(_11); _11 = observe(move _12) -> [return: bb7, unwind unreachable]; } bb7: { - StorageDead(_12); -- StorageDead(_11); + StorageDead(_11); - _0 = move _3; - StorageDead(_3); - StorageDead(_2); ++ StorageDead(_12); + nop; + nop; + nop; diff --git a/tests/mir-opt/move-elimination/exclusions.packed_fields_not_projected.MoveElimination.diff b/tests/mir-opt/move-elimination/exclusions.packed_fields_not_projected.MoveElimination.diff index 6c0bb304d3171..af6d2b34a0439 100644 --- a/tests/mir-opt/move-elimination/exclusions.packed_fields_not_projected.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/exclusions.packed_fields_not_projected.MoveElimination.diff @@ -21,13 +21,13 @@ - _1 = [const 1_u8; 8]; - StorageLive(_2); - _2 = [const 2_u8; 8]; -- StorageLive(_3); -- _3 = copy _1; -- StorageLive(_4); -- _4 = copy _2; + nop; + StorageLive(_3); +- _3 = copy _1; + _3 = [const 1_u8; 8]; + nop; + StorageLive(_4); +- _4 = copy _2; + _4 = [const 2_u8; 8]; + nop; + nop; @@ -35,9 +35,10 @@ + nop; _0 = Packed { a: move _3, b: move _4 }; - StorageDead(_4); -- StorageDead(_3); + StorageDead(_3); - StorageDead(_2); - StorageDead(_1); ++ StorageDead(_4); + nop; + nop; + nop; diff --git a/tests/mir-opt/move-elimination/exclusions.rust_call_tuple_not_projected.MoveElimination.diff b/tests/mir-opt/move-elimination/exclusions.rust_call_tuple_not_projected.MoveElimination.diff index bbde5a905a9e7..fcaf35ddeb8b0 100644 --- a/tests/mir-opt/move-elimination/exclusions.rust_call_tuple_not_projected.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/exclusions.rust_call_tuple_not_projected.MoveElimination.diff @@ -29,13 +29,13 @@ - StorageLive(_5); - _5 = move _1; - StorageLive(_6); -- StorageLive(_7); -- _7 = copy _2; -- StorageLive(_8); -- _8 = copy _3; + nop; + StorageLive(_7); +- _7 = copy _2; + _7 = [const 1_u8; 8]; + nop; + StorageLive(_8); +- _8 = copy _3; + _8 = [const 2_u8; 8]; + nop; + nop; @@ -45,8 +45,12 @@ + nop; + nop; + nop; ++ StorageLive(_6); _6 = (move _7, move _8); - _4 = >::call_once(move _5, move _6) -> [return: bb1, unwind unreachable]; ++ StorageDead(_7); ++ StorageDead(_8); ++ StorageLive(_4); + _4 = >::call_once(move _1, move _6) -> [return: bb1, unwind unreachable]; } @@ -55,7 +59,8 @@ - StorageDead(_7); - StorageDead(_6); - StorageDead(_5); -- StorageDead(_4); + StorageDead(_4); ++ StorageDead(_6); + nop; + nop; + nop; diff --git a/tests/mir-opt/move-elimination/exclusions.simd_field_not_projected.MoveElimination.diff b/tests/mir-opt/move-elimination/exclusions.simd_field_not_projected.MoveElimination.diff index 8d63e07039695..4844207200f34 100644 --- a/tests/mir-opt/move-elimination/exclusions.simd_field_not_projected.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/exclusions.simd_field_not_projected.MoveElimination.diff @@ -13,14 +13,14 @@ bb0: { - StorageLive(_1); - _1 = [const 1_u32, const 2_u32, const 3_u32, const 4_u32]; -- StorageLive(_2); -- _2 = copy _1; + nop; + StorageLive(_2); +- _2 = copy _1; + _2 = [const 1_u32, const 2_u32, const 3_u32, const 4_u32]; + nop; + nop; _0 = U32x4(move _2); -- StorageDead(_2); + StorageDead(_2); - StorageDead(_1); + nop; + nop; diff --git a/tests/mir-opt/move-elimination/exclusions.subslice_not_projected.MoveElimination.diff b/tests/mir-opt/move-elimination/exclusions.subslice_not_projected.MoveElimination.diff index 85b38460d277a..1d3c3b27e81e2 100644 --- a/tests/mir-opt/move-elimination/exclusions.subslice_not_projected.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/exclusions.subslice_not_projected.MoveElimination.diff @@ -16,19 +16,21 @@ - StorageLive(_2); - _2 = copy _1[1..3]; - StorageLive(_3); -- StorageLive(_4); -- _4 = copy _2; + nop; + StorageLive(_4); +- _4 = copy _2; + _4 = copy _1[1..3]; + nop; + nop; + nop; ++ StorageLive(_3); _3 = std::hint::black_box::<[u8; 2]>(move _4) -> [return: bb1, unwind unreachable]; } bb1: { - StorageDead(_4); -- StorageDead(_3); + StorageDead(_3); ++ StorageDead(_4); + nop; + nop; _0 = const (); diff --git a/tests/mir-opt/move-elimination/storage.address_observed_storage_dead_at_end.MoveElimination.diff b/tests/mir-opt/move-elimination/storage.address_observed_storage_dead_at_end.MoveElimination.diff new file mode 100644 index 0000000000000..dfc680dc01ff2 --- /dev/null +++ b/tests/mir-opt/move-elimination/storage.address_observed_storage_dead_at_end.MoveElimination.diff @@ -0,0 +1,61 @@ +- // MIR for `address_observed_storage_dead_at_end` before MoveElimination ++ // MIR for `address_observed_storage_dead_at_end` after MoveElimination + + fn address_observed_storage_dead_at_end(_1: bool) -> () { + debug flag => _1; + let mut _0: (); + let _2: u32; + let mut _3: bool; + let _4: *const u32; + let mut _5: *const u32; + scope 1 { + debug x => _2; + } + + bb0: { +- StorageLive(_2); +- StorageLive(_3); +- _3 = copy _1; +- switchInt(move _3) -> [0: bb3, otherwise: bb1]; ++ nop; ++ nop; ++ nop; ++ switchInt(move _1) -> [0: bb3, otherwise: bb1]; + } + + bb1: { ++ StorageLive(_2); + _2 = const 1_u32; +- StorageLive(_4); ++ nop; ++ nop; + StorageLive(_5); + _5 = &raw const _2; ++ StorageLive(_4); + _4 = opaque::<*const u32>(move _5) -> [return: bb2, unwind unreachable]; + } + + bb2: { +- StorageDead(_5); + StorageDead(_4); ++ StorageDead(_5); ++ nop; ++ nop; + _0 = const (); + goto -> bb4; + } + + bb3: { + _0 = const (); + goto -> bb4; + } + + bb4: { +- StorageDead(_3); ++ nop; ++ nop; + StorageDead(_2); + return; + } + } + diff --git a/tests/mir-opt/move-elimination/storage.borrowed_not_shortened_to_last_direct_use.MoveElimination.diff b/tests/mir-opt/move-elimination/storage.borrowed_not_shortened_to_last_direct_use.MoveElimination.diff new file mode 100644 index 0000000000000..c28ca81eb5b9c --- /dev/null +++ b/tests/mir-opt/move-elimination/storage.borrowed_not_shortened_to_last_direct_use.MoveElimination.diff @@ -0,0 +1,87 @@ +- // MIR for `borrowed_not_shortened_to_last_direct_use` before MoveElimination ++ // MIR for `borrowed_not_shortened_to_last_direct_use` after MoveElimination + + fn borrowed_not_shortened_to_last_direct_use(_1: u32) -> () { + debug x => _1; + let mut _0: (); + let _2: u32; + let mut _3: u32; + let _6: u32; + let mut _7: u32; + let mut _8: u32; + let mut _9: u32; + scope 1 { + debug a => _2; + let _4: &u32; + scope 2 { + debug r => _4; + let _5: u32; + scope 3 { +- debug out => _5; ++ debug out => _9; + } + } + } + + bb0: { ++ nop; ++ nop; ++ nop; + StorageLive(_2); +- StorageLive(_3); +- _3 = copy _1; +- _2 = opaque::(move _3) -> [return: bb1, unwind unreachable]; ++ _2 = opaque::(move _1) -> [return: bb1, unwind unreachable]; + } + + bb1: { +- StorageDead(_3); ++ nop; ++ nop; + StorageLive(_4); + _4 = &_2; +- StorageLive(_5); +- _5 = copy _2; +- StorageLive(_6); +- StorageLive(_7); ++ nop; ++ StorageLive(_9); ++ _9 = copy _2; ++ nop; ++ nop; ++ nop; + StorageLive(_8); + _8 = copy (*_4); +- StorageLive(_9); +- _9 = copy _5; ++ StorageDead(_4); ++ nop; ++ nop; ++ StorageLive(_7); + _7 = Add(move _8, move _9); +- StorageDead(_9); + StorageDead(_8); ++ StorageDead(_9); ++ nop; ++ nop; ++ StorageLive(_6); + _6 = opaque::(move _7) -> [return: bb2, unwind unreachable]; + } + + bb2: { +- StorageDead(_7); + StorageDead(_6); ++ StorageDead(_7); ++ nop; ++ nop; + _0 = const (); +- StorageDead(_5); +- StorageDead(_4); ++ nop; ++ nop; ++ nop; + StorageDead(_2); + return; + } + } + diff --git a/tests/mir-opt/move-elimination/storage.critical_edge_split_for_storage_live.MoveElimination.diff b/tests/mir-opt/move-elimination/storage.critical_edge_split_for_storage_live.MoveElimination.diff new file mode 100644 index 0000000000000..20a5abf62e439 --- /dev/null +++ b/tests/mir-opt/move-elimination/storage.critical_edge_split_for_storage_live.MoveElimination.diff @@ -0,0 +1,35 @@ +- // MIR for `critical_edge_split_for_storage_live` before MoveElimination ++ // MIR for `critical_edge_split_for_storage_live` after MoveElimination + + fn critical_edge_split_for_storage_live(_1: bool) -> () { + debug x => _2; + let mut _0: (); + let mut _2: u32; + let mut _3: *const u32; + + bb0: { +- switchInt(copy _1) -> [1: bb1, otherwise: bb2]; ++ switchInt(copy _1) -> [1: bb1, otherwise: bb3]; + } + + bb1: { ++ StorageLive(_2); + _2 = const 1_u32; ++ StorageLive(_3); + _3 = &raw const _2; + _3 = opaque::<*const u32>(copy _3) -> [return: bb2, unwind unreachable]; + } + + bb2: { ++ StorageDead(_3); + _2 = const 2_u32; ++ StorageDead(_2); + return; ++ } ++ ++ bb3: { ++ StorageLive(_2); ++ goto -> bb2; + } + } + diff --git a/tests/mir-opt/move-elimination/storage.rs b/tests/mir-opt/move-elimination/storage.rs new file mode 100644 index 0000000000000..c699e4591c22c --- /dev/null +++ b/tests/mir-opt/move-elimination/storage.rs @@ -0,0 +1,236 @@ +//@ test-mir-pass: MoveElimination +//@ compile-flags: -Cpanic=abort -Zlint-mir=false + +#![feature(custom_mir, core_intrinsics)] + +use std::intrinsics::mir::*; + +fn opaque(x: T) -> T { + x +} + +// EMIT_MIR storage.shorten_non_borrowed.MoveElimination.diff +pub fn shorten_non_borrowed(x: u32) { + // This checks that reconstruction can shorten a non-borrowed local's + // storage to its last use instead of keeping lexical storage markers. + // CHECK-LABEL: fn shorten_non_borrowed( + // CHECK: debug a => [[short:_.*]]; + // CHECK: debug b => [[short]]; + // CHECK: StorageLive([[short]]); + // CHECK: [[short]] = opaque::( + // CHECK: opaque::(move [[short]]) -> [return: [[short_ret:bb.*]], + // CHECK: [[short_ret]]: { + // CHECK: StorageDead([[short]]); + // CHECK: opaque::( + let a = opaque(x); + let b = a; + opaque(b); + opaque(x); +} + +// EMIT_MIR storage.borrowed_not_shortened_to_last_direct_use.MoveElimination.diff +pub fn borrowed_not_shortened_to_last_direct_use(x: u32) { + // This checks that a borrowed local is not shortened merely to its last + // direct use; the borrow keeps its storage live while the reference exists. + // CHECK-LABEL: fn borrowed_not_shortened_to_last_direct_use( + // CHECK: debug a => [[borrowed:_.*]]; + // CHECK: debug r => [[borrow_ref:_.*]]; + // CHECK: debug out => [[out:_.*]]; + // CHECK: StorageLive([[borrowed]]); + // CHECK: [[borrowed]] = opaque::(move _1) + // CHECK: [[borrow_ref]] = &[[borrowed]]; + // CHECK: [[out]] = copy [[borrowed]]; + // CHECK: copy (*[[borrow_ref]]); + // CHECK: StorageDead([[borrowed]]); + let a = opaque(x); + let r = &a; + let out = a; + opaque(*r + out); +} + +// EMIT_MIR storage.storage_live_moved_to_branch.MoveElimination.diff +pub fn storage_live_moved_to_branch(flag: bool) { + // This checks storage reconstruction can shrink a local declared before a + // branch so its storage is live only on the arm where it is initialized. + // CHECK-LABEL: fn storage_live_moved_to_branch( + // CHECK: debug x => [[branch_tmp:_.*]]; + // CHECK: switchInt(move _1) -> [0: bb3, otherwise: bb1]; + // CHECK: bb1: { + // CHECK: StorageLive([[branch_tmp]]); + // CHECK: [[branch_tmp]] = const 1_u32; + // CHECK: opaque::(move [[branch_tmp]]) -> [return: [[branch_ret:bb.*]], + // CHECK: [[branch_ret]]: { + // CHECK: StorageDead([[branch_tmp]]); + let x: u32; + if flag { + x = 1; + opaque(x); + } +} + +// EMIT_MIR storage.address_observed_storage_dead_at_end.MoveElimination.diff +pub fn address_observed_storage_dead_at_end(flag: bool) { + // This checks that an address-observed local declared before a branch still + // has StorageLive moved into the initialized arm without adding one to the + // uninitialized arm, but StorageDead remains at the end of the function + // instead of being shortened to the last direct use. + // CHECK-LABEL: fn address_observed_storage_dead_at_end( + // CHECK: debug x => [[addr_tmp:_.*]]; + // CHECK: switchInt(move _1) -> [0: [[skip:bb.*]], otherwise: [[init:bb.*]]]; + // CHECK: [[init]]: { + // CHECK: StorageLive([[addr_tmp]]); + // CHECK: [[addr_tmp]] = const 1_u32; + // CHECK: &raw const [[addr_tmp]]; + // CHECK: opaque::<*const u32> + // CHECK-NOT: StorageDead([[addr_tmp]]); + // CHECK: [[skip]]: { + // CHECK-NOT: StorageLive([[addr_tmp]]); + // CHECK: {{bb.*}}: { + // CHECK: StorageDead([[addr_tmp]]); + let x: u32; + if flag { + x = 1; + opaque(&raw const x); + } +} + +// EMIT_MIR storage.terminator_end_storage_dead_in_successor.MoveElimination.diff +pub fn terminator_end_storage_dead_in_successor(x: u32) -> u32 { + // This checks storage reconstruction when the last use of a local is as a + // call argument in a terminator. + // CHECK-LABEL: fn terminator_end_storage_dead_in_successor( + // CHECK: debug tmp => [[term_tmp:_.*]]; + // CHECK: StorageLive([[term_tmp]]); + // CHECK: [[term_tmp]] = opaque::(move _1) + // CHECK: opaque::(move [[term_tmp]]) -> [return: [[term_ret:bb.*]], + // CHECK: [[term_ret]]: { + // CHECK-NEXT: StorageDead([[term_tmp]]); + let tmp = opaque(x); + let out = opaque(tmp); + out +} + +// EMIT_MIR storage.storage_dead_before_return.MoveElimination.diff +#[custom_mir(dialect = "runtime", phase = "post-cleanup")] +pub fn storage_dead_before_return() -> *const u32 { + // This checks that a borrowed local without input storage statements has + // its reconstructed storage ended before returning. + // CHECK-LABEL: fn storage_dead_before_return( + // CHECK: debug x => [[x:_.*]]; + // CHECK: StorageLive([[x]]); + // CHECK: [[x]] = const 1_u32; + // CHECK: [[ret:_.*]] = &raw const [[x]]; + // CHECK: StorageDead([[x]]); + // CHECK-NEXT: return; + mir! { + let x: u32; + debug x => x; + + { + x = 1; + RET = &raw const x; + Return() + } + } +} + +// EMIT_MIR storage.critical_edge_split_for_storage_live.MoveElimination.diff +#[custom_mir(dialect = "runtime", phase = "post-cleanup")] +pub fn critical_edge_split_for_storage_live(flag: bool) { + // This checks storage reconstruction on a custom CFG where both branches + // reach a block which initializes a maybe-live local. The local is dead on + // the direct incoming edge, so inserting StorageLive requires splitting the + // critical edge from the entry switch. + // CHECK-LABEL: fn critical_edge_split_for_storage_live( + // CHECK: debug x => [[crit_tmp:_.*]]; + // CHECK: switchInt(copy _1) -> [1: [[init:bb.*]], otherwise: [[split:bb.*]]]; + // CHECK: [[init]]: { + // CHECK: StorageLive([[crit_tmp]]); + // CHECK: [[crit_tmp]] = const 1_u32; + // CHECK: &raw const [[crit_tmp]]; + // CHECK: opaque::<*const u32>{{.*}} -> [return: [[ret:bb.*]], + // CHECK: [[ret]]: { + // CHECK: [[crit_tmp]] = const 2_u32; + // CHECK: [[split]]: { + // CHECK-NEXT: StorageLive([[crit_tmp]]); + // CHECK-NEXT: goto -> [[ret]]; + mir! { + let x: u32; + let ptr: *const u32; + debug x => x; + + { + match flag { + true => init, + _ => ret, + } + } + + init = { + x = 1; + ptr = &raw const x; + Call(ptr = opaque::<*const u32>(ptr), ReturnTo(ret), UnwindUnreachable()) + } + + ret = { + // An initialization forces a StorageLive on both incoming branches, + // which in turn forces a critical edge split. + x = 2; + Return() + } + } +} + +// EMIT_MIR storage.storage_live_elided_on_join_fork.MoveElimination.diff +#[custom_mir(dialect = "runtime", phase = "post-cleanup")] +pub fn storage_live_elided_on_join_fork(flag: bool) { + // This checks a join-fork CFG where x is live in only one predecessor and + // one successor of the middle block. The flag correlation means the path + // which reads x is only reached after x has been initialized. On the direct + // edge to join, every continuation either reads x before initializing it or + // never accesses it, so no StorageLive or critical-edge split is needed. + // CHECK-LABEL: fn storage_live_elided_on_join_fork( + // CHECK: debug x => [[join_tmp:_.*]]; + // CHECK: switchInt(copy _1) -> [1: [[init:bb.*]], otherwise: [[join:bb.*]]]; + // CHECK: [[init]]: { + // CHECK: StorageLive([[join_tmp]]); + // CHECK: [[join_tmp]] = const 1_u32; + // CHECK: goto -> [[join]]; + // CHECK: [[join]]: { + // CHECK-NOT: StorageLive([[join_tmp]]); + // CHECK: switchInt(copy _1) -> [1: [[use_x:bb.*]], otherwise: [[done:bb.*]]]; + // CHECK: [[use_x]]: { + // CHECK: opaque::(move [[join_tmp]]) -> [return: [[done]], unwind unreachable]; + mir! { + let x: u32; + let out: u32; + debug x => x; + + { + match flag { + true => init, + _ => join, + } + } + + init = { + x = 1; + Goto(join) + } + + join = { + match flag { + true => use_x, + _ => done, + } + } + + use_x = { + Call(out = opaque::(Move(x)), ReturnTo(done), UnwindUnreachable()) + } + + done = { + Return() + } + } +} diff --git a/tests/mir-opt/move-elimination/storage.shorten_non_borrowed.MoveElimination.diff b/tests/mir-opt/move-elimination/storage.shorten_non_borrowed.MoveElimination.diff new file mode 100644 index 0000000000000..67a6b0ef87618 --- /dev/null +++ b/tests/mir-opt/move-elimination/storage.shorten_non_borrowed.MoveElimination.diff @@ -0,0 +1,79 @@ +- // MIR for `shorten_non_borrowed` before MoveElimination ++ // MIR for `shorten_non_borrowed` after MoveElimination + + fn shorten_non_borrowed(_1: u32) -> () { + debug x => _1; + let mut _0: (); + let _2: u32; + let mut _3: u32; + let _5: u32; + let mut _6: u32; + let _7: u32; + let mut _8: u32; + scope 1 { +- debug a => _2; ++ debug a => _6; + let _4: u32; + scope 2 { +- debug b => _4; ++ debug b => _6; + } + } + + bb0: { +- StorageLive(_2); ++ nop; ++ nop; + StorageLive(_3); + _3 = copy _1; +- _2 = opaque::(move _3) -> [return: bb1, unwind unreachable]; ++ StorageLive(_6); ++ _6 = opaque::(move _3) -> [return: bb1, unwind unreachable]; + } + + bb1: { + StorageDead(_3); +- StorageLive(_4); +- _4 = copy _2; ++ nop; ++ nop; ++ nop; ++ nop; ++ nop; ++ nop; + StorageLive(_5); +- StorageLive(_6); +- _6 = copy _4; + _5 = opaque::(move _6) -> [return: bb2, unwind unreachable]; + } + + bb2: { +- StorageDead(_6); + StorageDead(_5); ++ StorageDead(_6); ++ nop; ++ nop; ++ nop; ++ nop; ++ nop; + StorageLive(_7); +- StorageLive(_8); +- _8 = copy _1; +- _7 = opaque::(move _8) -> [return: bb3, unwind unreachable]; ++ _7 = opaque::(move _1) -> [return: bb3, unwind unreachable]; + } + + bb3: { +- StorageDead(_8); + StorageDead(_7); ++ nop; ++ nop; + _0 = const (); +- StorageDead(_4); +- StorageDead(_2); ++ nop; ++ nop; + return; + } + } + diff --git a/tests/mir-opt/move-elimination/storage.storage_dead_before_return.MoveElimination.diff b/tests/mir-opt/move-elimination/storage.storage_dead_before_return.MoveElimination.diff new file mode 100644 index 0000000000000..bc6299c97b6be --- /dev/null +++ b/tests/mir-opt/move-elimination/storage.storage_dead_before_return.MoveElimination.diff @@ -0,0 +1,17 @@ +- // MIR for `storage_dead_before_return` before MoveElimination ++ // MIR for `storage_dead_before_return` after MoveElimination + + fn storage_dead_before_return() -> *const u32 { + debug x => _1; + let mut _0: *const u32; + let mut _1: u32; + + bb0: { ++ StorageLive(_1); + _1 = const 1_u32; + _0 = &raw const _1; ++ StorageDead(_1); + return; + } + } + diff --git a/tests/mir-opt/move-elimination/storage.storage_live_elided_on_join_fork.MoveElimination.diff b/tests/mir-opt/move-elimination/storage.storage_live_elided_on_join_fork.MoveElimination.diff new file mode 100644 index 0000000000000..d5b9552b4fdf9 --- /dev/null +++ b/tests/mir-opt/move-elimination/storage.storage_live_elided_on_join_fork.MoveElimination.diff @@ -0,0 +1,36 @@ +- // MIR for `storage_live_elided_on_join_fork` before MoveElimination ++ // MIR for `storage_live_elided_on_join_fork` after MoveElimination + + fn storage_live_elided_on_join_fork(_1: bool) -> () { + debug x => _2; + let mut _0: (); + let mut _2: u32; + let mut _3: u32; + + bb0: { + switchInt(copy _1) -> [1: bb1, otherwise: bb2]; + } + + bb1: { ++ StorageLive(_2); + _2 = const 1_u32; + goto -> bb2; + } + + bb2: { + switchInt(copy _1) -> [1: bb3, otherwise: bb4]; + } + + bb3: { ++ StorageLive(_3); + _3 = opaque::(move _2) -> [return: bb4, unwind unreachable]; + } + + bb4: { ++ StorageDead(_2); ++ StorageDead(_2); ++ StorageDead(_3); + return; + } + } + diff --git a/tests/mir-opt/move-elimination/storage.storage_live_moved_to_branch.MoveElimination.diff b/tests/mir-opt/move-elimination/storage.storage_live_moved_to_branch.MoveElimination.diff new file mode 100644 index 0000000000000..9a7c3df9cb98c --- /dev/null +++ b/tests/mir-opt/move-elimination/storage.storage_live_moved_to_branch.MoveElimination.diff @@ -0,0 +1,63 @@ +- // MIR for `storage_live_moved_to_branch` before MoveElimination ++ // MIR for `storage_live_moved_to_branch` after MoveElimination + + fn storage_live_moved_to_branch(_1: bool) -> () { + debug flag => _1; + let mut _0: (); + let _2: u32; + let mut _3: bool; + let _4: u32; + let mut _5: u32; + scope 1 { +- debug x => _2; ++ debug x => _5; + } + + bb0: { +- StorageLive(_2); +- StorageLive(_3); +- _3 = copy _1; +- switchInt(move _3) -> [0: bb3, otherwise: bb1]; ++ nop; ++ nop; ++ nop; ++ switchInt(move _1) -> [0: bb3, otherwise: bb1]; + } + + bb1: { +- _2 = const 1_u32; +- StorageLive(_4); + StorageLive(_5); +- _5 = copy _2; ++ _5 = const 1_u32; ++ nop; ++ nop; ++ nop; ++ StorageLive(_4); + _4 = opaque::(move _5) -> [return: bb2, unwind unreachable]; + } + + bb2: { +- StorageDead(_5); + StorageDead(_4); ++ StorageDead(_5); ++ nop; ++ nop; + _0 = const (); + goto -> bb4; + } + + bb3: { + _0 = const (); + goto -> bb4; + } + + bb4: { +- StorageDead(_3); +- StorageDead(_2); ++ nop; ++ nop; + return; + } + } + diff --git a/tests/mir-opt/move-elimination/storage.terminator_end_storage_dead_in_successor.MoveElimination.diff b/tests/mir-opt/move-elimination/storage.terminator_end_storage_dead_in_successor.MoveElimination.diff new file mode 100644 index 0000000000000..ffc1f04c58097 --- /dev/null +++ b/tests/mir-opt/move-elimination/storage.terminator_end_storage_dead_in_successor.MoveElimination.diff @@ -0,0 +1,57 @@ +- // MIR for `terminator_end_storage_dead_in_successor` before MoveElimination ++ // MIR for `terminator_end_storage_dead_in_successor` after MoveElimination + + fn terminator_end_storage_dead_in_successor(_1: u32) -> u32 { + debug x => _1; + let mut _0: u32; + let _2: u32; + let mut _3: u32; + let mut _5: u32; + scope 1 { +- debug tmp => _2; ++ debug tmp => _5; + let _4: u32; + scope 2 { +- debug out => _4; ++ debug out => _0; + } + } + + bb0: { +- StorageLive(_2); +- StorageLive(_3); +- _3 = copy _1; +- _2 = opaque::(move _3) -> [return: bb1, unwind unreachable]; ++ nop; ++ nop; ++ nop; ++ StorageLive(_5); ++ _5 = opaque::(move _1) -> [return: bb1, unwind unreachable]; + } + + bb1: { +- StorageDead(_3); +- StorageLive(_4); +- StorageLive(_5); +- _5 = copy _2; +- _4 = opaque::(move _5) -> [return: bb2, unwind unreachable]; ++ nop; ++ nop; ++ nop; ++ nop; ++ _0 = opaque::(move _5) -> [return: bb2, unwind unreachable]; + } + + bb2: { + StorageDead(_5); +- _0 = copy _4; +- StorageDead(_4); +- StorageDead(_2); ++ nop; ++ nop; ++ nop; ++ nop; + return; + } + } + diff --git a/tests/mir-opt/move-elimination/storage_disabled.disabled.MoveElimination.diff b/tests/mir-opt/move-elimination/storage_disabled.disabled.MoveElimination.diff new file mode 100644 index 0000000000000..a90e345fdb701 --- /dev/null +++ b/tests/mir-opt/move-elimination/storage_disabled.disabled.MoveElimination.diff @@ -0,0 +1,18 @@ +- // MIR for `disabled` before MoveElimination ++ // MIR for `disabled` after MoveElimination + + fn disabled() -> *const u32 { + let mut _0: *const u32; + let mut _1: u32; + + bb0: { +- StorageLive(_1); ++ nop; + _1 = const 1_u32; + _0 = &raw const _1; +- StorageDead(_1); ++ nop; + return; + } + } + diff --git a/tests/mir-opt/move-elimination/storage_disabled.rs b/tests/mir-opt/move-elimination/storage_disabled.rs new file mode 100644 index 0000000000000..223861fd51594 --- /dev/null +++ b/tests/mir-opt/move-elimination/storage_disabled.rs @@ -0,0 +1,30 @@ +//@ test-mir-pass: MoveElimination +//@ compile-flags: -Copt-level=0 -Cpanic=abort + +#![feature(custom_mir, core_intrinsics)] + +use std::intrinsics::mir::*; + +// With storage reconstruction disabled, existing storage markers are removed +// without inserting new ones. +// EMIT_MIR storage_disabled.disabled.MoveElimination.diff +#[custom_mir(dialect = "runtime", phase = "post-cleanup")] +pub fn disabled() -> *const u32 { + // CHECK-LABEL: fn disabled( + // CHECK: bb0: { + // CHECK-NOT: Storage + // CHECK: [[X:_[0-9]+]] = const 1_u32; + // CHECK-NOT: Storage + // CHECK: return; + // CHECK-NOT: Storage + mir! { + let x: u32; + { + StorageLive(x); + x = 1; + RET = &raw const x; + StorageDead(x); + Return() + } + } +} diff --git a/tests/mir-opt/move-elimination/unwind.call_destination.MoveElimination.diff b/tests/mir-opt/move-elimination/unwind.call_destination.MoveElimination.diff index 7507f7bc81e7e..618e5b531b85e 100644 --- a/tests/mir-opt/move-elimination/unwind.call_destination.MoveElimination.diff +++ b/tests/mir-opt/move-elimination/unwind.call_destination.MoveElimination.diff @@ -8,19 +8,25 @@ let mut _3: *const u32; bb0: { ++ StorageLive(_1); _1 = const 0_u32; ++ StorageLive(_3); _3 = &raw const _1; ++ StorageDead(_3); _1 = opaque() -> [return: bb1, unwind: bb2]; } bb1: { _0 = (); ++ StorageDead(_1); return; } bb2 (cleanup): { ++ StorageLive(_2); _2 = const 2_u32; _1 = move _2; ++ StorageDead(_2); resume; } }