]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/elaborate_drops.rs
Auto merge of #84944 - lcnr:obligation-dedup, r=jackh726
[rust.git] / compiler / rustc_mir_transform / src / elaborate_drops.rs
1 use crate::MirPass;
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};
15 use rustc_span::Span;
16 use rustc_target::abi::VariantIdx;
17 use std::fmt;
18
19 pub struct ElaborateDrops;
20
21 impl<'tcx> MirPass<'tcx> for ElaborateDrops {
22     fn phase_change(&self) -> Option<MirPhase> {
23         Some(MirPhase::DropLowering)
24     }
25
26     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
27         debug!("elaborate_drops({:?} @ {:?})", body.source, body.span);
28
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(
35                     body.span,
36                     "No `move_errors` should be allowed in MIR borrowck",
37                 );
38                 move_data
39             }
40         };
41         let elaborate_patch = {
42             let body = &*body;
43             let env = MoveDataParamEnv { move_data, param_env };
44             let dead_unwinds = find_dead_unwinds(tcx, body, &env);
45
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);
52
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);
60
61             ElaborateDropsCtxt {
62                 tcx,
63                 body,
64                 env: &env,
65                 init_data: InitializationData { inits, uninits },
66                 drop_flags: Default::default(),
67                 patch: MirPatch::new(body),
68             }
69             .elaborate()
70         };
71         elaborate_patch.apply(body);
72     }
73 }
74
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>(
79     tcx: TyCtxt<'tcx>,
80     body: &Body<'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,
96             _ => continue,
97         };
98
99         debug!("find_dead_unwinds @ {:?}: {:?}", bb, bb_data);
100
101         let LookupResult::Exact(path) = env.move_data.rev_lookup.find(place.as_ref()) else {
102             debug!("find_dead_unwinds: has parent; skipping");
103             continue;
104         };
105
106         flow_inits.seek_before_primary_effect(body.terminator_loc(bb));
107         debug!(
108             "find_dead_unwinds @ {:?}: path({:?})={:?}; init_data={:?}",
109             bb,
110             place,
111             path,
112             flow_inits.get()
113         );
114
115         let mut maybe_live = false;
116         on_all_drop_children_bits(tcx, body, &env, path, |child| {
117             maybe_live |= flow_inits.contains(child);
118         });
119
120         debug!("find_dead_unwinds @ {:?}: maybe_live={}", bb, maybe_live);
121         if !maybe_live {
122             dead_unwinds.insert(bb);
123         }
124     }
125
126     dead_unwinds
127 }
128
129 struct InitializationData<'mir, 'tcx> {
130     inits: ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
131     uninits: ResultsCursor<'mir, 'tcx, MaybeUninitializedPlaces<'mir, 'tcx>>,
132 }
133
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);
138     }
139
140     fn maybe_live_dead(&self, path: MovePathIndex) -> (bool, bool) {
141         (self.inits.contains(path), self.uninits.contains(path))
142     }
143 }
144
145 struct Elaborator<'a, 'b, 'tcx> {
146     ctxt: &'a mut ElaborateDropsCtxt<'b, 'tcx>,
147 }
148
149 impl fmt::Debug for Elaborator<'_, '_, '_> {
150     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
151         Ok(())
152     }
153 }
154
155 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for Elaborator<'a, '_, 'tcx> {
156     type Path = MovePathIndex;
157
158     fn patch(&mut self) -> &mut MirPatch<'tcx> {
159         &mut self.ctxt.patch
160     }
161
162     fn body(&self) -> &'a Body<'tcx> {
163         self.ctxt.body
164     }
165
166     fn tcx(&self) -> TyCtxt<'tcx> {
167         self.ctxt.tcx
168     }
169
170     fn param_env(&self) -> ty::ParamEnv<'tcx> {
171         self.ctxt.param_env()
172     }
173
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));
184                     some_live |= live;
185                     some_dead |= dead;
186                     children_count += 1;
187                 });
188                 ((some_live, some_dead), children_count != 1)
189             }
190         };
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,
196         }
197     }
198
199     fn clear_drop_flag(&mut self, loc: Location, path: Self::Path, mode: DropFlagMode) {
200         match mode {
201             DropFlagMode::Shallow => {
202                 self.ctxt.set_drop_flag(loc, path, DropFlagState::Absent);
203             }
204             DropFlagMode::Deep => {
205                 on_all_children_bits(
206                     self.tcx(),
207                     self.body(),
208                     self.ctxt.move_data(),
209                     path,
210                     |child| self.ctxt.set_drop_flag(loc, child, DropFlagState::Absent),
211                 );
212             }
213         }
214     }
215
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,
219             _ => false,
220         })
221     }
222
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");
228                 offset == index
229             }
230             _ => false,
231         })
232     }
233
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
237         })
238     }
239
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,
243             _ => false,
244         })
245     }
246
247     fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>> {
248         self.ctxt.drop_flag(path).map(Operand::Copy)
249     }
250 }
251
252 struct ElaborateDropsCtxt<'a, 'tcx> {
253     tcx: TyCtxt<'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>,
259 }
260
261 impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
262     fn move_data(&self) -> &'b MoveData<'tcx> {
263         &self.env.move_data
264     }
265
266     fn param_env(&self) -> ty::ParamEnv<'tcx> {
267         self.env.param_env
268     }
269
270     fn create_drop_flag(&mut self, index: MovePathIndex, span: Span) {
271         let tcx = self.tcx;
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));
275     }
276
277     fn drop_flag(&mut self, index: MovePathIndex) -> Option<Place<'tcx>> {
278         self.drop_flags.get(&index).map(|t| Place::from(*t))
279     }
280
281     /// create a patch that elaborates all drops in the input
282     /// MIR.
283     fn elaborate(mut self) -> MirPatch<'tcx> {
284         self.collect_drop_flags();
285
286         self.elaborate_drops();
287
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();
292
293         self.patch
294     }
295
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,
302                 _ => continue,
303             };
304
305             self.init_data.seek_before(self.body.terminator_loc(bb));
306
307             let path = self.move_data().rev_lookup.find(place.as_ref());
308             debug!("collect_drop_flags: {:?}, place {:?} ({:?})", bb, place, path);
309
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);
315                     if maybe_dead {
316                         self.tcx.sess.delay_span_bug(
317                             terminator.source_info.span,
318                             &format!(
319                                 "drop of untracked, uninitialized value {:?}, place {:?} ({:?})",
320                                 bb, place, path,
321                             ),
322                         );
323                     }
324                     continue;
325                 }
326             };
327
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);
330                 debug!(
331                     "collect_drop_flags: collecting {:?} from {:?}@{:?} - {:?}",
332                     child,
333                     place,
334                     path,
335                     (maybe_live, maybe_dead)
336                 );
337                 if maybe_live && maybe_dead {
338                     self.create_drop_flag(child, terminator.source_info.span)
339                 }
340             });
341         }
342     }
343
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();
348
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,
357                             place,
358                             path,
359                             target,
360                             if data.is_cleanup {
361                                 Unwind::InCleanup
362                             } else {
363                                 Unwind::To(Option::unwrap_or(unwind, resume_block))
364                             },
365                             bb,
366                         ),
367                         LookupResult::Parent(..) => {
368                             self.tcx.sess.delay_span_bug(
369                                 terminator.source_info.span,
370                                 &format!("drop of untracked value {:?}", bb),
371                             );
372                         }
373                     }
374                 }
375                 TerminatorKind::DropAndReplace { place, ref value, target, unwind } => {
376                     assert!(!data.is_cleanup);
377
378                     self.elaborate_replace(loc, place, value, target, unwind);
379                 }
380                 _ => continue,
381             }
382         }
383     }
384
385     /// Elaborate a MIR `replace` terminator. This instruction
386     /// is not directly handled by codegen, and therefore
387     /// must be desugared.
388     ///
389     /// The desugaring drops the location if needed, and then writes
390     /// the value (including setting the drop flag) over it in *both* arms.
391     ///
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(
398         &mut self,
399         loc: Location,
400         place: Place<'tcx>,
401         value: &Operand<'tcx>,
402         target: BasicBlock,
403         unwind: Option<BasicBlock>,
404     ) {
405         let bb = loc.block;
406         let data = &self.body[bb];
407         let terminator = data.terminator();
408         assert!(!data.is_cleanup, "DropAndReplace in unwind path not supported");
409
410         let assign = Statement {
411             kind: StatementKind::Assign(Box::new((place, Rvalue::Use(value.clone())))),
412             source_info: terminator.source_info,
413         };
414
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 },
420                 ..*terminator
421             }),
422             is_cleanup: true,
423         });
424
425         let target = self.patch.new_block(BasicBlockData {
426             statements: vec![assign],
427             terminator: Some(Terminator { kind: TerminatorKind::Goto { target }, ..*terminator }),
428             is_cleanup: false,
429         });
430
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);
435                 elaborate_drop(
436                     &mut Elaborator { ctxt: self },
437                     terminator.source_info,
438                     place,
439                     path,
440                     target,
441                     Unwind::To(unwind),
442                     bb,
443                 );
444                 on_all_children_bits(self.tcx, self.body, self.move_data(), path, |child| {
445                     self.set_drop_flag(
446                         Location { block: target, statement_index: 0 },
447                         child,
448                         DropFlagState::Present,
449                     );
450                     self.set_drop_flag(
451                         Location { block: unwind, statement_index: 0 },
452                         child,
453                         DropFlagState::Present,
454                     );
455                 });
456             }
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(
462                     bb,
463                     TerminatorKind::Drop { place, target, unwind: Some(unwind) },
464                 );
465             }
466         }
467     }
468
469     fn constant_bool(&self, span: Span, val: bool) -> Rvalue<'tcx> {
470         Rvalue::Use(Operand::Constant(Box::new(Constant {
471             span,
472             user_ty: None,
473             literal: ty::Const::from_bool(self.tcx, val).into(),
474         })))
475     }
476
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);
482         }
483     }
484
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());
491         }
492     }
493
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)),
498                 cleanup: Some(_),
499                 ..
500             } = data.terminator().kind
501             {
502                 assert!(!self.patch.is_patched(bb));
503
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)
508                 });
509             }
510         }
511     }
512
513     fn drop_flags_for_args(&mut self) {
514         let loc = Location::START;
515         rustc_mir_dataflow::drop_flag_effects_for_function_entry(
516             self.tcx,
517             self.body,
518             self.env,
519             |path, ds| {
520                 self.set_drop_flag(loc, path, ds);
521             },
522         )
523     }
524
525     fn drop_flags_for_locs(&mut self) {
526         // We intentionally iterate only over the *old* basic blocks.
527         //
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.
531
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
541                             continue;
542                         }
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;
551                         }
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`).
556                         }
557                         _ => {
558                             assert!(!self.patch.is_patched(bb));
559                         }
560                     }
561                 }
562                 let loc = Location { block: bb, statement_index: i };
563                 rustc_mir_dataflow::drop_flag_effects_for_location(
564                     self.tcx,
565                     self.body,
566                     self.env,
567                     loc,
568                     |path, ds| {
569                         if ds == DropFlagState::Absent || allow_initializations {
570                             self.set_drop_flag(loc, path, ds)
571                         }
572                     },
573                 )
574             }
575
576             // There may be a critical edge after this call,
577             // so mark the return as initialized *before* the
578             // call.
579             if let TerminatorKind::Call {
580                 destination: Some((ref place, _)), cleanup: None, ..
581             } = data.terminator().kind
582             {
583                 assert!(!self.patch.is_patched(bb));
584
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)
589                 });
590             }
591         }
592     }
593 }