2 use rustc_data_structures::fx::FxHashMap;
3 use rustc_index::bit_set::BitSet;
4 use rustc_middle::mir::patch::MirPatch;
5 use rustc_middle::mir::*;
6 use rustc_middle::ty::{self, TyCtxt};
7 use rustc_mir_dataflow::elaborate_drops::{elaborate_drop, DropFlagState, Unwind};
8 use rustc_mir_dataflow::elaborate_drops::{DropElaborator, DropFlagMode, DropStyle};
9 use rustc_mir_dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
10 use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex};
11 use rustc_mir_dataflow::on_lookup_result_bits;
12 use rustc_mir_dataflow::MoveDataParamEnv;
13 use rustc_mir_dataflow::{on_all_children_bits, on_all_drop_children_bits};
14 use rustc_mir_dataflow::{Analysis, ResultsCursor};
16 use rustc_target::abi::VariantIdx;
19 pub struct ElaborateDrops;
21 impl<'tcx> MirPass<'tcx> for ElaborateDrops {
22 fn phase_change(&self) -> Option<MirPhase> {
23 Some(MirPhase::DropsLowered)
26 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
27 debug!("elaborate_drops({:?} @ {:?})", body.source, body.span);
29 let def_id = body.source.def_id();
30 let param_env = tcx.param_env_reveal_all_normalized(def_id);
31 let move_data = match MoveData::gather_moves(body, tcx, param_env) {
32 Ok(move_data) => move_data,
33 Err((move_data, _)) => {
34 tcx.sess.delay_span_bug(
36 "No `move_errors` should be allowed in MIR borrowck",
41 let elaborate_patch = {
43 let env = MoveDataParamEnv { move_data, param_env };
44 let dead_unwinds = find_dead_unwinds(tcx, body, &env);
46 let inits = MaybeInitializedPlaces::new(tcx, body, &env)
47 .into_engine(tcx, body)
48 .dead_unwinds(&dead_unwinds)
49 .pass_name("elaborate_drops")
50 .iterate_to_fixpoint()
51 .into_results_cursor(body);
53 let uninits = MaybeUninitializedPlaces::new(tcx, body, &env)
54 .mark_inactive_variants_as_uninit()
55 .into_engine(tcx, body)
56 .dead_unwinds(&dead_unwinds)
57 .pass_name("elaborate_drops")
58 .iterate_to_fixpoint()
59 .into_results_cursor(body);
65 init_data: InitializationData { inits, uninits },
66 drop_flags: Default::default(),
67 patch: MirPatch::new(body),
71 elaborate_patch.apply(body);
75 /// Returns the set of basic blocks whose unwind edges are known
76 /// to not be reachable, because they are `drop` terminators
77 /// that can't drop anything.
78 fn find_dead_unwinds<'tcx>(
81 env: &MoveDataParamEnv<'tcx>,
82 ) -> BitSet<BasicBlock> {
83 debug!("find_dead_unwinds({:?})", body.span);
84 // We only need to do this pass once, because unwind edges can only
85 // reach cleanup blocks, which can't have unwind edges themselves.
86 let mut dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
87 let mut flow_inits = MaybeInitializedPlaces::new(tcx, body, &env)
88 .into_engine(tcx, body)
89 .pass_name("find_dead_unwinds")
90 .iterate_to_fixpoint()
91 .into_results_cursor(body);
92 for (bb, bb_data) in body.basic_blocks().iter_enumerated() {
93 let place = match bb_data.terminator().kind {
94 TerminatorKind::Drop { ref place, unwind: Some(_), .. }
95 | TerminatorKind::DropAndReplace { ref place, unwind: Some(_), .. } => place,
99 debug!("find_dead_unwinds @ {:?}: {:?}", bb, bb_data);
101 let LookupResult::Exact(path) = env.move_data.rev_lookup.find(place.as_ref()) else {
102 debug!("find_dead_unwinds: has parent; skipping");
106 flow_inits.seek_before_primary_effect(body.terminator_loc(bb));
108 "find_dead_unwinds @ {:?}: path({:?})={:?}; init_data={:?}",
115 let mut maybe_live = false;
116 on_all_drop_children_bits(tcx, body, &env, path, |child| {
117 maybe_live |= flow_inits.contains(child);
120 debug!("find_dead_unwinds @ {:?}: maybe_live={}", bb, maybe_live);
122 dead_unwinds.insert(bb);
129 struct InitializationData<'mir, 'tcx> {
130 inits: ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
131 uninits: ResultsCursor<'mir, 'tcx, MaybeUninitializedPlaces<'mir, 'tcx>>,
134 impl InitializationData<'_, '_> {
135 fn seek_before(&mut self, loc: Location) {
136 self.inits.seek_before_primary_effect(loc);
137 self.uninits.seek_before_primary_effect(loc);
140 fn maybe_live_dead(&self, path: MovePathIndex) -> (bool, bool) {
141 (self.inits.contains(path), self.uninits.contains(path))
145 struct Elaborator<'a, 'b, 'tcx> {
146 ctxt: &'a mut ElaborateDropsCtxt<'b, 'tcx>,
149 impl fmt::Debug for Elaborator<'_, '_, '_> {
150 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for Elaborator<'a, '_, 'tcx> {
156 type Path = MovePathIndex;
158 fn patch(&mut self) -> &mut MirPatch<'tcx> {
162 fn body(&self) -> &'a Body<'tcx> {
166 fn tcx(&self) -> TyCtxt<'tcx> {
170 fn param_env(&self) -> ty::ParamEnv<'tcx> {
171 self.ctxt.param_env()
174 fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle {
175 let ((maybe_live, maybe_dead), multipart) = match mode {
176 DropFlagMode::Shallow => (self.ctxt.init_data.maybe_live_dead(path), false),
177 DropFlagMode::Deep => {
178 let mut some_live = false;
179 let mut some_dead = false;
180 let mut children_count = 0;
181 on_all_drop_children_bits(self.tcx(), self.body(), self.ctxt.env, path, |child| {
182 let (live, dead) = self.ctxt.init_data.maybe_live_dead(child);
183 debug!("elaborate_drop: state({:?}) = {:?}", child, (live, dead));
188 ((some_live, some_dead), children_count != 1)
191 match (maybe_live, maybe_dead, multipart) {
192 (false, _, _) => DropStyle::Dead,
193 (true, false, _) => DropStyle::Static,
194 (true, true, false) => DropStyle::Conditional,
195 (true, true, true) => DropStyle::Open,
199 fn clear_drop_flag(&mut self, loc: Location, path: Self::Path, mode: DropFlagMode) {
201 DropFlagMode::Shallow => {
202 self.ctxt.set_drop_flag(loc, path, DropFlagState::Absent);
204 DropFlagMode::Deep => {
205 on_all_children_bits(
208 self.ctxt.move_data(),
210 |child| self.ctxt.set_drop_flag(loc, child, DropFlagState::Absent),
216 fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path> {
217 rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
218 ProjectionElem::Field(idx, _) => idx == field,
223 fn array_subpath(&self, path: Self::Path, index: u64, size: u64) -> Option<Self::Path> {
224 rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
225 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
226 debug_assert!(size == min_length, "min_length should be exact for arrays");
227 assert!(!from_end, "from_end should not be used for array element ConstantIndex");
234 fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path> {
235 rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| {
236 e == ProjectionElem::Deref
240 fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path> {
241 rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
242 ProjectionElem::Downcast(_, idx) => idx == variant,
247 fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>> {
248 self.ctxt.drop_flag(path).map(Operand::Copy)
252 struct ElaborateDropsCtxt<'a, 'tcx> {
254 body: &'a Body<'tcx>,
255 env: &'a MoveDataParamEnv<'tcx>,
256 init_data: InitializationData<'a, 'tcx>,
257 drop_flags: FxHashMap<MovePathIndex, Local>,
258 patch: MirPatch<'tcx>,
261 impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
262 fn move_data(&self) -> &'b MoveData<'tcx> {
266 fn param_env(&self) -> ty::ParamEnv<'tcx> {
270 fn create_drop_flag(&mut self, index: MovePathIndex, span: Span) {
272 let patch = &mut self.patch;
273 debug!("create_drop_flag({:?})", self.body.span);
274 self.drop_flags.entry(index).or_insert_with(|| patch.new_internal(tcx.types.bool, span));
277 fn drop_flag(&mut self, index: MovePathIndex) -> Option<Place<'tcx>> {
278 self.drop_flags.get(&index).map(|t| Place::from(*t))
281 /// create a patch that elaborates all drops in the input
283 fn elaborate(mut self) -> MirPatch<'tcx> {
284 self.collect_drop_flags();
286 self.elaborate_drops();
288 self.drop_flags_on_init();
289 self.drop_flags_for_fn_rets();
290 self.drop_flags_for_args();
291 self.drop_flags_for_locs();
296 fn collect_drop_flags(&mut self) {
297 for (bb, data) in self.body.basic_blocks().iter_enumerated() {
298 let terminator = data.terminator();
299 let place = match terminator.kind {
300 TerminatorKind::Drop { ref place, .. }
301 | TerminatorKind::DropAndReplace { ref place, .. } => place,
305 self.init_data.seek_before(self.body.terminator_loc(bb));
307 let path = self.move_data().rev_lookup.find(place.as_ref());
308 debug!("collect_drop_flags: {:?}, place {:?} ({:?})", bb, place, path);
310 let path = match path {
311 LookupResult::Exact(e) => e,
312 LookupResult::Parent(None) => continue,
313 LookupResult::Parent(Some(parent)) => {
314 let (_maybe_live, maybe_dead) = self.init_data.maybe_live_dead(parent);
316 self.tcx.sess.delay_span_bug(
317 terminator.source_info.span,
319 "drop of untracked, uninitialized value {:?}, place {:?} ({:?})",
328 on_all_drop_children_bits(self.tcx, self.body, self.env, path, |child| {
329 let (maybe_live, maybe_dead) = self.init_data.maybe_live_dead(child);
331 "collect_drop_flags: collecting {:?} from {:?}@{:?} - {:?}",
335 (maybe_live, maybe_dead)
337 if maybe_live && maybe_dead {
338 self.create_drop_flag(child, terminator.source_info.span)
344 fn elaborate_drops(&mut self) {
345 for (bb, data) in self.body.basic_blocks().iter_enumerated() {
346 let loc = Location { block: bb, statement_index: data.statements.len() };
347 let terminator = data.terminator();
349 let resume_block = self.patch.resume_block();
350 match terminator.kind {
351 TerminatorKind::Drop { place, target, unwind } => {
352 self.init_data.seek_before(loc);
353 match self.move_data().rev_lookup.find(place.as_ref()) {
354 LookupResult::Exact(path) => elaborate_drop(
355 &mut Elaborator { ctxt: self },
356 terminator.source_info,
363 Unwind::To(Option::unwrap_or(unwind, resume_block))
367 LookupResult::Parent(..) => {
368 self.tcx.sess.delay_span_bug(
369 terminator.source_info.span,
370 &format!("drop of untracked value {:?}", bb),
375 TerminatorKind::DropAndReplace { place, ref value, target, unwind } => {
376 assert!(!data.is_cleanup);
378 self.elaborate_replace(loc, place, value, target, unwind);
385 /// Elaborate a MIR `replace` terminator. This instruction
386 /// is not directly handled by codegen, and therefore
387 /// must be desugared.
389 /// The desugaring drops the location if needed, and then writes
390 /// the value (including setting the drop flag) over it in *both* arms.
392 /// The `replace` terminator can also be called on places that
393 /// are not tracked by elaboration (for example,
394 /// `replace x[i] <- tmp0`). The borrow checker requires that
395 /// these locations are initialized before the assignment,
396 /// so we just generate an unconditional drop.
397 fn elaborate_replace(
401 value: &Operand<'tcx>,
403 unwind: Option<BasicBlock>,
406 let data = &self.body[bb];
407 let terminator = data.terminator();
408 assert!(!data.is_cleanup, "DropAndReplace in unwind path not supported");
410 let assign = Statement {
411 kind: StatementKind::Assign(Box::new((place, Rvalue::Use(value.clone())))),
412 source_info: terminator.source_info,
415 let unwind = unwind.unwrap_or_else(|| self.patch.resume_block());
416 let unwind = self.patch.new_block(BasicBlockData {
417 statements: vec![assign.clone()],
418 terminator: Some(Terminator {
419 kind: TerminatorKind::Goto { target: unwind },
425 let target = self.patch.new_block(BasicBlockData {
426 statements: vec![assign],
427 terminator: Some(Terminator { kind: TerminatorKind::Goto { target }, ..*terminator }),
431 match self.move_data().rev_lookup.find(place.as_ref()) {
432 LookupResult::Exact(path) => {
433 debug!("elaborate_drop_and_replace({:?}) - tracked {:?}", terminator, path);
434 self.init_data.seek_before(loc);
436 &mut Elaborator { ctxt: self },
437 terminator.source_info,
444 on_all_children_bits(self.tcx, self.body, self.move_data(), path, |child| {
446 Location { block: target, statement_index: 0 },
448 DropFlagState::Present,
451 Location { block: unwind, statement_index: 0 },
453 DropFlagState::Present,
457 LookupResult::Parent(parent) => {
458 // drop and replace behind a pointer/array/whatever. The location
459 // must be initialized.
460 debug!("elaborate_drop_and_replace({:?}) - untracked {:?}", terminator, parent);
461 self.patch.patch_terminator(
463 TerminatorKind::Drop { place, target, unwind: Some(unwind) },
469 fn constant_bool(&self, span: Span, val: bool) -> Rvalue<'tcx> {
470 Rvalue::Use(Operand::Constant(Box::new(Constant {
473 literal: ty::Const::from_bool(self.tcx, val).into(),
477 fn set_drop_flag(&mut self, loc: Location, path: MovePathIndex, val: DropFlagState) {
478 if let Some(&flag) = self.drop_flags.get(&path) {
479 let span = self.patch.source_info_for_location(self.body, loc).span;
480 let val = self.constant_bool(span, val.value());
481 self.patch.add_assign(loc, Place::from(flag), val);
485 fn drop_flags_on_init(&mut self) {
486 let loc = Location::START;
487 let span = self.patch.source_info_for_location(self.body, loc).span;
488 let false_ = self.constant_bool(span, false);
489 for flag in self.drop_flags.values() {
490 self.patch.add_assign(loc, Place::from(*flag), false_.clone());
494 fn drop_flags_for_fn_rets(&mut self) {
495 for (bb, data) in self.body.basic_blocks().iter_enumerated() {
496 if let TerminatorKind::Call {
497 destination: Some((ref place, tgt)),
500 } = data.terminator().kind
502 assert!(!self.patch.is_patched(bb));
504 let loc = Location { block: tgt, statement_index: 0 };
505 let path = self.move_data().rev_lookup.find(place.as_ref());
506 on_lookup_result_bits(self.tcx, self.body, self.move_data(), path, |child| {
507 self.set_drop_flag(loc, child, DropFlagState::Present)
513 fn drop_flags_for_args(&mut self) {
514 let loc = Location::START;
515 rustc_mir_dataflow::drop_flag_effects_for_function_entry(
520 self.set_drop_flag(loc, path, ds);
525 fn drop_flags_for_locs(&mut self) {
526 // We intentionally iterate only over the *old* basic blocks.
528 // Basic blocks created by drop elaboration update their
529 // drop flags by themselves, to avoid the drop flags being
530 // clobbered before they are read.
532 for (bb, data) in self.body.basic_blocks().iter_enumerated() {
533 debug!("drop_flags_for_locs({:?})", data);
534 for i in 0..(data.statements.len() + 1) {
535 debug!("drop_flag_for_locs: stmt {}", i);
536 let mut allow_initializations = true;
537 if i == data.statements.len() {
538 match data.terminator().kind {
539 TerminatorKind::Drop { .. } => {
540 // drop elaboration should handle that by itself
543 TerminatorKind::DropAndReplace { .. } => {
544 // this contains the move of the source and
545 // the initialization of the destination. We
546 // only want the former - the latter is handled
547 // by the elaboration code and must be done
548 // *after* the destination is dropped.
549 assert!(self.patch.is_patched(bb));
550 allow_initializations = false;
552 TerminatorKind::Resume => {
553 // It is possible for `Resume` to be patched
554 // (in particular it can be patched to be replaced with
555 // a Goto; see `MirPatch::new`).
558 assert!(!self.patch.is_patched(bb));
562 let loc = Location { block: bb, statement_index: i };
563 rustc_mir_dataflow::drop_flag_effects_for_location(
569 if ds == DropFlagState::Absent || allow_initializations {
570 self.set_drop_flag(loc, path, ds)
576 // There may be a critical edge after this call,
577 // so mark the return as initialized *before* the
579 if let TerminatorKind::Call {
580 destination: Some((ref place, _)), cleanup: None, ..
581 } = data.terminator().kind
583 assert!(!self.patch.is_patched(bb));
585 let loc = Location { block: bb, statement_index: data.statements.len() };
586 let path = self.move_data().rev_lookup.find(place.as_ref());
587 on_lookup_result_bits(self.tcx, self.body, self.move_data(), path, |child| {
588 self.set_drop_flag(loc, child, DropFlagState::Present)