1use std::{fmt, iter, mem};
2
3use itertools::Itertools;
4use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
5use rustc_data_structures::thin_vec::ThinVec;
6use rustc_hir::lang_items::LangItem;
7use rustc_hir::{CoroutineDesugaring, CoroutineKind};
8use rustc_index::Idx;
9use rustc_middle::mir::*;
10use rustc_middle::ty::adjustment::PointerCoercion;
11use rustc_middle::ty::util::{Discr, IntTypeExt};
12use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt};
13use rustc_middle::{bug, span_bug};
14use rustc_span::{DUMMY_SP, dummy_spanned};
15use tracing::{debug, instrument};
16
17use crate::coroutine::CTX_ARG;
18use crate::patch::MirPatch;
19
20#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropStyle {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
DropStyle::Dead => "Dead",
DropStyle::Static => "Static",
DropStyle::Conditional => "Conditional",
DropStyle::Open => "Open",
})
}
}Debug)]
22pub(crate) enum DropStyle {
23 Dead,
25
26 Static,
29
30 Conditional,
32
33 Open,
39}
40
41#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropFlagMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
DropFlagMode::Shallow => "Shallow",
DropFlagMode::Deep => "Deep",
})
}
}Debug)]
43pub(crate) enum DropFlagMode {
44 Shallow,
46 Deep,
48}
49
50#[derive(#[automatically_derived]
impl ::core::marker::Copy for Unwind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Unwind {
#[inline]
fn clone(&self) -> Unwind {
let _: ::core::clone::AssertParamIsClone<BasicBlock>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Unwind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Unwind::To(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "To",
&__self_0),
Unwind::InCleanup =>
::core::fmt::Formatter::write_str(f, "InCleanup"),
}
}
}Debug)]
52pub(crate) enum Unwind {
53 To(BasicBlock),
55 InCleanup,
57}
58
59impl Unwind {
60 fn is_cleanup(self) -> bool {
61 match self {
62 Unwind::To(..) => false,
63 Unwind::InCleanup => true,
64 }
65 }
66
67 fn into_action(self) -> UnwindAction {
68 match self {
69 Unwind::To(bb) => UnwindAction::Cleanup(bb),
70 Unwind::InCleanup => UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
71 }
72 }
73
74 fn map<F>(self, f: F) -> Self
75 where
76 F: FnOnce(BasicBlock) -> BasicBlock,
77 {
78 match self {
79 Unwind::To(bb) => Unwind::To(f(bb)),
80 Unwind::InCleanup => Unwind::InCleanup,
81 }
82 }
83}
84
85pub(crate) trait DropElaborator<'a, 'tcx>: fmt::Debug {
86 type Path: Copy + fmt::Debug;
92
93 fn patch_ref(&self) -> &MirPatch<'tcx>;
96 fn patch(&mut self) -> &mut MirPatch<'tcx>;
97 fn body(&self) -> &'a Body<'tcx>;
98 fn tcx(&self) -> TyCtxt<'tcx>;
99 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
100 fn allow_async_drops(&self) -> bool;
101
102 fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
106
107 fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
109
110 fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);
115
116 fn field_subpath(&self, path: Self::Path, field: FieldIdx) -> Option<Self::Path>;
122
123 fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
129
130 fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path>;
134
135 fn array_subpath(&self, path: Self::Path, index: u64, size: u64) -> Option<Self::Path>;
141}
142
143#[derive(#[automatically_derived]
impl<'a, 'b, 'tcx, D: ::core::fmt::Debug> ::core::fmt::Debug for
DropCtxt<'a, 'b, 'tcx, D> where D: DropElaborator<'b, 'tcx>,
D::Path: ::core::fmt::Debug {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["elaborator", "source_info", "place", "path", "succ", "unwind",
"dropline"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.elaborator, &self.source_info, &self.place, &self.path,
&self.succ, &self.unwind, &&self.dropline];
::core::fmt::Formatter::debug_struct_fields_finish(f, "DropCtxt",
names, values)
}
}Debug)]
144struct DropCtxt<'a, 'b, 'tcx, D>
145where
146 D: DropElaborator<'b, 'tcx>,
147{
148 elaborator: &'a mut D,
149
150 source_info: SourceInfo,
151
152 place: Place<'tcx>,
153 path: D::Path,
154 succ: BasicBlock,
155 unwind: Unwind,
156 dropline: Option<BasicBlock>,
157}
158
159pub(crate) fn elaborate_drop<'b, 'tcx, D>(
168 elaborator: &mut D,
169 source_info: SourceInfo,
170 place: Place<'tcx>,
171 path: D::Path,
172 succ: BasicBlock,
173 unwind: Unwind,
174 bb: BasicBlock,
175 dropline: Option<BasicBlock>,
176) where
177 D: DropElaborator<'b, 'tcx>,
178 'tcx: 'b,
179{
180 DropCtxt { elaborator, source_info, place, path, succ, unwind, dropline }.elaborate_drop(bb)
181}
182
183impl<'a, 'b, 'tcx, D> DropCtxt<'a, 'b, 'tcx, D>
184where
185 D: DropElaborator<'b, 'tcx>,
186 'tcx: 'b,
187{
188 x;#[instrument(level = "trace", skip(self), ret)]
189 fn place_ty(&self, place: Place<'tcx>) -> Ty<'tcx> {
190 if place.local < self.elaborator.body().local_decls.next_index() {
191 place.ty(self.elaborator.body(), self.tcx()).ty
192 } else {
193 PlaceTy::from_ty(self.elaborator.patch_ref().local_ty(place.local))
195 .multi_projection_ty(self.elaborator.tcx(), place.projection)
196 .ty
197 }
198 }
199
200 fn tcx(&self) -> TyCtxt<'tcx> {
201 self.elaborator.tcx()
202 }
203
204 x;#[instrument(level = "debug", skip(self), ret)]
229 fn build_async_drop(
230 &mut self,
231 place: Place<'tcx>,
232 drop_ty: Ty<'tcx>,
233 succ: BasicBlock,
234 unwind: Unwind,
235 dropline: Option<BasicBlock>,
236 call_destructor_only: bool,
237 ) -> BasicBlock {
238 let tcx = self.tcx();
239 let span = self.source_info.span;
240 let obj_ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, drop_ty);
241
242 let async_drop_fn_def_id = if call_destructor_only {
243 let async_drop_trait = tcx.require_lang_item(LangItem::AsyncDrop, span);
245 tcx.associated_item_def_ids(async_drop_trait)[0]
246 } else {
247 tcx.require_lang_item(LangItem::AsyncDropInPlace, span)
249 };
250
251 let fut_ty = tcx
252 .instantiate_bound_regions_with_erased(
253 Ty::new_fn_def(tcx, async_drop_fn_def_id, ty::Binder::dummy([drop_ty])).fn_sig(tcx),
255 )
256 .output();
257 let fut = self.new_temp(fut_ty);
258
259 let succ_with_dead = self.new_block_with_statements(
263 unwind,
264 vec![self.storage_dead(fut)],
265 TerminatorKind::Goto { target: succ },
266 );
267 let dropline_with_dead = dropline.map(|target| {
268 self.new_block_with_statements(
269 unwind,
270 vec![self.storage_dead(fut)],
271 TerminatorKind::Goto { target },
272 )
273 });
274 let unwind_with_dead = unwind.map(|target| {
275 self.new_block_with_statements(
276 Unwind::InCleanup,
277 vec![self.storage_dead(fut)],
278 TerminatorKind::Goto { target },
279 )
280 });
281
282 let coroutine_kind = self.elaborator.body().coroutine_kind().unwrap();
284 let yield_value = match coroutine_kind {
285 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
287 let full_yield_ty = self.elaborator.body().yield_ty().unwrap();
288 let ty::Adt(_poll_adt, args) = *full_yield_ty.kind() else { bug!() };
289 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
290 let yield_ty = args.type_at(0);
291 Operand::unevaluated_constant(
292 tcx,
293 tcx.require_lang_item(LangItem::AsyncGenPending, span),
294 tcx.mk_args(&[yield_ty.into()]),
295 span,
296 )
297 }
298 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
300 Operand::zero_sized_constant(tcx.types.unit, span)
301 }
302 _ => panic!("unexpected coroutine for async drop {coroutine_kind:?}"),
304 };
305
306 let panic_bb = self.build_resumed_after_drop_abort_block(unwind_with_dead, coroutine_kind);
315 let (drop_pin_bb, drop_resume_bb, drop_drop_bb) = self.build_pin_poll_yield_loop(
316 CTX_ARG.into(),
317 fut.into(),
318 yield_value.clone(),
319 dropline_with_dead.unwrap_or(succ_with_dead),
322 unwind_with_dead,
323 );
324 self.elaborator
325 .patch()
326 .patch_terminator(drop_resume_bb, TerminatorKind::Goto { target: panic_bb });
327 self.elaborator
328 .patch()
329 .patch_terminator(drop_drop_bb, TerminatorKind::Goto { target: drop_pin_bb });
330
331 let succ_yield_loop = if dropline_with_dead.is_some() {
338 let (pin_bb, resume_bb, drop_bb) = self.build_pin_poll_yield_loop(
339 CTX_ARG.into(),
340 fut.into(),
341 yield_value,
342 succ_with_dead,
344 unwind_with_dead,
345 );
346 self.elaborator
347 .patch()
348 .patch_terminator(resume_bb, TerminatorKind::Goto { target: pin_bb });
349 self.elaborator
350 .patch()
351 .patch_terminator(drop_bb, TerminatorKind::Goto { target: drop_pin_bb });
352 pin_bb
353 } else {
354 drop_pin_bb
356 };
357
358 let pin_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, span));
362 let pin_obj_ty = Ty::new_adt(tcx, pin_adt_def, tcx.mk_args(&[obj_ref_ty.into()]));
363 let pin_obj_local = self.new_temp(pin_obj_ty);
365 let drop_arg = if call_destructor_only {
366 Operand::Move(pin_obj_local.into())
368 } else {
369 Operand::Copy(tcx.mk_place_field(pin_obj_local.into(), FieldIdx::ZERO, obj_ref_ty))
371 };
372 let call_drop_bb = self.new_block_with_statements(
373 unwind_with_dead,
374 vec![self.storage_live(fut)],
375 TerminatorKind::Call {
376 func: Operand::function_handle(
378 tcx,
379 async_drop_fn_def_id,
380 ty::Binder::dummy([drop_ty.into()]),
381 span,
382 ),
383 args: [dummy_spanned(drop_arg)].into(),
384 destination: fut.into(),
385 target: Some(succ_yield_loop),
386 unwind: unwind_with_dead.into_action(),
387 call_source: CallSource::Misc,
388 fn_span: self.source_info.span,
389 },
390 );
391
392 let obj_ref_place = Place::from(self.new_temp(obj_ref_ty));
394 let pin_obj_new_unchecked_fn = tcx.require_lang_item(LangItem::PinNewUnchecked, span);
395 let assign_obj_ref_place = self.assign(
396 obj_ref_place,
397 Rvalue::Ref(
398 tcx.lifetimes.re_erased,
399 BorrowKind::Mut { kind: MutBorrowKind::Default },
400 place,
401 ),
402 );
403 self.new_block_with_statements(
404 unwind,
405 vec![assign_obj_ref_place],
406 TerminatorKind::Call {
407 func: Operand::function_handle(
408 tcx,
409 pin_obj_new_unchecked_fn,
410 ty::Binder::dummy([obj_ref_ty.into()]),
412 span,
413 ),
414 args: [dummy_spanned(Operand::Move(obj_ref_place))].into(),
415 destination: pin_obj_local.into(),
416 target: Some(call_drop_bb),
417 unwind: unwind.into_action(),
418 call_source: CallSource::Misc,
419 fn_span: span,
420 },
421 )
422 }
423
424 fn build_resumed_after_drop_abort_block(
425 &mut self,
426 unwind: Unwind,
427 coroutine_kind: CoroutineKind,
428 ) -> BasicBlock {
429 let tcx = self.tcx();
430 let panic_bb = self.new_block(unwind, TerminatorKind::Unreachable);
431 let msg = AssertMessage::ResumedAfterDrop(coroutine_kind);
432 let false_op = Operand::Constant(Box::new(ConstOperand {
433 span: self.source_info.span,
434 user_ty: None,
435 const_: Const::from_bool(tcx, false),
436 }));
437 self.elaborator.patch().patch_terminator(
438 panic_bb,
439 TerminatorKind::Assert {
440 cond: false_op,
441 expected: true,
442 msg: Box::new(msg),
443 target: panic_bb,
444 unwind: unwind.into_action(),
445 },
446 );
447 panic_bb
448 }
449
450 x;#[instrument(level = "trace", skip(self), ret)]
466 fn build_pin_poll_yield_loop(
467 &mut self,
468 resume_place: Place<'tcx>,
469 fut_place: Place<'tcx>,
470 yield_value: Operand<'tcx>,
471 succ: BasicBlock,
472 unwind: Unwind,
473 ) -> (BasicBlock, BasicBlock, BasicBlock) {
474 let tcx = self.tcx();
475 let source_info = self.source_info;
476
477 let resume_arg_ty = resume_place.ty(self.elaborator.body(), tcx).ty;
478 let context_ref_ty = Ty::new_task_context(tcx);
479
480 let poll_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Poll, source_info.span));
481 let poll_enum = Ty::new_adt(tcx, poll_adt_def, tcx.mk_args(&[tcx.types.unit.into()]));
482
483 let fut_ty = self.elaborator.patch_ref().local_ty(fut_place.local);
484 let fut_ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, fut_ty);
485
486 let pin_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, source_info.span));
487 let fut_pin_ty = Ty::new_adt(tcx, pin_adt_def, tcx.mk_args(&[fut_ref_ty.into()]));
488
489 let yield_resume_local = self.new_temp(resume_arg_ty);
492 let resume_bb = self.new_block_with_statements(
493 unwind,
494 vec![
495 self.assign(
496 resume_place,
497 Rvalue::Use(Operand::Move(yield_resume_local.into()), WithRetag::Yes),
498 ),
499 self.storage_dead(yield_resume_local),
500 ],
501 TerminatorKind::Unreachable,
503 );
504 let dropline_bb = self.new_block_with_statements(
505 unwind,
506 vec![
507 self.assign(
508 resume_place,
509 Rvalue::Use(Operand::Move(yield_resume_local.into()), WithRetag::Yes),
510 ),
511 self.storage_dead(yield_resume_local),
512 ],
513 TerminatorKind::Unreachable,
515 );
516 let yield_bb = self.new_block_with_statements(
517 unwind,
518 vec![self.storage_live(yield_resume_local)],
519 TerminatorKind::Yield {
520 value: yield_value,
521 resume: resume_bb,
522 resume_arg: yield_resume_local.into(),
523 drop: Some(dropline_bb),
524 },
525 );
526
527 let poll_unit_local = self.new_temp(poll_enum);
528 let switch_bb = {
529 let poll_ready_variant =
530 tcx.require_lang_item(LangItem::PollReady, self.source_info.span);
531 let poll_ready_variant_idx = poll_adt_def.variant_index_with_id(poll_ready_variant);
532 let poll_pending_variant =
533 tcx.require_lang_item(LangItem::PollPending, self.source_info.span);
534 let poll_pending_variant_idx = poll_adt_def.variant_index_with_id(poll_pending_variant);
535
536 let Discr { val: poll_ready_discr, ty: poll_discr_ty } =
537 poll_enum.discriminant_for_variant(tcx, poll_ready_variant_idx).unwrap();
538 let Discr { val: poll_pending_discr, ty: _ } =
539 poll_enum.discriminant_for_variant(tcx, poll_pending_variant_idx).unwrap();
540
541 let poll_discr_local = self.new_temp(poll_discr_ty);
542 let otherwise_bb = self.elaborator.patch().unreachable_no_cleanup_block();
543 self.new_block_with_statements(
544 unwind,
545 vec![
546 self.assign(
547 poll_discr_local.into(),
548 Rvalue::Discriminant(poll_unit_local.into()),
549 ),
550 ],
551 TerminatorKind::SwitchInt {
552 discr: Operand::Move(poll_discr_local.into()),
553 targets: SwitchTargets::new(
554 [
555 (poll_ready_discr, succ),
557 (poll_pending_discr, yield_bb),
559 ]
560 .into_iter(),
561 otherwise_bb,
563 ),
564 },
565 )
566 };
567
568 let fut_pin_local = self.new_temp(fut_pin_ty);
569 let context_ref_local = self.new_temp(context_ref_ty);
570
571 let poll_fn = tcx.require_lang_item(LangItem::FuturePoll, source_info.span);
572 let poll_bb = self.new_block_with_statements(
573 unwind,
574 Vec::new(),
575 TerminatorKind::Call {
576 func: Operand::function_handle(
578 tcx,
579 poll_fn,
580 ty::Binder::dummy([fut_ty.into()]),
581 source_info.span,
582 ),
583 args: [
584 dummy_spanned(Operand::Move(fut_pin_local.into())),
585 dummy_spanned(Operand::Move(context_ref_local.into())),
586 ]
587 .into(),
588 destination: poll_unit_local.into(),
589 target: Some(switch_bb),
590 unwind: unwind.into_action(),
591 call_source: CallSource::Misc,
592 fn_span: source_info.span,
593 },
594 );
595
596 let get_context_fn = tcx.require_lang_item(LangItem::GetContext, source_info.span);
597 let get_context_bb = {
598 let entry_resume_local = self.new_temp(resume_arg_ty);
601 self.new_block_with_statements(
602 unwind,
603 vec![self.assign(
604 entry_resume_local.into(),
605 Rvalue::Use(Operand::Move(resume_place), WithRetag::Yes),
606 )],
607 TerminatorKind::Call {
608 func: Operand::function_handle(
609 tcx,
610 get_context_fn,
611 ty::Binder::dummy([
613 tcx.lifetimes.re_erased.into(),
614 tcx.lifetimes.re_erased.into(),
615 ]),
616 source_info.span,
617 ),
618 args: [dummy_spanned(Operand::Move(entry_resume_local.into()))].into(),
619 destination: context_ref_local.into(),
620 target: Some(poll_bb),
621 unwind: unwind.into_action(),
622 call_source: CallSource::Misc,
623 fn_span: source_info.span,
624 },
625 )
626 };
627
628 let fut_ref_local = self.new_temp(fut_ref_ty);
629 let fut_pin_new_unchecked_fn =
630 tcx.require_lang_item(LangItem::PinNewUnchecked, source_info.span);
631 let pin_bb = self.new_block_with_statements(
632 unwind,
633 vec![self.assign(
634 fut_ref_local.into(),
635 Rvalue::Ref(
636 tcx.lifetimes.re_erased,
637 BorrowKind::Mut { kind: MutBorrowKind::Default },
638 fut_place,
639 ),
640 )],
641 TerminatorKind::Call {
642 func: Operand::function_handle(
643 tcx,
644 fut_pin_new_unchecked_fn,
645 ty::Binder::dummy([fut_ref_ty.into()]),
646 source_info.span,
647 ),
648 args: [dummy_spanned(Operand::Move(fut_ref_local.into()))].into(),
649 destination: fut_pin_local.into(),
650 target: Some(get_context_bb),
651 unwind: unwind.into_action(),
652 call_source: CallSource::Misc,
653 fn_span: source_info.span,
654 },
655 );
656
657 (pin_bb, resume_bb, dropline_bb)
658 }
659
660 fn build_drop(&mut self, bb: BasicBlock) {
661 let drop_ty = self.place_ty(self.place);
662 if !self.elaborator.patch_ref().block(self.elaborator.body(), bb).is_cleanup
663 && self.check_if_can_async_drop(drop_ty, false)
664 {
665 let async_drop_bb = self.build_async_drop(
666 self.place,
667 drop_ty,
668 self.succ,
669 self.unwind,
670 self.dropline,
671 false,
672 );
673 self.elaborator
674 .patch()
675 .patch_terminator(bb, TerminatorKind::Goto { target: async_drop_bb });
676 } else {
677 self.elaborator.patch().patch_terminator(
678 bb,
679 TerminatorKind::Drop {
680 place: self.place,
681 target: self.succ,
682 unwind: self.unwind.into_action(),
683 replace: false,
684 drop: None,
685 },
686 );
687 }
688 }
689
690 fn check_if_can_async_drop(&mut self, drop_ty: Ty<'tcx>, call_destructor_only: bool) -> bool {
692 if !self.elaborator.allow_async_drops()
693 || !self
694 .elaborator
695 .body()
696 .coroutine
697 .as_ref()
698 .is_some_and(|ck| ck.coroutine_kind.is_async_desugaring())
699 {
700 return false;
701 }
702
703 if drop_ty == self.place_ty(Local::arg(0).into()) {
704 return false;
705 }
706
707 let is_async_drop_feature_enabled = if self.tcx().features().async_drop() {
708 true
709 } else {
710 if let ty::Adt(adt_def, _) = drop_ty.kind() {
712 !adt_def.did().is_local() && adt_def.async_destructor(self.tcx()).is_some()
713 } else {
714 false
715 }
716 };
717
718 if !is_async_drop_feature_enabled {
722 return false;
723 }
724
725 let needs_async_drop = if call_destructor_only {
726 drop_ty.is_async_drop(self.tcx(), self.elaborator.typing_env())
727 } else {
728 drop_ty.needs_async_drop(self.tcx(), self.elaborator.typing_env())
729 };
730
731 if needs_async_drop && self.tcx().features().staged_api() {
733 ::rustc_middle::util::bug::span_bug_fmt(self.source_info.span,
format_args!("don\'t use async drop in libstd, it becomes insta-stable"));span_bug!(
734 self.source_info.span,
735 "don't use async drop in libstd, it becomes insta-stable"
736 );
737 }
738
739 needs_async_drop
740 }
741
742 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("elaborate_drop",
"rustc_mir_transform::elaborate_drop",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_transform/src/elaborate_drop.rs"),
::tracing_core::__macro_support::Option::Some(760u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_transform::elaborate_drop"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self")
}> =
::tracing::__macro_support::FieldName::new("self");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("bb")
}> =
::tracing::__macro_support::FieldName::new("bb");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bb)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
match self.elaborator.drop_style(self.path, DropFlagMode::Deep) {
DropStyle::Dead => {
self.elaborator.patch().patch_terminator(bb,
TerminatorKind::Goto { target: self.succ });
}
DropStyle::Static => { self.build_drop(bb); }
DropStyle::Conditional => {
let drop_bb = self.complete_drop(self.succ, self.unwind);
self.elaborator.patch().patch_terminator(bb,
TerminatorKind::Goto { target: drop_bb });
}
DropStyle::Open => {
let drop_bb = self.open_drop();
self.elaborator.patch().patch_terminator(bb,
TerminatorKind::Goto { target: drop_bb });
}
}
}
}
}#[instrument(level = "debug")]
761 fn elaborate_drop(&mut self, bb: BasicBlock) {
762 match self.elaborator.drop_style(self.path, DropFlagMode::Deep) {
763 DropStyle::Dead => {
764 self.elaborator
765 .patch()
766 .patch_terminator(bb, TerminatorKind::Goto { target: self.succ });
767 }
768 DropStyle::Static => {
769 self.build_drop(bb);
770 }
771 DropStyle::Conditional => {
772 let drop_bb = self.complete_drop(self.succ, self.unwind);
773 self.elaborator
774 .patch()
775 .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
776 }
777 DropStyle::Open => {
778 let drop_bb = self.open_drop();
779 self.elaborator
780 .patch()
781 .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
782 }
783 }
784 }
785
786 fn move_paths_for_fields(
789 &self,
790 base_place: Place<'tcx>,
791 variant_path: D::Path,
792 variant: &'tcx ty::VariantDef,
793 args: GenericArgsRef<'tcx>,
794 ) -> Vec<(Place<'tcx>, Option<D::Path>)> {
795 variant
796 .fields
797 .iter_enumerated()
798 .map(|(field_idx, field)| {
799 let subpath = self.elaborator.field_subpath(variant_path, field_idx);
800 let tcx = self.tcx();
801
802 match self.elaborator.typing_env().typing_mode().assert_not_erased() {
803 ty::TypingMode::PostAnalysis | ty::TypingMode::Codegen => {}
804 ty::TypingMode::Coherence
805 | ty::TypingMode::Typeck { .. }
806 | ty::TypingMode::PostTypeckUntilBorrowck { .. }
807 | ty::TypingMode::PostBorrowck { .. } => {
808 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
809 }
810 }
811
812 let field_ty = field.ty(tcx, args);
813 let field_ty = tcx
816 .try_normalize_erasing_regions(self.elaborator.typing_env(), field_ty)
817 .unwrap_or(field_ty.skip_norm_wip());
818
819 (tcx.mk_place_field(base_place, field_idx, field_ty), subpath)
820 })
821 .filter(|path| self.should_retain_for_ladder(path))
822 .collect()
823 }
824
825 x;#[instrument(level = "debug", skip(self), ret)]
826 fn drop_subpath(
827 &mut self,
828 place: Place<'tcx>,
829 path: Option<D::Path>,
830 succ: BasicBlock,
831 unwind: Unwind,
832 dropline: Option<BasicBlock>,
833 ) -> BasicBlock {
834 if let Some(path) = path {
835 DropCtxt {
836 elaborator: self.elaborator,
837 source_info: self.source_info,
838 path,
839 place,
840 succ,
841 unwind,
842 dropline,
843 }
844 .elaborated_drop_block()
845 } else {
846 DropCtxt {
847 elaborator: self.elaborator,
848 source_info: self.source_info,
849 place,
850 succ,
851 unwind,
852 dropline,
853 path: self.path,
855 }
856 .complete_drop(succ, unwind)
857 }
858 }
859
860 x;#[instrument(level = "debug", skip(self), ret)]
871 fn drop_halfladder(
872 &mut self,
873 unwind_ladder: &[Unwind],
874 dropline_ladder: &[Option<BasicBlock>],
875 mut succ: BasicBlock,
876 fields: &[(Place<'tcx>, Option<D::Path>)],
877 ) -> Vec<BasicBlock> {
878 iter::once(succ)
879 .chain(itertools::izip!(fields.iter().rev(), unwind_ladder, dropline_ladder).map(
880 |(&(place, path), &unwind_succ, &dropline_to)| {
881 succ = self.drop_subpath(place, path, succ, unwind_succ, dropline_to);
882 succ
883 },
884 ))
885 .collect()
886 }
887
888 fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind, Option<BasicBlock>) {
889 (
893 self.drop_flag_reset_block(DropFlagMode::Shallow, self.succ, self.unwind),
894 self.unwind,
895 self.dropline,
896 )
897 }
898
899 fn should_retain_for_ladder(&self, (place, subpath): &(Place<'tcx>, Option<D::Path>)) -> bool {
901 if !self.place_ty(*place).needs_drop(self.tcx(), self.elaborator.typing_env()) {
902 return false;
903 }
904 if let Some(subpath) = subpath
905 && let DropStyle::Dead = self.elaborator.drop_style(*subpath, DropFlagMode::Deep)
906 {
907 return false;
908 }
909 true
910 }
911
912 x;#[instrument(level = "debug", skip(self), ret)]
950 fn drop_ladder(
951 &mut self,
952 mut fields: Vec<(Place<'tcx>, Option<D::Path>)>,
953 succ: BasicBlock,
954 unwind: Unwind,
955 dropline: Option<BasicBlock>,
956 ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
957 assert!(
958 if unwind.is_cleanup() { dropline.is_none() } else { true },
959 "Dropline is set for cleanup drop ladder"
960 );
961
962 fields.retain(|path| self.should_retain_for_ladder(path));
963
964 debug!("drop_ladder - fields needing drop: {:?}", fields);
965
966 let dropline_ladder: Vec<Option<BasicBlock>> = vec![None; fields.len() + 1];
967 let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
968 let unwind_ladder: Vec<_> = if let Unwind::To(succ) = unwind {
969 let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
970 halfladder.into_iter().map(Unwind::To).collect()
971 } else {
972 unwind_ladder
973 };
974 let dropline_ladder: Vec<_> = if let Some(succ) = dropline {
975 let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
976 halfladder.into_iter().map(Some).collect()
977 } else {
978 dropline_ladder
979 };
980
981 let normal_ladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
982
983 (
984 *normal_ladder.last().unwrap(),
985 *unwind_ladder.last().unwrap(),
986 *dropline_ladder.last().unwrap(),
987 )
988 }
989
990 x;#[instrument(level = "debug", skip(self), ret)]
991 fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
992 let fields = tys
993 .iter()
994 .enumerate()
995 .map(|(i, &ty)| {
996 (
997 self.tcx().mk_place_field(self.place, FieldIdx::new(i), ty),
998 self.elaborator.field_subpath(self.path, FieldIdx::new(i)),
999 )
1000 })
1001 .collect();
1002
1003 let (succ, unwind, dropline) = self.drop_ladder_bottom();
1004 self.drop_ladder(fields, succ, unwind, dropline).0
1005 }
1006
1007 x;#[instrument(level = "debug", ret)]
1009 fn open_drop_for_box_contents(
1010 &mut self,
1011 adt: ty::AdtDef<'tcx>,
1012 args: GenericArgsRef<'tcx>,
1013 succ: BasicBlock,
1014 unwind: Unwind,
1015 dropline: Option<BasicBlock>,
1016 ) -> BasicBlock {
1017 let unique_ty =
1020 adt.non_enum_variant().fields[FieldIdx::ZERO].ty(self.tcx(), args).skip_norm_wip();
1021 let unique_variant = unique_ty.ty_adt_def().unwrap().non_enum_variant();
1022 let nonnull_ty = unique_variant.fields[FieldIdx::ZERO].ty(self.tcx(), args).skip_norm_wip();
1023 let ptr_ty = Ty::new_imm_ptr(self.tcx(), args[0].expect_ty());
1024
1025 let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::ZERO, unique_ty);
1026 let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::ZERO, nonnull_ty);
1027
1028 let ptr_local = self.new_temp(ptr_ty);
1029
1030 let interior = self.tcx().mk_place_deref(Place::from(ptr_local));
1031 let interior_path = self.elaborator.deref_subpath(self.path);
1032
1033 let do_drop_bb = self.drop_subpath(interior, interior_path, succ, unwind, dropline);
1034
1035 self.new_block_with_statements(
1036 unwind,
1037 vec![self.assign(
1038 Place::from(ptr_local),
1039 Rvalue::Cast(CastKind::Transmute, Operand::Copy(nonnull_place), ptr_ty),
1040 )],
1041 TerminatorKind::Goto { target: do_drop_bb },
1042 )
1043 }
1044
1045 x;#[instrument(level = "debug", ret)]
1046 fn open_drop_for_adt(
1047 &mut self,
1048 adt: ty::AdtDef<'tcx>,
1049 args: GenericArgsRef<'tcx>,
1050 ) -> BasicBlock {
1051 if adt.variants().is_empty() {
1052 return self.new_block(self.unwind, TerminatorKind::Unreachable);
1053 }
1054
1055 let skip_contents = adt.is_union() || adt.is_manually_drop();
1056 let (contents_succ, contents_unwind, contents_dropline) = if skip_contents {
1057 if adt.has_dtor(self.tcx()) && self.elaborator.get_drop_flag(self.path).is_some() {
1058 span_bug!(self.source_info.span, "open dropping partially moved union");
1065 }
1066
1067 (self.succ, self.unwind, self.dropline)
1068 } else {
1069 self.open_drop_for_adt_contents(adt, args)
1070 };
1071
1072 if adt.has_dtor(self.tcx()) {
1073 let destructor_block = if adt.is_box() {
1074 let succ = self.destructor_call_block_sync(contents_succ, contents_unwind);
1076 let unwind = contents_unwind
1077 .map(|unwind| self.destructor_call_block_sync(unwind, Unwind::InCleanup));
1078 let dropline = contents_dropline
1079 .map(|dropline| self.destructor_call_block_sync(dropline, contents_unwind));
1080 self.open_drop_for_box_contents(adt, args, succ, unwind, dropline)
1081 } else {
1082 self.destructor_call_block(contents_succ, contents_unwind, contents_dropline)
1083 };
1084
1085 self.drop_flag_test_block(destructor_block, contents_succ, contents_unwind)
1086 } else {
1087 contents_succ
1088 }
1089 }
1090
1091 fn open_drop_for_adt_contents(
1092 &mut self,
1093 adt: ty::AdtDef<'tcx>,
1094 args: GenericArgsRef<'tcx>,
1095 ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
1096 let (succ, unwind, dropline) = self.drop_ladder_bottom();
1097 if !adt.is_enum() {
1098 let fields =
1099 self.move_paths_for_fields(self.place, self.path, adt.variant(FIRST_VARIANT), args);
1100 self.drop_ladder(fields, succ, unwind, dropline)
1101 } else {
1102 self.open_drop_for_multivariant(adt, args, succ, unwind, dropline)
1103 }
1104 }
1105
1106 fn open_drop_for_multivariant(
1107 &mut self,
1108 adt: ty::AdtDef<'tcx>,
1109 args: GenericArgsRef<'tcx>,
1110 succ: BasicBlock,
1111 unwind: Unwind,
1112 dropline: Option<BasicBlock>,
1113 ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
1114 let mut values = Vec::with_capacity(adt.variants().len());
1115 let mut normal_blocks = Vec::with_capacity(adt.variants().len());
1116 let mut unwind_blocks =
1117 Vec::with_capacity(if unwind.is_cleanup() { 0 } else { adt.variants().len() });
1118 let mut dropline_blocks =
1119 Vec::with_capacity(if dropline.is_none() { 0 } else { adt.variants().len() });
1120
1121 let mut have_otherwise_with_drop_glue = false;
1122 let mut have_otherwise = false;
1123 let tcx = self.tcx();
1124
1125 for (variant_index, discr) in adt.discriminants(tcx) {
1126 let variant = &adt.variant(variant_index);
1127 let subpath = self.elaborator.downcast_subpath(self.path, variant_index);
1128
1129 if let Some(variant_path) = subpath {
1130 let base_place = tcx.mk_place_elem(
1131 self.place,
1132 ProjectionElem::Downcast(Some(variant.name), variant_index),
1133 );
1134 let fields = self.move_paths_for_fields(base_place, variant_path, variant, args);
1135 values.push(discr.val);
1136 if let Unwind::To(unwind) = unwind {
1137 let unwind_ladder = ::alloc::vec::from_elem(Unwind::InCleanup, fields.len() + 1)vec![Unwind::InCleanup; fields.len() + 1];
1156 let dropline_ladder: Vec<Option<BasicBlock>> = ::alloc::vec::from_elem(None, fields.len() + 1)vec![None; fields.len() + 1];
1157 let halfladder =
1158 self.drop_halfladder(&unwind_ladder, &dropline_ladder, unwind, &fields);
1159 unwind_blocks.push(halfladder.last().cloned().unwrap());
1160 }
1161 let (normal, _, drop_bb) = self.drop_ladder(fields, succ, unwind, dropline);
1162 normal_blocks.push(normal);
1163 if dropline.is_some() {
1164 dropline_blocks.push(drop_bb.unwrap());
1165 }
1166 } else {
1167 have_otherwise = true;
1168
1169 let typing_env = self.elaborator.typing_env();
1170 let have_field_with_drop_glue = variant
1171 .fields
1172 .iter()
1173 .any(|field| field.ty(tcx, args).skip_norm_wip().needs_drop(tcx, typing_env));
1174 if have_field_with_drop_glue {
1175 have_otherwise_with_drop_glue = true;
1176 }
1177 }
1178 }
1179
1180 if !have_otherwise {
1181 values.pop();
1182 } else if !have_otherwise_with_drop_glue {
1183 normal_blocks.push(succ);
1184 if let Unwind::To(unwind) = unwind {
1185 unwind_blocks.push(unwind);
1186 }
1187 if let Some(dropline) = dropline {
1188 dropline_blocks.push(dropline);
1189 }
1190 } else {
1191 normal_blocks.push(self.drop_block(succ, unwind));
1192 if let Unwind::To(unwind) = unwind {
1193 unwind_blocks.push(self.drop_block(unwind, Unwind::InCleanup));
1194 }
1195 if let Some(dropline) = dropline {
1196 dropline_blocks.push(self.drop_block(dropline, unwind));
1197 }
1198 }
1199
1200 (
1201 self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
1202 unwind.map(|unwind| {
1203 self.adt_switch_block(adt, unwind_blocks, &values, unwind, Unwind::InCleanup)
1204 }),
1205 dropline.map(|dropline| {
1206 self.adt_switch_block(adt, dropline_blocks, &values, dropline, unwind)
1207 }),
1208 )
1209 }
1210
1211 fn adt_switch_block(
1212 &mut self,
1213 adt: ty::AdtDef<'tcx>,
1214 blocks: Vec<BasicBlock>,
1215 values: &[u128],
1216 succ: BasicBlock,
1217 unwind: Unwind,
1218 ) -> BasicBlock {
1219 let switch_block = blocks.iter().copied().all_equal_value().unwrap_or_else(|_| {
1220 let discr_ty = adt.repr().discr_type().to_ty(self.tcx());
1228 let discr = Place::from(self.new_temp(discr_ty));
1229 let discr_rv = Rvalue::Discriminant(self.place);
1230 self.new_block_with_statements(
1231 unwind,
1232 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.assign(discr, discr_rv)]))vec![self.assign(discr, discr_rv)],
1233 TerminatorKind::SwitchInt {
1234 discr: Operand::Move(discr),
1235 targets: SwitchTargets::new(
1236 values.iter().copied().zip(blocks.iter().copied()),
1237 *blocks.last().unwrap(),
1238 ),
1239 },
1240 )
1241 });
1242 self.drop_flag_test_block(switch_block, succ, unwind)
1243 }
1244
1245 x;#[instrument(level = "debug", skip(self), ret)]
1246 fn destructor_call_block_sync(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1247 let tcx = self.tcx();
1248 let drop_trait = tcx.require_lang_item(LangItem::Drop, DUMMY_SP);
1249 let drop_fn = tcx.associated_item_def_ids(drop_trait)[0];
1250 let ty = self.place_ty(self.place);
1251
1252 let ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
1253 let ref_place = self.new_temp(ref_ty);
1254 let unit_temp = Place::from(self.new_temp(tcx.types.unit));
1255
1256 self.new_block_with_statements(
1257 unwind,
1258 vec![self.assign(
1259 Place::from(ref_place),
1260 Rvalue::Ref(
1261 tcx.lifetimes.re_erased,
1262 BorrowKind::Mut { kind: MutBorrowKind::Default },
1263 self.place,
1264 ),
1265 )],
1266 TerminatorKind::Call {
1267 func: Operand::function_handle(
1269 tcx,
1270 drop_fn,
1271 ty::Binder::dummy([ty.into()]),
1272 self.source_info.span,
1273 ),
1274 args: [dummy_spanned(Operand::Move(Place::from(ref_place)))].into(),
1275 destination: unit_temp,
1276 target: Some(succ),
1277 unwind: unwind.into_action(),
1278 call_source: CallSource::Misc,
1279 fn_span: self.source_info.span,
1280 },
1281 )
1282 }
1283
1284 x;#[instrument(level = "debug", skip(self), ret)]
1285 fn destructor_call_block(
1286 &mut self,
1287 succ: BasicBlock,
1288 unwind: Unwind,
1289 dropline: Option<BasicBlock>,
1290 ) -> BasicBlock {
1291 let ty = self.place_ty(self.place);
1292 if !unwind.is_cleanup() && self.check_if_can_async_drop(ty, true) {
1293 self.build_async_drop(self.place, ty, succ, unwind, dropline, true)
1294 } else {
1295 self.destructor_call_block_sync(succ, unwind)
1296 }
1297 }
1298
1299 fn drop_loop(
1311 &mut self,
1312 succ: BasicBlock,
1313 cur: Local,
1314 len: Local,
1315 ety: Ty<'tcx>,
1316 unwind: Unwind,
1317 dropline: Option<BasicBlock>,
1318 ) -> BasicBlock {
1319 let copy = |place: Place<'tcx>| Operand::Copy(place);
1320 let move_ = |place: Place<'tcx>| Operand::Move(place);
1321 let tcx = self.tcx();
1322
1323 let ptr_ty = Ty::new_mut_ptr(tcx, ety);
1324 let ptr = Place::from(self.new_temp(ptr_ty));
1325 let can_go = Place::from(self.new_temp(tcx.types.bool));
1326 let one = self.constant_usize(1);
1327
1328 let drop_block = self.new_block_with_statements(
1329 unwind,
1330 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.assign(ptr,
Rvalue::RawPtr(RawPtrKind::Mut,
tcx.mk_place_index(self.place, cur))),
self.assign(cur.into(),
Rvalue::BinaryOp(BinOp::Add,
Box::new((move_(cur.into()), one))))]))vec![
1331 self.assign(
1332 ptr,
1333 Rvalue::RawPtr(RawPtrKind::Mut, tcx.mk_place_index(self.place, cur)),
1334 ),
1335 self.assign(
1336 cur.into(),
1337 Rvalue::BinaryOp(BinOp::Add, Box::new((move_(cur.into()), one))),
1338 ),
1339 ],
1340 TerminatorKind::Unreachable,
1342 );
1343
1344 let loop_block = self.new_block_with_statements(
1345 unwind,
1346 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.assign(can_go,
Rvalue::BinaryOp(BinOp::Eq,
Box::new((copy(Place::from(cur)), copy(len.into())))))]))vec![self.assign(
1347 can_go,
1348 Rvalue::BinaryOp(BinOp::Eq, Box::new((copy(Place::from(cur)), copy(len.into())))),
1349 )],
1350 TerminatorKind::if_(move_(can_go), succ, drop_block),
1351 );
1352
1353 let place = tcx.mk_place_deref(ptr);
1354 if !unwind.is_cleanup() && self.check_if_can_async_drop(ety, false) {
1355 let async_drop_bb =
1356 self.build_async_drop(place, ety, loop_block, unwind, dropline, false);
1357 self.elaborator
1358 .patch()
1359 .patch_terminator(drop_block, TerminatorKind::Goto { target: async_drop_bb });
1360 } else {
1361 self.elaborator.patch().patch_terminator(
1362 drop_block,
1363 TerminatorKind::Drop {
1364 place,
1365 target: loop_block,
1366 unwind: unwind.into_action(),
1367 replace: false,
1368 drop: None,
1369 },
1370 );
1371 }
1372 loop_block
1373 }
1374
1375 x;#[instrument(level = "debug", skip(self), ret)]
1376 fn open_drop_for_array(
1377 &mut self,
1378 array_ty: Ty<'tcx>,
1379 ety: Ty<'tcx>,
1380 opt_size: Option<u64>,
1381 ) -> BasicBlock {
1382 let tcx = self.tcx();
1383
1384 if let Some(size) = opt_size {
1385 enum ProjectionKind<Path> {
1386 Drop(std::ops::Range<u64>),
1387 Keep(u64, Path),
1388 }
1389 let mut drop_ranges = vec![];
1394 let mut dropping = true;
1395 let mut start = 0;
1396 for i in 0..size {
1397 let path = self.elaborator.array_subpath(self.path, i, size);
1398 if dropping && path.is_some() {
1399 drop_ranges.push(ProjectionKind::Drop(start..i));
1400 dropping = false;
1401 } else if !dropping && path.is_none() {
1402 dropping = true;
1403 start = i;
1404 }
1405 if let Some(path) = path {
1406 drop_ranges.push(ProjectionKind::Keep(i, path));
1407 }
1408 }
1409 if !drop_ranges.is_empty() {
1410 if dropping {
1411 drop_ranges.push(ProjectionKind::Drop(start..size));
1412 }
1413 let fields = drop_ranges
1414 .iter()
1415 .rev()
1416 .map(|p| {
1417 let (project, path) = match p {
1418 ProjectionKind::Drop(r) => (
1419 ProjectionElem::Subslice {
1420 from: r.start,
1421 to: r.end,
1422 from_end: false,
1423 },
1424 None,
1425 ),
1426 &ProjectionKind::Keep(offset, path) => (
1427 ProjectionElem::ConstantIndex {
1428 offset,
1429 min_length: size,
1430 from_end: false,
1431 },
1432 Some(path),
1433 ),
1434 };
1435 (tcx.mk_place_elem(self.place, project), path)
1436 })
1437 .collect::<Vec<_>>();
1438 let (succ, unwind, dropline) = self.drop_ladder_bottom();
1439 return self.drop_ladder(fields, succ, unwind, dropline).0;
1440 }
1441 }
1442
1443 let array_ptr_ty = Ty::new_mut_ptr(tcx, array_ty);
1444 let array_ptr = self.new_temp(array_ptr_ty);
1445
1446 let slice_ty = Ty::new_slice(tcx, ety);
1447 let slice_ptr_ty = Ty::new_mut_ptr(tcx, slice_ty);
1448 let slice_ptr = self.new_temp(slice_ptr_ty);
1449
1450 let array_place = mem::replace(
1451 &mut self.place,
1452 Place::from(slice_ptr).project_deeper(&[PlaceElem::Deref], tcx),
1453 );
1454 let slice_block = self.drop_loop_trio_for_slice(ety);
1455 self.place = array_place;
1456
1457 self.new_block_with_statements(
1458 self.unwind,
1459 vec![
1460 self.assign(Place::from(array_ptr), Rvalue::RawPtr(RawPtrKind::Mut, self.place)),
1461 self.assign(
1462 Place::from(slice_ptr),
1463 Rvalue::Cast(
1464 CastKind::PointerCoercion(
1465 PointerCoercion::Unsize,
1466 CoercionSource::Implicit,
1467 ),
1468 Operand::Move(Place::from(array_ptr)),
1469 slice_ptr_ty,
1470 ),
1471 ),
1472 ],
1473 TerminatorKind::Goto { target: slice_block },
1474 )
1475 }
1476
1477 x;#[instrument(level = "debug", skip(self), ret)]
1480 fn drop_loop_trio_for_slice(&mut self, ety: Ty<'tcx>) -> BasicBlock {
1481 let tcx = self.tcx();
1482 let len = self.new_temp(tcx.types.usize);
1483 let cur = self.new_temp(tcx.types.usize);
1484
1485 let unwind = self
1486 .unwind
1487 .map(|unwind| self.drop_loop(unwind, cur, len, ety, Unwind::InCleanup, None));
1488
1489 let dropline =
1490 self.dropline.map(|dropline| self.drop_loop(dropline, cur, len, ety, unwind, None));
1491
1492 let loop_block = self.drop_loop(self.succ, cur, len, ety, unwind, dropline);
1493
1494 let [PlaceElem::Deref] = self.place.projection.as_slice() else {
1495 span_bug!(
1496 self.source_info.span,
1497 "Expected place for slice drop shim to be *_n, but it's {:?}",
1498 self.place,
1499 );
1500 };
1501
1502 let zero = self.constant_usize(0);
1503 let drop_block = self.new_block_with_statements(
1504 unwind,
1505 vec![
1506 self.assign(
1507 len.into(),
1508 Rvalue::UnaryOp(
1509 UnOp::PtrMetadata,
1510 Operand::Copy(Place::from(self.place.local)),
1511 ),
1512 ),
1513 self.assign(cur.into(), Rvalue::Use(zero, WithRetag::Yes)),
1514 ],
1515 TerminatorKind::Goto { target: loop_block },
1516 );
1517
1518 let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
1520 self.drop_flag_test_block(reset_block, self.succ, unwind)
1521 }
1522
1523 fn open_drop(&mut self) -> BasicBlock {
1532 let ty = self.place_ty(self.place);
1533 match ty.kind() {
1534 ty::Closure(_, args) => self.open_drop_for_tuple(args.as_closure().upvar_tys()),
1535 ty::CoroutineClosure(_, args) => {
1536 self.open_drop_for_tuple(args.as_coroutine_closure().upvar_tys())
1537 }
1538 ty::Coroutine(_, args) => self.open_drop_for_tuple(args.as_coroutine().upvar_tys()),
1545 ty::Tuple(fields) => self.open_drop_for_tuple(fields),
1546 ty::Adt(def, args) => self.open_drop_for_adt(*def, args),
1547 ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind),
1548 ty::Array(ety, size) => {
1549 let size = size.try_to_target_usize(self.tcx());
1550 self.open_drop_for_array(ty, *ety, size)
1551 }
1552 ty::Slice(ety) => self.drop_loop_trio_for_slice(*ety),
1553
1554 ty::UnsafeBinder(_) => {
1555 self.tcx().dcx().span_delayed_bug(
1558 self.source_info.span,
1559 "open drop for unsafe binder shouldn't be encountered",
1560 );
1561 self.new_block(self.unwind, TerminatorKind::Unreachable)
1562 }
1563
1564 _ => ::rustc_middle::util::bug::span_bug_fmt(self.source_info.span,
format_args!("open drop from non-ADT `{0:?}`", ty))span_bug!(self.source_info.span, "open drop from non-ADT `{:?}`", ty),
1565 }
1566 }
1567
1568 x;#[instrument(level = "debug", skip(self), ret)]
1569 fn complete_drop(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1570 let drop_block = self.drop_block(succ, unwind);
1571 self.drop_flag_test_block(drop_block, succ, unwind)
1572 }
1573
1574 x;#[instrument(level = "debug", skip(self), ret)]
1577 fn drop_flag_reset_block(
1578 &mut self,
1579 mode: DropFlagMode,
1580 succ: BasicBlock,
1581 unwind: Unwind,
1582 ) -> BasicBlock {
1583 if unwind.is_cleanup() {
1584 return succ;
1587 }
1588 let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
1589 let block_start = Location { block, statement_index: 0 };
1590 self.elaborator.clear_drop_flag(block_start, self.path, mode);
1591 block
1592 }
1593
1594 x;#[instrument(level = "debug", skip(self), ret)]
1595 fn elaborated_drop_block(&mut self) -> BasicBlock {
1596 let blk = self.new_block(
1597 self.unwind,
1598 TerminatorKind::Drop {
1599 place: self.place,
1600 target: self.succ,
1601 unwind: self.unwind.into_action(),
1602 replace: false,
1603 drop: self.dropline,
1604 },
1605 );
1606 self.elaborate_drop(blk);
1607 blk
1608 }
1609
1610 fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1611 let drop_ty = self.place_ty(self.place);
1612 if !unwind.is_cleanup() && self.check_if_can_async_drop(drop_ty, false) {
1613 self.build_async_drop(self.place, drop_ty, self.succ, unwind, self.dropline, false)
1614 } else {
1615 self.new_block(
1616 unwind,
1617 TerminatorKind::Drop {
1618 place: self.place,
1619 target,
1620 unwind: unwind.into_action(),
1621 replace: false,
1622 drop: None,
1623 },
1624 )
1625 }
1626 }
1627
1628 x;#[instrument(level = "debug", skip(self), ret)]
1634 fn drop_flag_test_block(
1635 &mut self,
1636 on_set: BasicBlock,
1637 on_unset: BasicBlock,
1638 unwind: Unwind,
1639 ) -> BasicBlock {
1640 let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
1641 match style {
1642 DropStyle::Dead => on_unset,
1643 DropStyle::Static => on_set,
1644 DropStyle::Conditional | DropStyle::Open => {
1645 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
1646 let term = TerminatorKind::if_(flag, on_set, on_unset);
1647 self.new_block(unwind, term)
1648 }
1649 }
1650 }
1651
1652 x;#[instrument(level = "trace", skip(self), ret)]
1653 fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
1654 self.elaborator.patch().new_block(BasicBlockData::new(
1655 Some(Terminator { source_info: self.source_info, kind: k, attributes: ThinVec::new() }),
1656 unwind.is_cleanup(),
1657 ))
1658 }
1659
1660 x;#[instrument(level = "trace", skip(self, statements), ret)]
1661 fn new_block_with_statements(
1662 &mut self,
1663 unwind: Unwind,
1664 statements: Vec<Statement<'tcx>>,
1665 k: TerminatorKind<'tcx>,
1666 ) -> BasicBlock {
1667 self.elaborator.patch().new_block(BasicBlockData::new_stmts(
1668 statements,
1669 Some(Terminator { source_info: self.source_info, kind: k, attributes: ThinVec::new() }),
1670 unwind.is_cleanup(),
1671 ))
1672 }
1673
1674 fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
1675 self.elaborator.patch().new_temp(ty, self.source_info.span)
1676 }
1677
1678 fn constant_usize(&self, val: u16) -> Operand<'tcx> {
1679 Operand::Constant(Box::new(ConstOperand {
1680 span: self.source_info.span,
1681 user_ty: None,
1682 const_: Const::from_usize(self.tcx(), val.into()),
1683 }))
1684 }
1685
1686 fn assign(&self, lhs: Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
1687 Statement::new(self.source_info, StatementKind::Assign(Box::new((lhs, rhs))))
1688 }
1689
1690 fn storage_live(&self, local: Local) -> Statement<'tcx> {
1691 Statement::new(self.source_info, StatementKind::StorageLive(local))
1692 }
1693
1694 fn storage_dead(&self, local: Local) -> Statement<'tcx> {
1695 Statement::new(self.source_info, StatementKind::StorageDead(local))
1696 }
1697}