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
21pub(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 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 PassPolicy::Required
92 }
93}
94
95#[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 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 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 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 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 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 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 continue;
480 }
481 TerminatorKind::UnwindResume => {
482 }
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 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}