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