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 run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
23 debug!("elaborate_drops({:?} @ {:?})", body.source, body.span);
25 let def_id = body.source.def_id();
26 let param_env = tcx.param_env_reveal_all_normalized(def_id);
27 let move_data = match MoveData::gather_moves(body, tcx, param_env) {
28 Ok(move_data) => move_data,
29 Err((move_data, _)) => {
30 tcx.sess.delay_span_bug(
32 "No `move_errors` should be allowed in MIR borrowck",
37 let elaborate_patch = {
39 let env = MoveDataParamEnv { move_data, param_env };
40 let dead_unwinds = find_dead_unwinds(tcx, body, &env);
42 let inits = MaybeInitializedPlaces::new(tcx, body, &env)
43 .into_engine(tcx, body)
44 .dead_unwinds(&dead_unwinds)
45 .pass_name("elaborate_drops")
46 .iterate_to_fixpoint()
47 .into_results_cursor(body);
49 let uninits = MaybeUninitializedPlaces::new(tcx, body, &env)
50 .mark_inactive_variants_as_uninit()
51 .into_engine(tcx, body)
52 .dead_unwinds(&dead_unwinds)
53 .pass_name("elaborate_drops")
54 .iterate_to_fixpoint()
55 .into_results_cursor(body);
61 init_data: InitializationData { inits, uninits },
62 drop_flags: Default::default(),
63 patch: MirPatch::new(body),
67 elaborate_patch.apply(body);
71 /// Returns the set of basic blocks whose unwind edges are known
72 /// to not be reachable, because they are `drop` terminators
73 /// that can't drop anything.
74 fn find_dead_unwinds<'tcx>(
77 env: &MoveDataParamEnv<'tcx>,
78 ) -> BitSet<BasicBlock> {
79 debug!("find_dead_unwinds({:?})", body.span);
80 // We only need to do this pass once, because unwind edges can only
81 // reach cleanup blocks, which can't have unwind edges themselves.
82 let mut dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
83 let mut flow_inits = MaybeInitializedPlaces::new(tcx, body, &env)
84 .into_engine(tcx, body)
85 .pass_name("find_dead_unwinds")
86 .iterate_to_fixpoint()
87 .into_results_cursor(body);
88 for (bb, bb_data) in body.basic_blocks().iter_enumerated() {
89 let place = match bb_data.terminator().kind {
90 TerminatorKind::Drop { ref place, unwind: Some(_), .. }
91 | TerminatorKind::DropAndReplace { ref place, unwind: Some(_), .. } => place,
95 debug!("find_dead_unwinds @ {:?}: {:?}", bb, bb_data);
97 let path = match env.move_data.rev_lookup.find(place.as_ref()) {
98 LookupResult::Exact(e) => e,
99 LookupResult::Parent(..) => {
100 debug!("find_dead_unwinds: has parent; skipping");
105 flow_inits.seek_before_primary_effect(body.terminator_loc(bb));
107 "find_dead_unwinds @ {:?}: path({:?})={:?}; init_data={:?}",
114 let mut maybe_live = false;
115 on_all_drop_children_bits(tcx, body, &env, path, |child| {
116 maybe_live |= flow_inits.contains(child);
119 debug!("find_dead_unwinds @ {:?}: maybe_live={}", bb, maybe_live);
121 dead_unwinds.insert(bb);
128 struct InitializationData<'mir, 'tcx> {
129 inits: ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
130 uninits: ResultsCursor<'mir, 'tcx, MaybeUninitializedPlaces<'mir, 'tcx>>,
133 impl InitializationData<'_, '_> {
134 fn seek_before(&mut self, loc: Location) {
135 self.inits.seek_before_primary_effect(loc);
136 self.uninits.seek_before_primary_effect(loc);
139 fn maybe_live_dead(&self, path: MovePathIndex) -> (bool, bool) {
140 (self.inits.contains(path), self.uninits.contains(path))
144 struct Elaborator<'a, 'b, 'tcx> {
145 ctxt: &'a mut ElaborateDropsCtxt<'b, 'tcx>,
148 impl<'a, 'b, 'tcx> fmt::Debug for Elaborator<'a, 'b, 'tcx> {
149 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 impl<'a, 'b, 'tcx> DropElaborator<'a, 'tcx> for Elaborator<'a, 'b, 'tcx> {
155 type Path = MovePathIndex;
157 fn patch(&mut self) -> &mut MirPatch<'tcx> {
161 fn body(&self) -> &'a Body<'tcx> {
165 fn tcx(&self) -> TyCtxt<'tcx> {
169 fn param_env(&self) -> ty::ParamEnv<'tcx> {
170 self.ctxt.param_env()
173 fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle {
174 let ((maybe_live, maybe_dead), multipart) = match mode {
175 DropFlagMode::Shallow => (self.ctxt.init_data.maybe_live_dead(path), false),
176 DropFlagMode::Deep => {
177 let mut some_live = false;
178 let mut some_dead = false;
179 let mut children_count = 0;
180 on_all_drop_children_bits(self.tcx(), self.body(), self.ctxt.env, path, |child| {
181 let (live, dead) = self.ctxt.init_data.maybe_live_dead(child);
182 debug!("elaborate_drop: state({:?}) = {:?}", child, (live, dead));
187 ((some_live, some_dead), children_count != 1)
190 match (maybe_live, maybe_dead, multipart) {
191 (false, _, _) => DropStyle::Dead,
192 (true, false, _) => DropStyle::Static,
193 (true, true, false) => DropStyle::Conditional,
194 (true, true, true) => DropStyle::Open,
198 fn clear_drop_flag(&mut self, loc: Location, path: Self::Path, mode: DropFlagMode) {
200 DropFlagMode::Shallow => {
201 self.ctxt.set_drop_flag(loc, path, DropFlagState::Absent);
203 DropFlagMode::Deep => {
204 on_all_children_bits(
207 self.ctxt.move_data(),
209 |child| self.ctxt.set_drop_flag(loc, child, DropFlagState::Absent),
215 fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path> {
216 rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
217 ProjectionElem::Field(idx, _) => idx == field,
222 fn array_subpath(&self, path: Self::Path, index: u64, size: u64) -> Option<Self::Path> {
223 rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
224 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
225 debug_assert!(size == min_length, "min_length should be exact for arrays");
226 assert!(!from_end, "from_end should not be used for array element ConstantIndex");
233 fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path> {
234 rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| {
235 e == ProjectionElem::Deref
239 fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path> {
240 rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
241 ProjectionElem::Downcast(_, idx) => idx == variant,
246 fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>> {
247 self.ctxt.drop_flag(path).map(Operand::Copy)
251 struct ElaborateDropsCtxt<'a, 'tcx> {
253 body: &'a Body<'tcx>,
254 env: &'a MoveDataParamEnv<'tcx>,
255 init_data: InitializationData<'a, 'tcx>,
256 drop_flags: FxHashMap<MovePathIndex, Local>,
257 patch: MirPatch<'tcx>,
260 impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
261 fn move_data(&self) -> &'b MoveData<'tcx> {
265 fn param_env(&self) -> ty::ParamEnv<'tcx> {
269 fn create_drop_flag(&mut self, index: MovePathIndex, span: Span) {
271 let patch = &mut self.patch;
272 debug!("create_drop_flag({:?})", self.body.span);
273 self.drop_flags.entry(index).or_insert_with(|| patch.new_internal(tcx.types.bool, span));
276 fn drop_flag(&mut self, index: MovePathIndex) -> Option<Place<'tcx>> {
277 self.drop_flags.get(&index).map(|t| Place::from(*t))
280 /// create a patch that elaborates all drops in the input
282 fn elaborate(mut self) -> MirPatch<'tcx> {
283 self.collect_drop_flags();
285 self.elaborate_drops();
287 self.drop_flags_on_init();
288 self.drop_flags_for_fn_rets();
289 self.drop_flags_for_args();
290 self.drop_flags_for_locs();
295 fn collect_drop_flags(&mut self) {
296 for (bb, data) in self.body.basic_blocks().iter_enumerated() {
297 let terminator = data.terminator();
298 let place = match terminator.kind {
299 TerminatorKind::Drop { ref place, .. }
300 | TerminatorKind::DropAndReplace { ref place, .. } => place,
304 self.init_data.seek_before(self.body.terminator_loc(bb));
306 let path = self.move_data().rev_lookup.find(place.as_ref());
307 debug!("collect_drop_flags: {:?}, place {:?} ({:?})", bb, place, path);
309 let path = match path {
310 LookupResult::Exact(e) => e,
311 LookupResult::Parent(None) => continue,
312 LookupResult::Parent(Some(parent)) => {
313 let (_maybe_live, maybe_dead) = self.init_data.maybe_live_dead(parent);
316 terminator.source_info.span,
317 "drop of untracked, uninitialized value {:?}, place {:?} ({:?})",
327 on_all_drop_children_bits(self.tcx, self.body, self.env, path, |child| {
328 let (maybe_live, maybe_dead) = self.init_data.maybe_live_dead(child);
330 "collect_drop_flags: collecting {:?} from {:?}@{:?} - {:?}",
334 (maybe_live, maybe_dead)
336 if maybe_live && maybe_dead {
337 self.create_drop_flag(child, terminator.source_info.span)
343 fn elaborate_drops(&mut self) {
344 for (bb, data) in self.body.basic_blocks().iter_enumerated() {
345 let loc = Location { block: bb, statement_index: data.statements.len() };
346 let terminator = data.terminator();
348 let resume_block = self.patch.resume_block();
349 match terminator.kind {
350 TerminatorKind::Drop { place, target, unwind } => {
351 self.init_data.seek_before(loc);
352 match self.move_data().rev_lookup.find(place.as_ref()) {
353 LookupResult::Exact(path) => elaborate_drop(
354 &mut Elaborator { ctxt: self },
355 terminator.source_info,
362 Unwind::To(Option::unwrap_or(unwind, resume_block))
366 LookupResult::Parent(..) => {
368 terminator.source_info.span,
369 "drop of untracked value {:?}",
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)