1 use rustc_hir::def_id::DefId;
2 use rustc_middle::mir::*;
3 use rustc_middle::ty::TyCtxt;
5 use crate::transform::MirPass;
7 use crate::util::patch::MirPatch;
9 // This pass moves values being dropped that are within a packed
10 // struct to a separate local before dropping them, to ensure that
11 // they are dropped from an aligned address.
13 // For example, if we have something like
24 // We want to call `drop_in_place::<Vec<u8>>` on `data` from an aligned
25 // address. This means we can't simply drop `foo.data` directly, because
26 // its address is not aligned.
28 // Instead, we move `foo.data` to a local and drop that:
30 // storage.live(drop_temp)
31 // drop_temp = foo.data;
32 // drop(drop_temp) -> next
34 // storage.dead(drop_temp)
37 // The storage instructions are required to avoid stack space
40 pub struct AddMovesForPackedDrops;
42 impl<'tcx> MirPass<'tcx> for AddMovesForPackedDrops {
43 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
44 debug!("add_moves_for_packed_drops({:?} @ {:?})", body.source, body.span);
45 add_moves_for_packed_drops(tcx, body, body.source.def_id());
49 pub fn add_moves_for_packed_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, def_id: DefId) {
50 let patch = add_moves_for_packed_drops_patch(tcx, body, def_id);
54 fn add_moves_for_packed_drops_patch<'tcx>(
59 let mut patch = MirPatch::new(body);
60 let param_env = tcx.param_env(def_id);
62 for (bb, data) in body.basic_blocks().iter_enumerated() {
63 let loc = Location { block: bb, statement_index: data.statements.len() };
64 let terminator = data.terminator();
66 match terminator.kind {
67 TerminatorKind::Drop { place, .. }
68 if util::is_disaligned(tcx, body, param_env, place) =>
70 add_move_for_packed_drop(tcx, body, &mut patch, terminator, loc, data.is_cleanup);
72 TerminatorKind::DropAndReplace { .. } => {
73 span_bug!(terminator.source_info.span, "replace in AddMovesForPackedDrops");
82 fn add_move_for_packed_drop<'tcx>(
85 patch: &mut MirPatch<'tcx>,
86 terminator: &Terminator<'tcx>,
90 debug!("add_move_for_packed_drop({:?} @ {:?})", terminator, loc);
91 let (place, target, unwind) = match terminator.kind {
92 TerminatorKind::Drop { ref place, target, unwind } => (place, target, unwind),
96 let source_info = terminator.source_info;
97 let ty = place.ty(body, tcx).ty;
98 let temp = patch.new_temp(ty, terminator.source_info.span);
100 let storage_dead_block = patch.new_block(BasicBlockData {
101 statements: vec![Statement { source_info, kind: StatementKind::StorageDead(temp) }],
102 terminator: Some(Terminator { source_info, kind: TerminatorKind::Goto { target } }),
106 patch.add_statement(loc, StatementKind::StorageLive(temp));
107 patch.add_assign(loc, Place::from(temp), Rvalue::Use(Operand::Move(*place)));
108 patch.patch_terminator(
110 TerminatorKind::Drop { place: Place::from(temp), target: storage_dead_block, unwind },