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::attrs::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_mir_dataflow::DropFlagState;
15use rustc_span::{DUMMY_SP, dummy_spanned};
16use tracing::{debug, instrument};
17
18use crate::coroutine::CTX_ARG;
19use crate::patch::MirPatch;
20
21#[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)]
23pub(crate) enum DropStyle {
24 Dead,
26
27 Static,
30
31 Conditional,
33
34 Open,
40}
41
42#[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)]
44pub(crate) enum DropFlagMode {
45 Shallow,
47 Deep,
49}
50
51#[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)]
53pub(crate) enum Unwind {
54 To(BasicBlock),
56 InCleanup,
58}
59
60impl Unwind {
61 fn is_cleanup(self) -> bool {
62 match self {
63 Unwind::To(..) => false,
64 Unwind::InCleanup => true,
65 }
66 }
67
68 fn into_action(self) -> UnwindAction {
69 match self {
70 Unwind::To(bb) => UnwindAction::Cleanup(bb),
71 Unwind::InCleanup => UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
72 }
73 }
74
75 fn map<F>(self, f: F) -> Self
76 where
77 F: FnOnce(BasicBlock) -> BasicBlock,
78 {
79 match self {
80 Unwind::To(bb) => Unwind::To(f(bb)),
81 Unwind::InCleanup => Unwind::InCleanup,
82 }
83 }
84}
85
86pub(crate) trait DropElaborator<'a, 'tcx>: fmt::Debug {
87 type Path: Copy + fmt::Debug;
93
94 fn patch_ref(&self) -> &MirPatch<'tcx>;
97 fn patch(&mut self) -> &mut MirPatch<'tcx>;
98 fn body(&self) -> &'a Body<'tcx>;
99 fn tcx(&self) -> TyCtxt<'tcx>;
100 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
101 fn allow_async_drops(&self) -> bool;
102
103 fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
107
108 fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
110
111 fn drop_flags_for(&mut self, path: Self::Path, mode: DropFlagMode) -> Vec<Place<'tcx>>;
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 tcx.fn_sig(async_drop_fn_def_id)
254 .instantiate(tcx, &[drop_ty.into()])
255 .skip_norm_wip(),
256 )
257 .output();
258 let fut = self.new_temp(fut_ty);
259
260 let succ_with_dead = self.new_block_with_statements(
264 unwind,
265 vec![self.storage_dead(fut)],
266 TerminatorKind::Goto { target: succ },
267 );
268 let dropline_with_dead = dropline.map(|target| {
269 self.new_block_with_statements(
270 unwind,
271 vec![self.storage_dead(fut)],
272 TerminatorKind::Goto { target },
273 )
274 });
275 let unwind_with_dead = unwind.map(|target| {
276 self.new_block_with_statements(
277 Unwind::InCleanup,
278 vec![self.storage_dead(fut)],
279 TerminatorKind::Goto { target },
280 )
281 });
282
283 let coroutine_kind = self.elaborator.body().coroutine_kind().unwrap();
285 let yield_value = match coroutine_kind {
286 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
288 let full_yield_ty = self.elaborator.body().yield_ty().unwrap();
289 let ty::Adt(_poll_adt, args) = *full_yield_ty.kind() else { bug!() };
290 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
291 let yield_ty = args.type_at(0);
292 Operand::unevaluated_constant(
293 tcx,
294 tcx.require_lang_item(LangItem::AsyncGenPending, span),
295 tcx.mk_args(&[yield_ty.into()]),
296 span,
297 )
298 }
299 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
301 Operand::zero_sized_constant(tcx.types.unit, span)
302 }
303 _ => panic!("unexpected coroutine for async drop {coroutine_kind:?}"),
305 };
306
307 let panic_bb = self.build_resumed_after_drop_abort_block(unwind_with_dead, coroutine_kind);
316 let (drop_pin_bb, drop_resume_bb, drop_drop_bb) = self.build_pin_poll_yield_loop(
317 CTX_ARG.into(),
318 fut.into(),
319 yield_value.clone(),
320 dropline_with_dead.unwrap_or(succ_with_dead),
323 unwind_with_dead,
324 );
325 self.elaborator
326 .patch()
327 .patch_terminator(drop_resume_bb, TerminatorKind::Goto { target: panic_bb });
328 self.elaborator
329 .patch()
330 .patch_terminator(drop_drop_bb, TerminatorKind::Goto { target: drop_pin_bb });
331
332 let succ_yield_loop = if dropline_with_dead.is_some() {
339 let (pin_bb, resume_bb, drop_bb) = self.build_pin_poll_yield_loop(
340 CTX_ARG.into(),
341 fut.into(),
342 yield_value,
343 succ_with_dead,
345 unwind_with_dead,
346 );
347 self.elaborator
348 .patch()
349 .patch_terminator(resume_bb, TerminatorKind::Goto { target: pin_bb });
350 self.elaborator
351 .patch()
352 .patch_terminator(drop_bb, TerminatorKind::Goto { target: drop_pin_bb });
353 pin_bb
354 } else {
355 drop_pin_bb
357 };
358
359 let pin_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, span));
363 let pin_obj_ty = Ty::new_adt(tcx, pin_adt_def, tcx.mk_args(&[obj_ref_ty.into()]));
364 let pin_obj_local = self.new_temp(pin_obj_ty);
366 let drop_arg = if call_destructor_only {
367 Operand::Move(pin_obj_local.into())
369 } else {
370 Operand::Copy(tcx.mk_place_field(pin_obj_local.into(), FieldIdx::ZERO, obj_ref_ty))
372 };
373 let call_drop_bb = self.new_block_with_statements(
374 unwind_with_dead,
375 vec![self.storage_live(fut)],
376 TerminatorKind::Call {
377 func: Operand::function_handle(tcx, async_drop_fn_def_id, &[drop_ty.into()], span),
378 args: [dummy_spanned(drop_arg)].into(),
379 destination: fut.into(),
380 target: Some(succ_yield_loop),
381 unwind: unwind_with_dead.into_action(),
382 call_source: CallSource::Misc,
383 fn_span: self.source_info.span,
384 },
385 );
386
387 let obj_ref_place = Place::from(self.new_temp(obj_ref_ty));
389 let pin_obj_new_unchecked_fn = tcx.require_lang_item(LangItem::PinNewUnchecked, span);
390 let assign_obj_ref_place = self.assign(
391 obj_ref_place,
392 Rvalue::Ref(
393 tcx.lifetimes.re_erased,
394 BorrowKind::Mut { kind: MutBorrowKind::Default },
395 place,
396 ),
397 );
398 self.new_block_with_statements(
399 unwind,
400 vec![assign_obj_ref_place],
401 TerminatorKind::Call {
402 func: Operand::function_handle(
403 tcx,
404 pin_obj_new_unchecked_fn,
405 &[obj_ref_ty.into()],
406 span,
407 ),
408 args: [dummy_spanned(Operand::Move(obj_ref_place))].into(),
409 destination: pin_obj_local.into(),
410 target: Some(call_drop_bb),
411 unwind: unwind.into_action(),
412 call_source: CallSource::Misc,
413 fn_span: span,
414 },
415 )
416 }
417
418 fn build_resumed_after_drop_abort_block(
419 &mut self,
420 unwind: Unwind,
421 coroutine_kind: CoroutineKind,
422 ) -> BasicBlock {
423 let tcx = self.tcx();
424 let panic_bb = self.new_block(unwind, TerminatorKind::Unreachable);
425 let msg = AssertMessage::ResumedAfterDrop(coroutine_kind);
426 let false_op = Operand::Constant(Box::new(ConstOperand {
427 span: self.source_info.span,
428 user_ty: None,
429 const_: Const::from_bool(tcx, false),
430 }));
431 self.elaborator.patch().patch_terminator(
432 panic_bb,
433 TerminatorKind::Assert {
434 cond: false_op,
435 expected: true,
436 msg: Box::new(msg),
437 target: panic_bb,
438 unwind: unwind.into_action(),
439 },
440 );
441 panic_bb
442 }
443
444 x;#[instrument(level = "trace", skip(self), ret)]
460 fn build_pin_poll_yield_loop(
461 &mut self,
462 resume_place: Place<'tcx>,
463 fut_place: Place<'tcx>,
464 yield_value: Operand<'tcx>,
465 succ: BasicBlock,
466 unwind: Unwind,
467 ) -> (BasicBlock, BasicBlock, BasicBlock) {
468 let tcx = self.tcx();
469 let source_info = self.source_info;
470
471 let resume_arg_ty = resume_place.ty(self.elaborator.body(), tcx).ty;
472 let context_ref_ty = Ty::new_task_context(tcx);
473
474 let poll_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Poll, source_info.span));
475 let poll_enum = Ty::new_adt(tcx, poll_adt_def, tcx.mk_args(&[tcx.types.unit.into()]));
476
477 let fut_ty = self.elaborator.patch_ref().local_ty(fut_place.local);
478 let fut_ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, fut_ty);
479
480 let pin_adt_def = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, source_info.span));
481 let fut_pin_ty = Ty::new_adt(tcx, pin_adt_def, tcx.mk_args(&[fut_ref_ty.into()]));
482
483 let yield_resume_local = self.new_temp(resume_arg_ty);
486 let resume_bb = self.new_block_with_statements(
487 unwind,
488 vec![
489 self.assign(
490 resume_place,
491 Rvalue::Use(Operand::Move(yield_resume_local.into()), WithRetag::Yes),
492 ),
493 self.storage_dead(yield_resume_local),
494 ],
495 TerminatorKind::Unreachable,
497 );
498 let dropline_bb = self.new_block_with_statements(
499 unwind,
500 vec![
501 self.assign(
502 resume_place,
503 Rvalue::Use(Operand::Move(yield_resume_local.into()), WithRetag::Yes),
504 ),
505 self.storage_dead(yield_resume_local),
506 ],
507 TerminatorKind::Unreachable,
509 );
510 let yield_bb = self.new_block_with_statements(
511 unwind,
512 vec![self.storage_live(yield_resume_local)],
513 TerminatorKind::Yield {
514 value: yield_value,
515 resume: resume_bb,
516 resume_arg: yield_resume_local.into(),
517 drop: Some(dropline_bb),
518 },
519 );
520
521 let poll_unit_local = self.new_temp(poll_enum);
522 let switch_bb = {
523 let poll_ready_variant =
524 tcx.require_lang_item(LangItem::PollReady, self.source_info.span);
525 let poll_ready_variant_idx = poll_adt_def.variant_index_with_id(poll_ready_variant);
526 let poll_pending_variant =
527 tcx.require_lang_item(LangItem::PollPending, self.source_info.span);
528 let poll_pending_variant_idx = poll_adt_def.variant_index_with_id(poll_pending_variant);
529
530 let Discr { val: poll_ready_discr, ty: poll_discr_ty } =
531 poll_enum.discriminant_for_variant(tcx, poll_ready_variant_idx).unwrap();
532 let Discr { val: poll_pending_discr, ty: _ } =
533 poll_enum.discriminant_for_variant(tcx, poll_pending_variant_idx).unwrap();
534
535 let poll_discr_local = self.new_temp(poll_discr_ty);
536 let otherwise_bb = self.elaborator.patch().unreachable_no_cleanup_block();
537 self.new_block_with_statements(
538 unwind,
539 vec![
540 self.assign(
541 poll_discr_local.into(),
542 Rvalue::Discriminant(poll_unit_local.into()),
543 ),
544 ],
545 TerminatorKind::SwitchInt {
546 discr: Operand::Move(poll_discr_local.into()),
547 targets: SwitchTargets::new(
548 [
549 (poll_ready_discr, succ),
551 (poll_pending_discr, yield_bb),
553 ]
554 .into_iter(),
555 otherwise_bb,
557 ),
558 },
559 )
560 };
561
562 let fut_pin_local = self.new_temp(fut_pin_ty);
563 let context_ref_local = self.new_temp(context_ref_ty);
564
565 let poll_fn = tcx.require_lang_item(LangItem::FuturePoll, source_info.span);
566 let poll_bb = self.new_block_with_statements(
567 unwind,
568 Vec::new(),
569 TerminatorKind::Call {
570 func: Operand::function_handle(tcx, poll_fn, &[fut_ty.into()], source_info.span),
571 args: [
572 dummy_spanned(Operand::Move(fut_pin_local.into())),
573 dummy_spanned(Operand::Move(context_ref_local.into())),
574 ]
575 .into(),
576 destination: poll_unit_local.into(),
577 target: Some(switch_bb),
578 unwind: unwind.into_action(),
579 call_source: CallSource::Misc,
580 fn_span: source_info.span,
581 },
582 );
583
584 let get_context_fn = tcx.require_lang_item(LangItem::GetContext, source_info.span);
585 let get_context_bb = {
586 let entry_resume_local = self.new_temp(resume_arg_ty);
589 self.new_block_with_statements(
590 unwind,
591 vec![self.assign(
592 entry_resume_local.into(),
593 Rvalue::Use(Operand::Move(resume_place), WithRetag::Yes),
594 )],
595 TerminatorKind::Call {
596 func: Operand::function_handle(
597 tcx,
598 get_context_fn,
599 &[tcx.lifetimes.re_erased.into(), tcx.lifetimes.re_erased.into()],
600 source_info.span,
601 ),
602 args: [dummy_spanned(Operand::Move(entry_resume_local.into()))].into(),
603 destination: context_ref_local.into(),
604 target: Some(poll_bb),
605 unwind: unwind.into_action(),
606 call_source: CallSource::Misc,
607 fn_span: source_info.span,
608 },
609 )
610 };
611
612 let fut_ref_local = self.new_temp(fut_ref_ty);
613 let fut_pin_new_unchecked_fn =
614 tcx.require_lang_item(LangItem::PinNewUnchecked, source_info.span);
615 let pin_bb = self.new_block_with_statements(
616 unwind,
617 vec![self.assign(
618 fut_ref_local.into(),
619 Rvalue::Ref(
620 tcx.lifetimes.re_erased,
621 BorrowKind::Mut { kind: MutBorrowKind::Default },
622 fut_place,
623 ),
624 )],
625 TerminatorKind::Call {
626 func: Operand::function_handle(
627 tcx,
628 fut_pin_new_unchecked_fn,
629 &[fut_ref_ty.into()],
630 source_info.span,
631 ),
632 args: [dummy_spanned(Operand::Move(fut_ref_local.into()))].into(),
633 destination: fut_pin_local.into(),
634 target: Some(get_context_bb),
635 unwind: unwind.into_action(),
636 call_source: CallSource::Misc,
637 fn_span: source_info.span,
638 },
639 );
640
641 (pin_bb, resume_bb, dropline_bb)
642 }
643
644 fn build_drop(&mut self, bb: BasicBlock) {
645 let drop_ty = self.place_ty(self.place);
646 if !self.elaborator.patch_ref().block(self.elaborator.body(), bb).is_cleanup
647 && self.check_if_can_async_drop(drop_ty, false)
648 {
649 let async_drop_bb = self.build_async_drop(
650 self.place,
651 drop_ty,
652 self.succ,
653 self.unwind,
654 self.dropline,
655 false,
656 );
657 self.elaborator
658 .patch()
659 .patch_terminator(bb, TerminatorKind::Goto { target: async_drop_bb });
660 } else {
661 self.elaborator.patch().patch_terminator(
662 bb,
663 TerminatorKind::Drop {
664 place: self.place,
665 target: self.succ,
666 unwind: self.unwind.into_action(),
667 replace: false,
668 drop: None,
669 },
670 );
671 }
672 }
673
674 fn check_if_can_async_drop(&mut self, drop_ty: Ty<'tcx>, call_destructor_only: bool) -> bool {
676 if !self.elaborator.allow_async_drops()
677 || !self
678 .elaborator
679 .body()
680 .coroutine
681 .as_ref()
682 .is_some_and(|ck| ck.coroutine_kind.is_async_desugaring())
683 {
684 return false;
685 }
686
687 if drop_ty == self.place_ty(Local::arg(0).into()) {
688 return false;
689 }
690
691 let is_async_drop_feature_enabled = if self.tcx().features().async_drop() {
692 true
693 } else {
694 if let ty::Adt(adt_def, _) = drop_ty.kind() {
696 !adt_def.did().is_local() && adt_def.async_destructor(self.tcx()).is_some()
697 } else {
698 false
699 }
700 };
701
702 if !is_async_drop_feature_enabled {
706 return false;
707 }
708
709 let needs_async_drop = if call_destructor_only {
710 drop_ty.is_async_drop(self.tcx(), self.elaborator.typing_env())
711 } else {
712 drop_ty.needs_async_drop(self.tcx(), self.elaborator.typing_env())
713 };
714
715 if needs_async_drop && self.tcx().features().staged_api() {
717 ::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!(
718 self.source_info.span,
719 "don't use async drop in libstd, it becomes insta-stable"
720 );
721 }
722
723 needs_async_drop
724 }
725
726 #[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(744u32),
::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")]
745 fn elaborate_drop(&mut self, bb: BasicBlock) {
746 match self.elaborator.drop_style(self.path, DropFlagMode::Deep) {
747 DropStyle::Dead => {
748 self.elaborator
749 .patch()
750 .patch_terminator(bb, TerminatorKind::Goto { target: self.succ });
751 }
752 DropStyle::Static => {
753 self.build_drop(bb);
754 }
755 DropStyle::Conditional => {
756 let drop_bb = self.complete_drop(self.succ, self.unwind);
757 self.elaborator
758 .patch()
759 .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
760 }
761 DropStyle::Open => {
762 let drop_bb = self.open_drop();
763 self.elaborator
764 .patch()
765 .patch_terminator(bb, TerminatorKind::Goto { target: drop_bb });
766 }
767 }
768 }
769
770 fn move_paths_for_fields(
773 &self,
774 base_place: Place<'tcx>,
775 variant_path: D::Path,
776 variant: &'tcx ty::VariantDef,
777 args: GenericArgsRef<'tcx>,
778 ) -> Vec<(Place<'tcx>, Option<D::Path>)> {
779 variant
780 .fields
781 .iter_enumerated()
782 .map(|(field_idx, field)| {
783 let subpath = self.elaborator.field_subpath(variant_path, field_idx);
784 let tcx = self.tcx();
785
786 match self.elaborator.typing_env().typing_mode().assert_not_erased() {
787 ty::TypingMode::PostAnalysis | ty::TypingMode::Codegen => {}
788 ty::TypingMode::Coherence
789 | ty::TypingMode::Reflection
790 | ty::TypingMode::Typeck { .. }
791 | ty::TypingMode::PostTypeckUntilBorrowck { .. }
792 | ty::TypingMode::PostBorrowck { .. } => {
793 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
794 }
795 }
796
797 let field_ty = field.ty(tcx, args);
798 let field_ty = tcx
801 .try_normalize_erasing_regions(self.elaborator.typing_env(), field_ty)
802 .unwrap_or(field_ty.skip_norm_wip());
803
804 (tcx.mk_place_field(base_place, field_idx, field_ty), subpath)
805 })
806 .filter(|path| self.should_retain_for_ladder(path))
807 .collect()
808 }
809
810 x;#[instrument(level = "debug", skip(self), ret)]
811 fn drop_subpath(
812 &mut self,
813 place: Place<'tcx>,
814 path: Option<D::Path>,
815 succ: BasicBlock,
816 unwind: Unwind,
817 dropline: Option<BasicBlock>,
818 ) -> BasicBlock {
819 if let Some(path) = path {
820 DropCtxt {
821 elaborator: self.elaborator,
822 source_info: self.source_info,
823 path,
824 place,
825 succ,
826 unwind,
827 dropline,
828 }
829 .elaborated_drop_block()
830 } else {
831 DropCtxt {
832 elaborator: self.elaborator,
833 source_info: self.source_info,
834 place,
835 succ,
836 unwind,
837 dropline,
838 path: self.path,
840 }
841 .complete_drop(succ, unwind)
842 }
843 }
844
845 x;#[instrument(level = "debug", skip(self), ret)]
856 fn drop_halfladder(
857 &mut self,
858 unwind_ladder: &[Unwind],
859 dropline_ladder: &[Option<BasicBlock>],
860 mut succ: BasicBlock,
861 fields: &[(Place<'tcx>, Option<D::Path>)],
862 ) -> Vec<BasicBlock> {
863 iter::once(succ)
864 .chain(itertools::izip!(fields.iter().rev(), unwind_ladder, dropline_ladder).map(
865 |(&(place, path), &unwind_succ, &dropline_to)| {
866 succ = self.drop_subpath(place, path, succ, unwind_succ, dropline_to);
867 succ
868 },
869 ))
870 .collect()
871 }
872
873 fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind, Option<BasicBlock>) {
874 (
878 self.drop_flag_reset_block(DropFlagMode::Shallow, self.succ, self.unwind),
879 self.unwind,
880 self.dropline,
881 )
882 }
883
884 fn should_retain_for_ladder(&self, (place, subpath): &(Place<'tcx>, Option<D::Path>)) -> bool {
886 if !self.place_ty(*place).needs_drop(self.tcx(), self.elaborator.typing_env()) {
887 return false;
888 }
889 if let Some(subpath) = subpath
890 && let DropStyle::Dead = self.elaborator.drop_style(*subpath, DropFlagMode::Deep)
891 {
892 return false;
893 }
894 true
895 }
896
897 x;#[instrument(level = "debug", skip(self), ret)]
935 fn drop_ladder(
936 &mut self,
937 mut fields: Vec<(Place<'tcx>, Option<D::Path>)>,
938 succ: BasicBlock,
939 unwind: Unwind,
940 dropline: Option<BasicBlock>,
941 ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
942 assert!(
943 if unwind.is_cleanup() { dropline.is_none() } else { true },
944 "Dropline is set for cleanup drop ladder"
945 );
946
947 fields.retain(|path| self.should_retain_for_ladder(path));
948
949 debug!("drop_ladder - fields needing drop: {:?}", fields);
950
951 let dropline_ladder: Vec<Option<BasicBlock>> = vec![None; fields.len() + 1];
952 let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
953 let unwind_ladder: Vec<_> = if let Unwind::To(succ) = unwind {
954 let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
955 halfladder.into_iter().map(Unwind::To).collect()
956 } else {
957 unwind_ladder
958 };
959 let dropline_ladder: Vec<_> = if let Some(succ) = dropline {
960 let halfladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
961 halfladder.into_iter().map(Some).collect()
962 } else {
963 dropline_ladder
964 };
965
966 let normal_ladder = self.drop_halfladder(&unwind_ladder, &dropline_ladder, succ, &fields);
967
968 (
969 *normal_ladder.last().unwrap(),
970 *unwind_ladder.last().unwrap(),
971 *dropline_ladder.last().unwrap(),
972 )
973 }
974
975 x;#[instrument(level = "debug", skip(self), ret)]
976 fn open_drop_for_tuple(&mut self, tys: &[Ty<'tcx>]) -> BasicBlock {
977 let fields = tys
978 .iter()
979 .enumerate()
980 .map(|(i, &ty)| {
981 (
982 self.tcx().mk_place_field(self.place, FieldIdx::new(i), ty),
983 self.elaborator.field_subpath(self.path, FieldIdx::new(i)),
984 )
985 })
986 .collect();
987
988 let (succ, unwind, dropline) = self.drop_ladder_bottom();
989 self.drop_ladder(fields, succ, unwind, dropline).0
990 }
991
992 x;#[instrument(level = "debug", ret)]
994 fn open_drop_for_box_contents(
995 &mut self,
996 adt: ty::AdtDef<'tcx>,
997 args: GenericArgsRef<'tcx>,
998 succ: BasicBlock,
999 unwind: Unwind,
1000 dropline: Option<BasicBlock>,
1001 ) -> BasicBlock {
1002 let unique_ty =
1005 adt.non_enum_variant().fields[FieldIdx::ZERO].ty(self.tcx(), args).skip_norm_wip();
1006 let unique_variant = unique_ty.ty_adt_def().unwrap().non_enum_variant();
1007 let nonnull_ty = unique_variant.fields[FieldIdx::ZERO].ty(self.tcx(), args).skip_norm_wip();
1008 let ptr_ty = Ty::new_imm_ptr(self.tcx(), args[0].expect_ty());
1009
1010 let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::ZERO, unique_ty);
1011 let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::ZERO, nonnull_ty);
1012
1013 let ptr_local = self.new_temp(ptr_ty);
1014
1015 let interior = self.tcx().mk_place_deref(Place::from(ptr_local));
1016 let interior_path = self.elaborator.deref_subpath(self.path);
1017
1018 let do_drop_bb = self.drop_subpath(interior, interior_path, succ, unwind, dropline);
1019
1020 self.new_block_with_statements(
1021 unwind,
1022 vec![self.assign(
1023 Place::from(ptr_local),
1024 Rvalue::Cast(CastKind::Transmute, Operand::Copy(nonnull_place), ptr_ty),
1025 )],
1026 TerminatorKind::Goto { target: do_drop_bb },
1027 )
1028 }
1029
1030 x;#[instrument(level = "debug", ret)]
1031 fn open_drop_for_adt(
1032 &mut self,
1033 adt: ty::AdtDef<'tcx>,
1034 args: GenericArgsRef<'tcx>,
1035 ) -> BasicBlock {
1036 if adt.variants().is_empty() {
1037 return self.new_block(self.unwind, TerminatorKind::Unreachable);
1038 }
1039
1040 let skip_contents = adt.is_union() || adt.is_manually_drop();
1041 let (contents_succ, contents_unwind, contents_dropline) = if skip_contents {
1042 if adt.has_dtor(self.tcx()) && self.elaborator.get_drop_flag(self.path).is_some() {
1043 span_bug!(self.source_info.span, "open dropping partially moved union");
1050 }
1051
1052 (self.succ, self.unwind, self.dropline)
1053 } else {
1054 self.open_drop_for_adt_contents(adt, args)
1055 };
1056
1057 if adt.has_dtor(self.tcx()) {
1058 let destructor_block = if adt.is_box() {
1059 let succ = self.destructor_call_block_sync(contents_succ, contents_unwind);
1061 let unwind = contents_unwind
1062 .map(|unwind| self.destructor_call_block_sync(unwind, Unwind::InCleanup));
1063 let dropline = contents_dropline
1064 .map(|dropline| self.destructor_call_block_sync(dropline, contents_unwind));
1065 self.open_drop_for_box_contents(adt, args, succ, unwind, dropline)
1066 } else {
1067 self.destructor_call_block(contents_succ, contents_unwind, contents_dropline)
1068 };
1069
1070 self.drop_flag_test_block(destructor_block, contents_succ, contents_unwind)
1071 } else {
1072 contents_succ
1073 }
1074 }
1075
1076 fn open_drop_for_adt_contents(
1077 &mut self,
1078 adt: ty::AdtDef<'tcx>,
1079 args: GenericArgsRef<'tcx>,
1080 ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
1081 let (succ, unwind, dropline) = self.drop_ladder_bottom();
1082 if !adt.is_enum() {
1083 let fields =
1084 self.move_paths_for_fields(self.place, self.path, adt.variant(FIRST_VARIANT), args);
1085 self.drop_ladder(fields, succ, unwind, dropline)
1086 } else {
1087 self.open_drop_for_multivariant(adt, args, succ, unwind, dropline)
1088 }
1089 }
1090
1091 fn open_drop_for_multivariant(
1092 &mut self,
1093 adt: ty::AdtDef<'tcx>,
1094 args: GenericArgsRef<'tcx>,
1095 succ: BasicBlock,
1096 unwind: Unwind,
1097 dropline: Option<BasicBlock>,
1098 ) -> (BasicBlock, Unwind, Option<BasicBlock>) {
1099 let mut values = Vec::with_capacity(adt.variants().len());
1100 let mut normal_blocks = Vec::with_capacity(adt.variants().len());
1101 let mut unwind_blocks =
1102 Vec::with_capacity(if unwind.is_cleanup() { 0 } else { adt.variants().len() });
1103 let mut dropline_blocks =
1104 Vec::with_capacity(if dropline.is_none() { 0 } else { adt.variants().len() });
1105
1106 let mut have_otherwise_with_drop_glue = false;
1107 let mut have_otherwise = false;
1108 let tcx = self.tcx();
1109
1110 for (variant_index, discr) in adt.discriminants(tcx) {
1111 let variant = &adt.variant(variant_index);
1112 let subpath = self.elaborator.downcast_subpath(self.path, variant_index);
1113
1114 if let Some(variant_path) = subpath {
1115 let base_place = tcx.mk_place_elem(
1116 self.place,
1117 ProjectionElem::Downcast(Some(variant.name), variant_index),
1118 );
1119 let fields = self.move_paths_for_fields(base_place, variant_path, variant, args);
1120 values.push(discr.val);
1121 if let Unwind::To(unwind) = unwind {
1122 let unwind_ladder = ::alloc::vec::from_elem(Unwind::InCleanup, fields.len() + 1)vec![Unwind::InCleanup; fields.len() + 1];
1141 let dropline_ladder: Vec<Option<BasicBlock>> = ::alloc::vec::from_elem(None, fields.len() + 1)vec![None; fields.len() + 1];
1142 let halfladder =
1143 self.drop_halfladder(&unwind_ladder, &dropline_ladder, unwind, &fields);
1144 unwind_blocks.push(halfladder.last().cloned().unwrap());
1145 }
1146 let (normal, _, drop_bb) = self.drop_ladder(fields, succ, unwind, dropline);
1147 normal_blocks.push(normal);
1148 if dropline.is_some() {
1149 dropline_blocks.push(drop_bb.unwrap());
1150 }
1151 } else {
1152 have_otherwise = true;
1153
1154 let typing_env = self.elaborator.typing_env();
1155 let have_field_with_drop_glue = variant
1156 .fields
1157 .iter()
1158 .any(|field| field.ty(tcx, args).skip_norm_wip().needs_drop(tcx, typing_env));
1159 if have_field_with_drop_glue {
1160 have_otherwise_with_drop_glue = true;
1161 }
1162 }
1163 }
1164
1165 if !have_otherwise {
1166 values.pop();
1167 } else if !have_otherwise_with_drop_glue {
1168 normal_blocks.push(succ);
1169 if let Unwind::To(unwind) = unwind {
1170 unwind_blocks.push(unwind);
1171 }
1172 if let Some(dropline) = dropline {
1173 dropline_blocks.push(dropline);
1174 }
1175 } else {
1176 normal_blocks.push(self.drop_block(succ, unwind));
1177 if let Unwind::To(unwind) = unwind {
1178 unwind_blocks.push(self.drop_block(unwind, Unwind::InCleanup));
1179 }
1180 if let Some(dropline) = dropline {
1181 dropline_blocks.push(self.drop_block(dropline, unwind));
1182 }
1183 }
1184
1185 (
1186 self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
1187 unwind.map(|unwind| {
1188 self.adt_switch_block(adt, unwind_blocks, &values, unwind, Unwind::InCleanup)
1189 }),
1190 dropline.map(|dropline| {
1191 self.adt_switch_block(adt, dropline_blocks, &values, dropline, unwind)
1192 }),
1193 )
1194 }
1195
1196 fn adt_switch_block(
1197 &mut self,
1198 adt: ty::AdtDef<'tcx>,
1199 blocks: Vec<BasicBlock>,
1200 values: &[u128],
1201 succ: BasicBlock,
1202 unwind: Unwind,
1203 ) -> BasicBlock {
1204 let switch_block = blocks.iter().copied().all_equal_value().unwrap_or_else(|_| {
1205 let discr_ty = adt.repr().discr_type().to_ty(self.tcx());
1213 let discr = Place::from(self.new_temp(discr_ty));
1214 let discr_rv = Rvalue::Discriminant(self.place);
1215 self.new_block_with_statements(
1216 unwind,
1217 ::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)],
1218 TerminatorKind::SwitchInt {
1219 discr: Operand::Move(discr),
1220 targets: SwitchTargets::new(
1221 values.iter().copied().zip(blocks.iter().copied()),
1222 *blocks.last().unwrap(),
1223 ),
1224 },
1225 )
1226 });
1227 self.drop_flag_test_block(switch_block, succ, unwind)
1228 }
1229
1230 x;#[instrument(level = "debug", skip(self), ret)]
1231 fn destructor_call_block_sync(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1232 let tcx = self.tcx();
1233 let drop_trait = tcx.require_lang_item(LangItem::Drop, DUMMY_SP);
1234 let drop_fn = tcx.associated_item_def_ids(drop_trait)[0];
1235 let ty = self.place_ty(self.place);
1236
1237 let ref_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
1238 let ref_place = self.new_temp(ref_ty);
1239 let unit_temp = Place::from(self.new_temp(tcx.types.unit));
1240
1241 self.new_block_with_statements(
1242 unwind,
1243 vec![self.assign(
1244 Place::from(ref_place),
1245 Rvalue::Ref(
1246 tcx.lifetimes.re_erased,
1247 BorrowKind::Mut { kind: MutBorrowKind::Default },
1248 self.place,
1249 ),
1250 )],
1251 TerminatorKind::Call {
1252 func: Operand::function_handle(tcx, drop_fn, &[ty.into()], self.source_info.span),
1253 args: [dummy_spanned(Operand::Move(Place::from(ref_place)))].into(),
1254 destination: unit_temp,
1255 target: Some(succ),
1256 unwind: unwind.into_action(),
1257 call_source: CallSource::Misc,
1258 fn_span: self.source_info.span,
1259 },
1260 )
1261 }
1262
1263 x;#[instrument(level = "debug", skip(self), ret)]
1264 fn destructor_call_block(
1265 &mut self,
1266 succ: BasicBlock,
1267 unwind: Unwind,
1268 dropline: Option<BasicBlock>,
1269 ) -> BasicBlock {
1270 let ty = self.place_ty(self.place);
1271 if !unwind.is_cleanup() && self.check_if_can_async_drop(ty, true) {
1272 self.build_async_drop(self.place, ty, succ, unwind, dropline, true)
1273 } else {
1274 self.destructor_call_block_sync(succ, unwind)
1275 }
1276 }
1277
1278 fn drop_loop(
1290 &mut self,
1291 succ: BasicBlock,
1292 cur: Local,
1293 len: Local,
1294 ety: Ty<'tcx>,
1295 unwind: Unwind,
1296 dropline: Option<BasicBlock>,
1297 ) -> BasicBlock {
1298 let copy = |place: Place<'tcx>| Operand::Copy(place);
1299 let move_ = |place: Place<'tcx>| Operand::Move(place);
1300 let tcx = self.tcx();
1301
1302 let ptr_ty = Ty::new_mut_ptr(tcx, ety);
1303 let ptr = Place::from(self.new_temp(ptr_ty));
1304 let can_go = Place::from(self.new_temp(tcx.types.bool));
1305 let one = self.constant_usize(1);
1306
1307 let drop_block = self.new_block_with_statements(
1308 unwind,
1309 ::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![
1310 self.assign(
1311 ptr,
1312 Rvalue::RawPtr(RawPtrKind::Mut, tcx.mk_place_index(self.place, cur)),
1313 ),
1314 self.assign(
1315 cur.into(),
1316 Rvalue::BinaryOp(BinOp::Add, Box::new((move_(cur.into()), one))),
1317 ),
1318 ],
1319 TerminatorKind::Unreachable,
1321 );
1322
1323 let loop_block = self.new_block_with_statements(
1324 unwind,
1325 ::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(
1326 can_go,
1327 Rvalue::BinaryOp(BinOp::Eq, Box::new((copy(Place::from(cur)), copy(len.into())))),
1328 )],
1329 TerminatorKind::if_(move_(can_go), succ, drop_block),
1330 );
1331
1332 let place = tcx.mk_place_deref(ptr);
1333 if !unwind.is_cleanup() && self.check_if_can_async_drop(ety, false) {
1334 let async_drop_bb =
1335 self.build_async_drop(place, ety, loop_block, unwind, dropline, false);
1336 self.elaborator
1337 .patch()
1338 .patch_terminator(drop_block, TerminatorKind::Goto { target: async_drop_bb });
1339 } else {
1340 self.elaborator.patch().patch_terminator(
1341 drop_block,
1342 TerminatorKind::Drop {
1343 place,
1344 target: loop_block,
1345 unwind: unwind.into_action(),
1346 replace: false,
1347 drop: None,
1348 },
1349 );
1350 }
1351 loop_block
1352 }
1353
1354 x;#[instrument(level = "debug", skip(self), ret)]
1355 fn open_drop_for_array(
1356 &mut self,
1357 array_ty: Ty<'tcx>,
1358 ety: Ty<'tcx>,
1359 opt_size: Option<u64>,
1360 ) -> BasicBlock {
1361 let tcx = self.tcx();
1362
1363 if let Some(size) = opt_size {
1364 enum ProjectionKind<Path> {
1365 Drop(std::ops::Range<u64>),
1366 Keep(u64, Path),
1367 }
1368 let mut drop_ranges = vec![];
1373 let mut dropping = true;
1374 let mut start = 0;
1375 for i in 0..size {
1376 let path = self.elaborator.array_subpath(self.path, i, size);
1377 if dropping && path.is_some() {
1378 drop_ranges.push(ProjectionKind::Drop(start..i));
1379 dropping = false;
1380 } else if !dropping && path.is_none() {
1381 dropping = true;
1382 start = i;
1383 }
1384 if let Some(path) = path {
1385 drop_ranges.push(ProjectionKind::Keep(i, path));
1386 }
1387 }
1388 if !drop_ranges.is_empty() {
1389 if dropping {
1390 drop_ranges.push(ProjectionKind::Drop(start..size));
1391 }
1392 let fields = drop_ranges
1393 .iter()
1394 .rev()
1395 .map(|p| {
1396 let (project, path) = match p {
1397 ProjectionKind::Drop(r) => (
1398 ProjectionElem::Subslice {
1399 from: r.start,
1400 to: r.end,
1401 from_end: false,
1402 },
1403 None,
1404 ),
1405 &ProjectionKind::Keep(offset, path) => (
1406 ProjectionElem::ConstantIndex {
1407 offset,
1408 min_length: size,
1409 from_end: false,
1410 },
1411 Some(path),
1412 ),
1413 };
1414 (tcx.mk_place_elem(self.place, project), path)
1415 })
1416 .collect::<Vec<_>>();
1417 let (succ, unwind, dropline) = self.drop_ladder_bottom();
1418 return self.drop_ladder(fields, succ, unwind, dropline).0;
1419 }
1420 }
1421
1422 let array_ptr_ty = Ty::new_mut_ptr(tcx, array_ty);
1423 let array_ptr = self.new_temp(array_ptr_ty);
1424
1425 let slice_ty = Ty::new_slice(tcx, ety);
1426 let slice_ptr_ty = Ty::new_mut_ptr(tcx, slice_ty);
1427 let slice_ptr = self.new_temp(slice_ptr_ty);
1428
1429 let array_place = mem::replace(
1430 &mut self.place,
1431 Place::from(slice_ptr).project_deeper(&[PlaceElem::Deref], tcx),
1432 );
1433 let slice_block = self.drop_loop_trio_for_slice(ety);
1434 self.place = array_place;
1435
1436 self.new_block_with_statements(
1437 self.unwind,
1438 vec![
1439 self.assign(Place::from(array_ptr), Rvalue::RawPtr(RawPtrKind::Mut, self.place)),
1440 self.assign(
1441 Place::from(slice_ptr),
1442 Rvalue::Cast(
1443 CastKind::PointerCoercion(
1444 PointerCoercion::Unsize,
1445 CoercionSource::Implicit,
1446 ),
1447 Operand::Move(Place::from(array_ptr)),
1448 slice_ptr_ty,
1449 ),
1450 ),
1451 ],
1452 TerminatorKind::Goto { target: slice_block },
1453 )
1454 }
1455
1456 x;#[instrument(level = "debug", skip(self), ret)]
1459 fn drop_loop_trio_for_slice(&mut self, ety: Ty<'tcx>) -> BasicBlock {
1460 let tcx = self.tcx();
1461 let len = self.new_temp(tcx.types.usize);
1462 let cur = self.new_temp(tcx.types.usize);
1463
1464 let unwind = self
1465 .unwind
1466 .map(|unwind| self.drop_loop(unwind, cur, len, ety, Unwind::InCleanup, None));
1467
1468 let dropline =
1469 self.dropline.map(|dropline| self.drop_loop(dropline, cur, len, ety, unwind, None));
1470
1471 let loop_block = self.drop_loop(self.succ, cur, len, ety, unwind, dropline);
1472
1473 let [PlaceElem::Deref] = self.place.projection.as_slice() else {
1474 span_bug!(
1475 self.source_info.span,
1476 "Expected place for slice drop shim to be *_n, but it's {:?}",
1477 self.place,
1478 );
1479 };
1480
1481 let zero = self.constant_usize(0);
1482 let drop_block = self.new_block_with_statements(
1483 unwind,
1484 vec![
1485 self.assign(
1486 len.into(),
1487 Rvalue::UnaryOp(
1488 UnOp::PtrMetadata,
1489 Operand::Copy(Place::from(self.place.local)),
1490 ),
1491 ),
1492 self.assign(cur.into(), Rvalue::Use(zero, WithRetag::Yes)),
1493 ],
1494 TerminatorKind::Goto { target: loop_block },
1495 );
1496
1497 let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
1499 self.drop_flag_test_block(reset_block, self.succ, unwind)
1500 }
1501
1502 fn open_drop(&mut self) -> BasicBlock {
1511 let ty = self.place_ty(self.place);
1512 match ty.kind() {
1513 ty::Closure(_, args) => self.open_drop_for_tuple(args.as_closure().upvar_tys()),
1514 ty::CoroutineClosure(_, args) => {
1515 self.open_drop_for_tuple(args.as_coroutine_closure().upvar_tys())
1516 }
1517 ty::Coroutine(_, args) => self.open_drop_for_tuple(args.as_coroutine().upvar_tys()),
1524 ty::Tuple(fields) => self.open_drop_for_tuple(fields),
1525 ty::Adt(def, args) => self.open_drop_for_adt(*def, args),
1526 ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind),
1527 ty::Array(ety, size) => {
1528 let size = size.try_to_target_usize(self.tcx());
1529 self.open_drop_for_array(ty, *ety, size)
1530 }
1531 ty::Slice(ety) => self.drop_loop_trio_for_slice(*ety),
1532
1533 ty::UnsafeBinder(_) => {
1534 self.tcx().dcx().span_delayed_bug(
1537 self.source_info.span,
1538 "open drop for unsafe binder shouldn't be encountered",
1539 );
1540 self.new_block(self.unwind, TerminatorKind::Unreachable)
1541 }
1542
1543 _ => ::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),
1544 }
1545 }
1546
1547 x;#[instrument(level = "debug", skip(self), ret)]
1548 fn complete_drop(&mut self, succ: BasicBlock, unwind: Unwind) -> BasicBlock {
1549 let drop_block = self.drop_block(succ, unwind);
1550 self.drop_flag_test_block(drop_block, succ, unwind)
1551 }
1552
1553 x;#[instrument(level = "debug", skip(self), ret)]
1556 fn drop_flag_reset_block(
1557 &mut self,
1558 mode: DropFlagMode,
1559 succ: BasicBlock,
1560 unwind: Unwind,
1561 ) -> BasicBlock {
1562 if unwind.is_cleanup() {
1563 return succ;
1566 }
1567 let flags = self.elaborator.drop_flags_for(self.path, mode);
1568 let statements: Vec<_> = flags
1569 .into_iter()
1570 .map(|flag| {
1571 self.assign(
1572 flag,
1573 Rvalue::Use(self.constant_bool(DropFlagState::Absent.value()), WithRetag::Yes),
1574 )
1575 })
1576 .collect();
1577 if statements.is_empty() {
1578 return succ;
1579 }
1580 self.new_block_with_statements(unwind, statements, TerminatorKind::Goto { target: succ })
1581 }
1582
1583 x;#[instrument(level = "debug", skip(self), ret)]
1584 fn elaborated_drop_block(&mut self) -> BasicBlock {
1585 let blk = self.new_block(
1586 self.unwind,
1587 TerminatorKind::Drop {
1588 place: self.place,
1589 target: self.succ,
1590 unwind: self.unwind.into_action(),
1591 replace: false,
1592 drop: self.dropline,
1593 },
1594 );
1595 self.elaborate_drop(blk);
1596 blk
1597 }
1598
1599 fn drop_block(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
1600 let drop_ty = self.place_ty(self.place);
1601 if !unwind.is_cleanup() && self.check_if_can_async_drop(drop_ty, false) {
1602 self.build_async_drop(self.place, drop_ty, self.succ, unwind, self.dropline, false)
1603 } else {
1604 self.new_block(
1605 unwind,
1606 TerminatorKind::Drop {
1607 place: self.place,
1608 target,
1609 unwind: unwind.into_action(),
1610 replace: false,
1611 drop: None,
1612 },
1613 )
1614 }
1615 }
1616
1617 x;#[instrument(level = "debug", skip(self), ret)]
1623 fn drop_flag_test_block(
1624 &mut self,
1625 on_set: BasicBlock,
1626 on_unset: BasicBlock,
1627 unwind: Unwind,
1628 ) -> BasicBlock {
1629 let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
1630 match style {
1631 DropStyle::Dead => on_unset,
1632 DropStyle::Static => on_set,
1633 DropStyle::Conditional | DropStyle::Open => {
1634 let flag = self.elaborator.get_drop_flag(self.path).unwrap();
1635 let term = TerminatorKind::if_(flag, on_set, on_unset);
1636 self.new_block(unwind, term)
1637 }
1638 }
1639 }
1640
1641 x;#[instrument(level = "trace", skip(self), ret)]
1642 fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock {
1643 self.elaborator.patch().new_block(BasicBlockData::new(
1644 Some(Terminator { source_info: self.source_info, kind: k, attributes: ThinVec::new() }),
1645 unwind.is_cleanup(),
1646 ))
1647 }
1648
1649 x;#[instrument(level = "trace", skip(self, statements), ret)]
1650 fn new_block_with_statements(
1651 &mut self,
1652 unwind: Unwind,
1653 statements: Vec<Statement<'tcx>>,
1654 k: TerminatorKind<'tcx>,
1655 ) -> BasicBlock {
1656 self.elaborator.patch().new_block(BasicBlockData::new_stmts(
1657 statements,
1658 Some(Terminator { source_info: self.source_info, kind: k, attributes: ThinVec::new() }),
1659 unwind.is_cleanup(),
1660 ))
1661 }
1662
1663 fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
1664 self.elaborator.patch().new_temp(ty, self.source_info.span)
1665 }
1666
1667 fn constant_usize(&self, val: u16) -> Operand<'tcx> {
1668 Operand::Constant(Box::new(ConstOperand {
1669 span: self.source_info.span,
1670 user_ty: None,
1671 const_: Const::from_usize(self.tcx(), val.into()),
1672 }))
1673 }
1674
1675 fn constant_bool(&self, val: bool) -> Operand<'tcx> {
1676 Operand::Constant(Box::new(ConstOperand {
1677 span: self.source_info.span,
1678 user_ty: None,
1679 const_: Const::from_bool(self.tcx(), val),
1680 }))
1681 }
1682
1683 fn assign(&self, lhs: Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
1684 Statement::new(self.source_info, StatementKind::Assign(Box::new((lhs, rhs))))
1685 }
1686
1687 fn storage_live(&self, local: Local) -> Statement<'tcx> {
1688 Statement::new(self.source_info, StatementKind::StorageLive(local))
1689 }
1690
1691 fn storage_dead(&self, local: Local) -> Statement<'tcx> {
1692 Statement::new(self.source_info, StatementKind::StorageDead(local))
1693 }
1694}