Skip to main content

rustc_mir_transform/
elaborate_drops.rs

1use std::fmt;
2
3use rustc_abi::{FieldIdx, VariantIdx};
4use rustc_index::IndexVec;
5use rustc_index::bit_set::DenseBitSet;
6use rustc_middle::mir::*;
7use rustc_middle::ty::{self, TyCtxt};
8use rustc_mir_dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
9use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex};
10use rustc_mir_dataflow::{
11    Analysis, DropFlagState, MoveDataTypingEnv, ResultsCursor, on_all_children_bits,
12    on_lookup_result_bits,
13};
14use rustc_span::Span;
15use tracing::{debug, instrument};
16
17use crate::PassPolicy;
18use crate::elaborate_drop::{DropElaborator, DropFlagMode, DropStyle, Unwind, elaborate_drop};
19use crate::patch::MirPatch;
20
21/// During MIR building, Drop terminators are inserted in every place where a drop may occur.
22/// However, in this phase, the presence of these terminators does not guarantee that a destructor
23/// will run, as the target of the drop may be uninitialized.
24/// In general, the compiler cannot determine at compile time whether a destructor will run or not.
25///
26/// At a high level, this pass refines Drop to only run the destructor if the
27/// target is initialized. The way this is achieved is by inserting drop flags for every variable
28/// that may be dropped, and then using those flags to determine whether a destructor should run.
29/// Once this is complete, Drop terminators in the MIR correspond to a call to the "drop glue" or
30/// "drop shim" for the type of the dropped place.
31///
32/// This pass relies on dropped places having an associated move path, which is then used to
33/// determine the initialization status of the place and its descendants.
34/// It's worth noting that a MIR containing a Drop without an associated move path is probably ill
35/// formed, as it would allow running a destructor on a place behind a reference:
36///
37/// ```text
38/// fn drop_term<T>(t: &mut T) {
39///     mir! {
40///         {
41///             Drop(*t, exit)
42///         }
43///         exit = {
44///             Return()
45///         }
46///     }
47/// }
48/// ```
49pub(super) struct ElaborateDrops;
50
51impl<'tcx> crate::MirPass<'tcx> for ElaborateDrops {
52    #[instrument(level = "trace", skip(self, tcx, body))]
53    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
54        debug!("elaborate_drops({:?} @ {:?})", body.source, body.span);
55        let typing_env = body.typing_env(tcx);
56        // For types that do not need dropping, the behaviour is trivial. So we only need to track
57        // init/uninit for types that do need dropping.
58        let move_data = MoveData::gather_moves(body, tcx, |ty| ty.needs_drop(tcx, typing_env));
59        let elaborate_patch = {
60            let env = MoveDataTypingEnv { move_data, typing_env };
61
62            let mut inits = MaybeInitializedPlaces::new(tcx, body, &env.move_data)
63                .exclude_inactive_in_otherwise()
64                .skipping_unreachable_unwind()
65                .iterate_to_fixpoint(tcx, body, Some("elaborate_drops"))
66                .into_results_cursor(body);
67            let dead_unwinds = compute_dead_unwinds(body, &mut inits);
68
69            let uninits = MaybeUninitializedPlaces::new(tcx, body, &env.move_data)
70                .mark_inactive_variants_as_uninit()
71                .skipping_unreachable_unwind(dead_unwinds)
72                .iterate_to_fixpoint(tcx, body, Some("elaborate_drops"))
73                .into_results_cursor(body);
74
75            let drop_flags = IndexVec::from_elem(None, &env.move_data.move_paths);
76            ElaborateDropsCtxt {
77                tcx,
78                body,
79                env: &env,
80                init_data: InitializationData { inits, uninits },
81                drop_flags,
82                patch: MirPatch::new(body),
83            }
84            .elaborate()
85        };
86        elaborate_patch.apply(body);
87    }
88
89    fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
90        // Implements MIR drop semantics.
91        PassPolicy::Required
92    }
93}
94
95/// Records unwind edges which are known to be unreachable, because they are in `drop` terminators
96/// that can't drop anything.
97#[instrument(level = "trace", skip(body, flow_inits), ret)]
98fn compute_dead_unwinds<'a, 'tcx>(
99    body: &'a Body<'tcx>,
100    flow_inits: &mut ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
101) -> DenseBitSet<BasicBlock> {
102    // We only need to do this pass once, because unwind edges can only
103    // reach cleanup blocks, which can't have unwind edges themselves.
104    let mut dead_unwinds = DenseBitSet::new_empty(body.basic_blocks.len());
105    for (bb, bb_data) in body.basic_blocks.iter_enumerated() {
106        let TerminatorKind::Drop { place, unwind: UnwindAction::Cleanup(_), .. } =
107            bb_data.terminator.kind
108        else {
109            continue;
110        };
111
112        flow_inits.seek_before_primary_effect(body.terminator_loc(bb));
113        if flow_inits.analysis().is_unwind_dead(place, flow_inits.get()) {
114            dead_unwinds.insert(bb);
115        }
116    }
117
118    dead_unwinds
119}
120
121struct InitializationData<'a, 'tcx> {
122    inits: ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
123    uninits: ResultsCursor<'a, 'tcx, MaybeUninitializedPlaces<'a, 'tcx>>,
124}
125
126impl InitializationData<'_, '_> {
127    fn seek_before(&mut self, loc: Location) {
128        self.inits.seek_before_primary_effect(loc);
129        self.uninits.seek_before_primary_effect(loc);
130    }
131
132    fn maybe_init_uninit(&self, path: MovePathIndex) -> (bool, bool) {
133        (self.inits.get().contains(path), self.uninits.get().contains(path))
134    }
135}
136
137impl<'a, 'tcx> DropElaborator<'a, 'tcx> for ElaborateDropsCtxt<'a, 'tcx> {
138    type Path = MovePathIndex;
139
140    fn patch_ref(&self) -> &MirPatch<'tcx> {
141        &self.patch
142    }
143
144    fn patch(&mut self) -> &mut MirPatch<'tcx> {
145        &mut self.patch
146    }
147
148    fn body(&self) -> &'a Body<'tcx> {
149        self.body
150    }
151
152    fn tcx(&self) -> TyCtxt<'tcx> {
153        self.tcx
154    }
155
156    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
157        self.env.typing_env
158    }
159
160    fn allow_async_drops(&self) -> bool {
161        true
162    }
163
164    #[instrument(level = "debug", skip(self), ret)]
165    fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle {
166        let ((maybe_init, maybe_uninit), multipart) = match mode {
167            DropFlagMode::Shallow => (self.init_data.maybe_init_uninit(path), false),
168            DropFlagMode::Deep => {
169                let mut some_maybe_init = false;
170                let mut some_maybe_uninit = false;
171                let mut children_count = 0;
172                on_all_children_bits(self.move_data(), path, |child| {
173                    let (maybe_init, maybe_uninit) = self.init_data.maybe_init_uninit(child);
174                    debug!("elaborate_drop: state({:?}) = {:?}", child, (maybe_init, maybe_uninit));
175                    some_maybe_init |= maybe_init;
176                    some_maybe_uninit |= maybe_uninit;
177                    children_count += 1;
178                });
179                ((some_maybe_init, some_maybe_uninit), children_count != 1)
180            }
181        };
182        match (maybe_init, maybe_uninit, multipart) {
183            (false, _, _) => DropStyle::Dead,
184            (true, false, _) => DropStyle::Static,
185            (true, true, false) => DropStyle::Conditional,
186            (true, true, true) => DropStyle::Open,
187        }
188    }
189
190    fn drop_flags_for(&mut self, path: Self::Path, mode: DropFlagMode) -> Vec<Place<'tcx>> {
191        let mut flags = vec![];
192        match mode {
193            DropFlagMode::Shallow => {
194                if let Some(flag) = self.drop_flags[path] {
195                    flags.push(flag.into());
196                }
197            }
198            DropFlagMode::Deep => {
199                on_all_children_bits(self.move_data(), path, |child| {
200                    if let Some(flag) = self.drop_flags[child] {
201                        flags.push(flag.into());
202                    }
203                });
204            }
205        }
206        flags
207    }
208
209    fn field_subpath(&self, path: Self::Path, field: FieldIdx) -> Option<Self::Path> {
210        rustc_mir_dataflow::move_path_children_matching(self.move_data(), path, |e| match e {
211            ProjectionElem::Field(idx, _) => idx == field,
212            _ => false,
213        })
214    }
215
216    fn array_subpath(&self, path: Self::Path, index: u64, size: u64) -> Option<Self::Path> {
217        rustc_mir_dataflow::move_path_children_matching(self.move_data(), path, |e| match e {
218            ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
219                debug_assert!(size == min_length, "min_length should be exact for arrays");
220                assert!(!from_end, "from_end should not be used for array element ConstantIndex");
221                offset == index
222            }
223            _ => false,
224        })
225    }
226
227    fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path> {
228        rustc_mir_dataflow::move_path_children_matching(self.move_data(), path, |e| {
229            e == ProjectionElem::Deref
230        })
231    }
232
233    fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path> {
234        rustc_mir_dataflow::move_path_children_matching(self.move_data(), path, |e| match e {
235            ProjectionElem::Downcast(_, idx) => idx == variant,
236            _ => false,
237        })
238    }
239
240    fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>> {
241        self.drop_flag(path).map(Operand::Copy)
242    }
243}
244
245struct ElaborateDropsCtxt<'a, 'tcx> {
246    tcx: TyCtxt<'tcx>,
247    body: &'a Body<'tcx>,
248    env: &'a MoveDataTypingEnv<'tcx>,
249    init_data: InitializationData<'a, 'tcx>,
250    drop_flags: IndexVec<MovePathIndex, Option<Local>>,
251    patch: MirPatch<'tcx>,
252}
253
254impl fmt::Debug for ElaborateDropsCtxt<'_, '_> {
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        f.debug_struct("ElaborateDropsCtxt").finish_non_exhaustive()
257    }
258}
259
260impl<'a, 'tcx> ElaborateDropsCtxt<'a, 'tcx> {
261    fn move_data(&self) -> &'a MoveData<'tcx> {
262        &self.env.move_data
263    }
264
265    fn create_drop_flag(&mut self, index: MovePathIndex, span: Span) {
266        let patch = &mut self.patch;
267        debug!("create_drop_flag({:?})", self.body.span);
268        self.drop_flags[index].get_or_insert_with(|| patch.new_temp(self.tcx.types.bool, span));
269    }
270
271    fn drop_flag(&mut self, index: MovePathIndex) -> Option<Place<'tcx>> {
272        self.drop_flags[index].map(Place::from)
273    }
274
275    /// create a patch that elaborates all drops in the input
276    /// MIR.
277    fn elaborate(mut self) -> MirPatch<'tcx> {
278        self.collect_drop_flags();
279
280        self.elaborate_drops();
281
282        self.drop_flags_on_init();
283        self.drop_flags_for_fn_rets();
284        self.drop_flags_for_args();
285        self.drop_flags_for_locs();
286
287        self.patch
288    }
289
290    fn collect_drop_flags(&mut self) {
291        for (bb, data) in self.body.basic_blocks.iter_enumerated() {
292            let terminator = &data.terminator;
293            let TerminatorKind::Drop { ref place, .. } = terminator.kind else { continue };
294
295            let path = self.move_data().rev_lookup.find(place.as_ref());
296            debug!("collect_drop_flags: {:?}, place {:?} ({:?})", bb, place, path);
297
298            match path {
299                LookupResult::Exact(path) => {
300                    self.init_data.seek_before(self.body.terminator_loc(bb));
301                    on_all_children_bits(self.move_data(), path, |child| {
302                        let (maybe_init, maybe_uninit) = self.init_data.maybe_init_uninit(child);
303                        debug!(
304                            "collect_drop_flags: collecting {:?} from {:?}@{:?} - {:?}",
305                            child,
306                            place,
307                            path,
308                            (maybe_init, maybe_uninit)
309                        );
310                        if maybe_init && maybe_uninit {
311                            self.create_drop_flag(child, terminator.source_info.span)
312                        }
313                    });
314                }
315                LookupResult::Parent(None) => {}
316                LookupResult::Parent(Some(parent)) => {
317                    if self.body.local_decls[place.local].is_deref_temp() {
318                        continue;
319                    }
320
321                    self.init_data.seek_before(self.body.terminator_loc(bb));
322                    let (_maybe_init, maybe_uninit) = self.init_data.maybe_init_uninit(parent);
323                    if maybe_uninit {
324                        self.tcx.dcx().span_delayed_bug(
325                            terminator.source_info.span,
326                            format!(
327                                "drop of untracked, uninitialized value {bb:?}, place {place:?} ({path:?})"
328                            ),
329                        );
330                    }
331                }
332            };
333        }
334    }
335
336    fn elaborate_drops(&mut self) {
337        // This function should mirror what `collect_drop_flags` does.
338        for (bb, data) in self.body.basic_blocks.iter_enumerated() {
339            let terminator = &data.terminator;
340            let TerminatorKind::Drop { place, target, unwind, replace, drop } = terminator.kind
341            else {
342                continue;
343            };
344
345            // This place does not need dropping. It does not have an associated move-path, so the
346            // match below will conservatively keep an unconditional drop. As that drop is useless,
347            // just remove it here and now.
348            if !place
349                .ty(&self.body.local_decls, self.tcx)
350                .ty
351                .needs_drop(self.tcx, self.typing_env())
352            {
353                self.patch.patch_terminator(bb, TerminatorKind::goto(target));
354                continue;
355            }
356
357            let path = self.move_data().rev_lookup.find(place.as_ref());
358            match path {
359                LookupResult::Exact(path) => {
360                    let unwind = match unwind {
361                        _ if data.is_cleanup => Unwind::InCleanup,
362                        UnwindAction::Cleanup(cleanup) => Unwind::To(cleanup),
363                        UnwindAction::Continue => Unwind::To(self.patch.resume_block()),
364                        UnwindAction::Unreachable => {
365                            Unwind::To(self.patch.unreachable_cleanup_block())
366                        }
367                        UnwindAction::Terminate(reason) => {
368                            debug_assert_ne!(
369                                reason,
370                                UnwindTerminateReason::InCleanup,
371                                "we are not in a cleanup block, InCleanup reason should be impossible"
372                            );
373                            Unwind::To(self.patch.terminate_block(reason))
374                        }
375                    };
376                    self.init_data.seek_before(self.body.terminator_loc(bb));
377                    elaborate_drop(
378                        self,
379                        terminator.source_info,
380                        place,
381                        path,
382                        target,
383                        unwind,
384                        bb,
385                        drop,
386                    )
387                }
388                LookupResult::Parent(None) => {}
389                LookupResult::Parent(Some(_)) => {
390                    if !replace {
391                        self.tcx.dcx().span_bug(
392                            terminator.source_info.span,
393                            format!("drop of untracked value {bb:?}"),
394                        );
395                    }
396                    // A drop and replace behind a pointer/array/whatever.
397                    // The borrow checker requires that these locations are initialized before the
398                    // assignment, so we just leave an unconditional drop.
399                    assert!(!data.is_cleanup);
400                }
401            }
402        }
403    }
404
405    fn constant_bool(&self, span: Span, val: bool) -> Rvalue<'tcx> {
406        Rvalue::Use(
407            Operand::Constant(Box::new(ConstOperand {
408                span,
409                user_ty: None,
410                const_: Const::from_bool(self.tcx, val),
411            })),
412            WithRetag::Yes,
413        )
414    }
415
416    fn set_drop_flag(&mut self, loc: Location, path: MovePathIndex, val: DropFlagState) {
417        if let Some(flag) = self.drop_flags[path] {
418            let span = self.patch.source_info_for_location(self.body, loc).span;
419            let val = self.constant_bool(span, val.value());
420            self.patch.add_assign(loc, Place::from(flag), val);
421        }
422    }
423
424    fn drop_flags_on_init(&mut self) {
425        let loc = Location::START;
426        let span = self.patch.source_info_for_location(self.body, loc).span;
427        let false_ = self.constant_bool(span, false);
428        for flag in self.drop_flags.iter().flatten() {
429            self.patch.add_assign(loc, Place::from(*flag), false_.clone());
430        }
431    }
432
433    fn drop_flags_for_fn_rets(&mut self) {
434        for (bb, data) in self.body.basic_blocks.iter_enumerated() {
435            if let TerminatorKind::Call {
436                destination,
437                target: Some(tgt),
438                unwind: UnwindAction::Cleanup(_),
439                ..
440            } = data.terminator.kind
441            {
442                assert!(!self.patch.is_term_patched(bb));
443
444                let loc = tgt.start_location();
445                let path = self.move_data().rev_lookup.find(destination.as_ref());
446                on_lookup_result_bits(self.move_data(), path, |child| {
447                    self.set_drop_flag(loc, child, DropFlagState::Present)
448                });
449            }
450        }
451    }
452
453    fn drop_flags_for_args(&mut self) {
454        let loc = Location::START;
455        rustc_mir_dataflow::drop_flag_effects_for_function_entry(
456            self.body,
457            &self.env.move_data,
458            |path, ds| {
459                self.set_drop_flag(loc, path, ds);
460            },
461        )
462    }
463
464    fn drop_flags_for_locs(&mut self) {
465        // We intentionally iterate only over the *old* basic blocks.
466        //
467        // Basic blocks created by drop elaboration update their
468        // drop flags by themselves, to avoid the drop flags being
469        // clobbered before they are read.
470
471        for (bb, data) in self.body.basic_blocks.iter_enumerated() {
472            debug!("drop_flags_for_locs({:?})", data);
473            for i in 0..(data.statements.len() + 1) {
474                debug!("drop_flag_for_locs: stmt {}", i);
475                if i == data.statements.len() {
476                    match data.terminator.kind {
477                        TerminatorKind::Drop { .. } => {
478                            // drop elaboration should handle that by itself
479                            continue;
480                        }
481                        TerminatorKind::UnwindResume => {
482                            // It is possible for `Resume` to be patched
483                            // (in particular it can be patched to be replaced with
484                            // a Goto; see `MirPatch::new`).
485                        }
486                        _ => {
487                            assert!(!self.patch.is_term_patched(bb));
488                        }
489                    }
490                }
491                let loc = Location { block: bb, statement_index: i };
492                rustc_mir_dataflow::drop_flag_effects_for_location(
493                    self.body,
494                    &self.env.move_data,
495                    loc,
496                    |path, ds| self.set_drop_flag(loc, path, ds),
497                )
498            }
499
500            // There may be a critical edge after this call,
501            // so mark the return as initialized *before* the
502            // call.
503            if let TerminatorKind::Call {
504                destination,
505                target: Some(_),
506                unwind:
507                    UnwindAction::Continue | UnwindAction::Unreachable | UnwindAction::Terminate(_),
508                ..
509            } = data.terminator.kind
510            {
511                assert!(!self.patch.is_term_patched(bb));
512
513                let loc = Location { block: bb, statement_index: data.statements.len() };
514                let path = self.move_data().rev_lookup.find(destination.as_ref());
515                on_lookup_result_bits(self.move_data(), path, |child| {
516                    self.set_drop_flag(loc, child, DropFlagState::Present)
517                });
518            }
519        }
520    }
521}