1mod by_move_body;
54mod drop;
55use std::{iter, ops};
56
57pub(super) use by_move_body::coroutine_by_move_body_def_id;
58use drop::{
59 cleanup_async_drops, create_coroutine_drop_shim, create_coroutine_drop_shim_async,
60 create_coroutine_drop_shim_proxy_async, elaborate_coroutine_drops, expand_async_drops,
61 has_expandable_async_drops, insert_clean_drop,
62};
63use rustc_abi::{FieldIdx, VariantIdx};
64use rustc_data_structures::fx::FxHashSet;
65use rustc_errors::pluralize;
66use rustc_hir as hir;
67use rustc_hir::lang_items::LangItem;
68use rustc_hir::{CoroutineDesugaring, CoroutineKind};
69use rustc_index::bit_set::{BitMatrix, DenseBitSet, GrowableBitSet};
70use rustc_index::{Idx, IndexVec};
71use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
72use rustc_middle::mir::*;
73use rustc_middle::ty::util::Discr;
74use rustc_middle::ty::{
75 self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, Ty, TyCtxt, TypingMode,
76};
77use rustc_middle::{bug, span_bug};
78use rustc_mir_dataflow::impls::{
79 MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
80 always_storage_live_locals,
81};
82use rustc_mir_dataflow::{
83 Analysis, Results, ResultsCursor, ResultsVisitor, visit_reachable_results,
84};
85use rustc_span::def_id::{DefId, LocalDefId};
86use rustc_span::source_map::dummy_spanned;
87use rustc_span::symbol::sym;
88use rustc_span::{DUMMY_SP, Span};
89use rustc_target::spec::PanicStrategy;
90use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
91use rustc_trait_selection::infer::TyCtxtInferExt as _;
92use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt};
93use tracing::{debug, instrument, trace};
94
95use crate::deref_separator::deref_finder;
96use crate::{abort_unwinding_calls, errors, pass_manager as pm, simplify};
97
98pub(super) struct StateTransform;
99
100struct RenameLocalVisitor<'tcx> {
101 from: Local,
102 to: Local,
103 tcx: TyCtxt<'tcx>,
104}
105
106impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
107 fn tcx(&self) -> TyCtxt<'tcx> {
108 self.tcx
109 }
110
111 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
112 if *local == self.from {
113 *local = self.to;
114 }
115 }
116
117 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
118 match terminator.kind {
119 TerminatorKind::Return => {
120 }
123 _ => self.super_terminator(terminator, location),
124 }
125 }
126}
127
128struct SelfArgVisitor<'tcx> {
129 tcx: TyCtxt<'tcx>,
130 new_base: Place<'tcx>,
131}
132
133impl<'tcx> SelfArgVisitor<'tcx> {
134 fn new(tcx: TyCtxt<'tcx>, elem: ProjectionElem<Local, Ty<'tcx>>) -> Self {
135 Self { tcx, new_base: Place { local: SELF_ARG, projection: tcx.mk_place_elems(&[elem]) } }
136 }
137}
138
139impl<'tcx> MutVisitor<'tcx> for SelfArgVisitor<'tcx> {
140 fn tcx(&self) -> TyCtxt<'tcx> {
141 self.tcx
142 }
143
144 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
145 assert_ne!(*local, SELF_ARG);
146 }
147
148 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
149 if place.local == SELF_ARG {
150 replace_base(place, self.new_base, self.tcx);
151 } else {
152 self.visit_local(&mut place.local, context, location);
153
154 for elem in place.projection.iter() {
155 if let PlaceElem::Index(local) = elem {
156 assert_ne!(local, SELF_ARG);
157 }
158 }
159 }
160 }
161}
162
163fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
164 place.local = new_base.local;
165
166 let mut new_projection = new_base.projection.to_vec();
167 new_projection.append(&mut place.projection.to_vec());
168
169 place.projection = tcx.mk_place_elems(&new_projection);
170}
171
172const SELF_ARG: Local = Local::from_u32(1);
173const CTX_ARG: Local = Local::from_u32(2);
174
175struct SuspensionPoint<'tcx> {
177 state: usize,
179 resume: BasicBlock,
181 resume_arg: Place<'tcx>,
183 drop: Option<BasicBlock>,
185 storage_liveness: GrowableBitSet<Local>,
187}
188
189struct TransformVisitor<'tcx> {
190 tcx: TyCtxt<'tcx>,
191 coroutine_kind: hir::CoroutineKind,
192
193 discr_ty: Ty<'tcx>,
195
196 remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
198
199 storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
201
202 suspension_points: Vec<SuspensionPoint<'tcx>>,
204
205 always_live_locals: DenseBitSet<Local>,
207
208 old_ret_local: Local,
210
211 old_yield_ty: Ty<'tcx>,
212
213 old_ret_ty: Ty<'tcx>,
214}
215
216impl<'tcx> TransformVisitor<'tcx> {
217 fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
218 let block = body.basic_blocks.next_index();
219 let source_info = SourceInfo::outermost(body.span);
220
221 let none_value = match self.coroutine_kind {
222 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
223 span_bug!(body.span, "`Future`s are not fused inherently")
224 }
225 CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
226 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
228 let option_def_id = self.tcx.require_lang_item(LangItem::Option, None);
229 make_aggregate_adt(
230 option_def_id,
231 VariantIdx::ZERO,
232 self.tcx.mk_args(&[self.old_yield_ty.into()]),
233 IndexVec::new(),
234 )
235 }
236 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
238 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
239 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
240 let yield_ty = args.type_at(0);
241 Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
242 span: source_info.span,
243 const_: Const::Unevaluated(
244 UnevaluatedConst::new(
245 self.tcx.require_lang_item(LangItem::AsyncGenFinished, None),
246 self.tcx.mk_args(&[yield_ty.into()]),
247 ),
248 self.old_yield_ty,
249 ),
250 user_ty: None,
251 })))
252 }
253 };
254
255 let statements = vec![Statement {
256 kind: StatementKind::Assign(Box::new((Place::return_place(), none_value))),
257 source_info,
258 }];
259
260 body.basic_blocks_mut().push(BasicBlockData {
261 statements,
262 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
263 is_cleanup: false,
264 });
265
266 block
267 }
268
269 fn make_state(
275 &self,
276 val: Operand<'tcx>,
277 source_info: SourceInfo,
278 is_return: bool,
279 statements: &mut Vec<Statement<'tcx>>,
280 ) {
281 const ZERO: VariantIdx = VariantIdx::ZERO;
282 const ONE: VariantIdx = VariantIdx::from_usize(1);
283 let rvalue = match self.coroutine_kind {
284 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
285 let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, None);
286 let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
287 let (variant_idx, operands) = if is_return {
288 (ZERO, IndexVec::from_raw(vec![val])) } else {
290 (ONE, IndexVec::new()) };
292 make_aggregate_adt(poll_def_id, variant_idx, args, operands)
293 }
294 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
295 let option_def_id = self.tcx.require_lang_item(LangItem::Option, None);
296 let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
297 let (variant_idx, operands) = if is_return {
298 (ZERO, IndexVec::new()) } else {
300 (ONE, IndexVec::from_raw(vec![val])) };
302 make_aggregate_adt(option_def_id, variant_idx, args, operands)
303 }
304 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
305 if is_return {
306 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
307 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
308 let yield_ty = args.type_at(0);
309 Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
310 span: source_info.span,
311 const_: Const::Unevaluated(
312 UnevaluatedConst::new(
313 self.tcx.require_lang_item(LangItem::AsyncGenFinished, None),
314 self.tcx.mk_args(&[yield_ty.into()]),
315 ),
316 self.old_yield_ty,
317 ),
318 user_ty: None,
319 })))
320 } else {
321 Rvalue::Use(val)
322 }
323 }
324 CoroutineKind::Coroutine(_) => {
325 let coroutine_state_def_id =
326 self.tcx.require_lang_item(LangItem::CoroutineState, None);
327 let args = self.tcx.mk_args(&[self.old_yield_ty.into(), self.old_ret_ty.into()]);
328 let variant_idx = if is_return {
329 ONE } else {
331 ZERO };
333 make_aggregate_adt(
334 coroutine_state_def_id,
335 variant_idx,
336 args,
337 IndexVec::from_raw(vec![val]),
338 )
339 }
340 };
341
342 statements.push(Statement {
343 kind: StatementKind::Assign(Box::new((Place::return_place(), rvalue))),
344 source_info,
345 });
346 }
347
348 fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
350 let self_place = Place::from(SELF_ARG);
351 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
352 let mut projection = base.projection.to_vec();
353 projection.push(ProjectionElem::Field(idx, ty));
354
355 Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
356 }
357
358 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
360 let self_place = Place::from(SELF_ARG);
361 Statement {
362 source_info,
363 kind: StatementKind::SetDiscriminant {
364 place: Box::new(self_place),
365 variant_index: state_disc,
366 },
367 }
368 }
369
370 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
372 let temp_decl = LocalDecl::new(self.discr_ty, body.span);
373 let local_decls_len = body.local_decls.push(temp_decl);
374 let temp = Place::from(local_decls_len);
375
376 let self_place = Place::from(SELF_ARG);
377 let assign = Statement {
378 source_info: SourceInfo::outermost(body.span),
379 kind: StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
380 };
381 (assign, temp)
382 }
383}
384
385impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
386 fn tcx(&self) -> TyCtxt<'tcx> {
387 self.tcx
388 }
389
390 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
391 assert!(!self.remap.contains(*local));
392 }
393
394 fn visit_place(
395 &mut self,
396 place: &mut Place<'tcx>,
397 _context: PlaceContext,
398 _location: Location,
399 ) {
400 if let Some(&Some((ty, variant_index, idx))) = self.remap.get(place.local) {
402 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
403 }
404 }
405
406 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
407 for s in &mut data.statements {
409 if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = s.kind
410 && self.remap.contains(l)
411 {
412 s.make_nop();
413 }
414 }
415
416 let ret_val = match data.terminator().kind {
417 TerminatorKind::Return => {
418 Some((true, None, Operand::Move(Place::from(self.old_ret_local)), None))
419 }
420 TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
421 Some((false, Some((resume, resume_arg)), value.clone(), drop))
422 }
423 _ => None,
424 };
425
426 if let Some((is_return, resume, v, drop)) = ret_val {
427 let source_info = data.terminator().source_info;
428 self.make_state(v, source_info, is_return, &mut data.statements);
430 let state = if let Some((resume, mut resume_arg)) = resume {
431 let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
433
434 if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
437 replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
438 }
439
440 let storage_liveness: GrowableBitSet<Local> =
441 self.storage_liveness[block].clone().unwrap().into();
442
443 for i in 0..self.always_live_locals.domain_size() {
444 let l = Local::new(i);
445 let needs_storage_dead = storage_liveness.contains(l)
446 && !self.remap.contains(l)
447 && !self.always_live_locals.contains(l);
448 if needs_storage_dead {
449 data.statements
450 .push(Statement { source_info, kind: StatementKind::StorageDead(l) });
451 }
452 }
453
454 self.suspension_points.push(SuspensionPoint {
455 state,
456 resume,
457 resume_arg,
458 drop,
459 storage_liveness,
460 });
461
462 VariantIdx::new(state)
463 } else {
464 VariantIdx::new(CoroutineArgs::RETURNED) };
467 data.statements.push(self.set_discr(state, source_info));
468 data.terminator_mut().kind = TerminatorKind::Return;
469 }
470
471 self.super_basic_block_data(block, data);
472 }
473}
474
475fn make_aggregate_adt<'tcx>(
476 def_id: DefId,
477 variant_idx: VariantIdx,
478 args: GenericArgsRef<'tcx>,
479 operands: IndexVec<FieldIdx, Operand<'tcx>>,
480) -> Rvalue<'tcx> {
481 Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
482}
483
484fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
485 let coroutine_ty = body.local_decls.raw[1].ty;
486
487 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
488
489 body.local_decls.raw[1].ty = ref_coroutine_ty;
491
492 SelfArgVisitor::new(tcx, ProjectionElem::Deref).visit_body(body);
494}
495
496fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
497 let ref_coroutine_ty = body.local_decls.raw[1].ty;
498
499 let pin_did = tcx.require_lang_item(LangItem::Pin, Some(body.span));
500 let pin_adt_ref = tcx.adt_def(pin_did);
501 let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
502 let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
503
504 body.local_decls.raw[1].ty = pin_ref_coroutine_ty;
506
507 SelfArgVisitor::new(tcx, ProjectionElem::Field(FieldIdx::ZERO, ref_coroutine_ty))
509 .visit_body(body);
510}
511
512fn replace_local<'tcx>(
519 local: Local,
520 ty: Ty<'tcx>,
521 body: &mut Body<'tcx>,
522 tcx: TyCtxt<'tcx>,
523) -> Local {
524 let new_decl = LocalDecl::new(ty, body.span);
525 let new_local = body.local_decls.push(new_decl);
526 body.local_decls.swap(local, new_local);
527
528 RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
529
530 new_local
531}
532
533fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> Ty<'tcx> {
555 let context_mut_ref = Ty::new_task_context(tcx);
556
557 replace_resume_ty_local(tcx, body, CTX_ARG, context_mut_ref);
559
560 let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, None);
561
562 for bb in body.basic_blocks.indices() {
563 let bb_data = &body[bb];
564 if bb_data.is_cleanup {
565 continue;
566 }
567
568 match &bb_data.terminator().kind {
569 TerminatorKind::Call { func, .. } => {
570 let func_ty = func.ty(body, tcx);
571 if let ty::FnDef(def_id, _) = *func_ty.kind()
572 && def_id == get_context_def_id
573 {
574 let local = eliminate_get_context_call(&mut body[bb]);
575 replace_resume_ty_local(tcx, body, local, context_mut_ref);
576 }
577 }
578 TerminatorKind::Yield { resume_arg, .. } => {
579 replace_resume_ty_local(tcx, body, resume_arg.local, context_mut_ref);
580 }
581 _ => {}
582 }
583 }
584 context_mut_ref
585}
586
587fn eliminate_get_context_call<'tcx>(bb_data: &mut BasicBlockData<'tcx>) -> Local {
588 let terminator = bb_data.terminator.take().unwrap();
589 let TerminatorKind::Call { args, destination, target, .. } = terminator.kind else {
590 bug!();
591 };
592 let [arg] = *Box::try_from(args).unwrap();
593 let local = arg.node.place().unwrap().local;
594
595 let arg = Rvalue::Use(arg.node);
596 let assign = Statement {
597 source_info: terminator.source_info,
598 kind: StatementKind::Assign(Box::new((destination, arg))),
599 };
600 bb_data.statements.push(assign);
601 bb_data.terminator = Some(Terminator {
602 source_info: terminator.source_info,
603 kind: TerminatorKind::Goto { target: target.unwrap() },
604 });
605 local
606}
607
608#[cfg_attr(not(debug_assertions), allow(unused))]
609fn replace_resume_ty_local<'tcx>(
610 tcx: TyCtxt<'tcx>,
611 body: &mut Body<'tcx>,
612 local: Local,
613 context_mut_ref: Ty<'tcx>,
614) {
615 let local_ty = std::mem::replace(&mut body.local_decls[local].ty, context_mut_ref);
616 #[cfg(debug_assertions)]
619 {
620 if let ty::Adt(resume_ty_adt, _) = local_ty.kind() {
621 let expected_adt = tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
622 assert_eq!(*resume_ty_adt, expected_adt);
623 } else {
624 panic!("expected `ResumeTy`, found `{:?}`", local_ty);
625 };
626 }
627}
628
629fn transform_gen_context<'tcx>(body: &mut Body<'tcx>) {
639 body.arg_count = 1;
643}
644
645struct LivenessInfo {
646 saved_locals: CoroutineSavedLocals,
648
649 live_locals_at_suspension_points: Vec<DenseBitSet<CoroutineSavedLocal>>,
651
652 source_info_at_suspension_points: Vec<SourceInfo>,
654
655 storage_conflicts: BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
659
660 storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
663}
664
665fn locals_live_across_suspend_points<'tcx>(
674 tcx: TyCtxt<'tcx>,
675 body: &Body<'tcx>,
676 always_live_locals: &DenseBitSet<Local>,
677 movable: bool,
678) -> LivenessInfo {
679 let mut storage_live = MaybeStorageLive::new(std::borrow::Cow::Borrowed(always_live_locals))
682 .iterate_to_fixpoint(tcx, body, None)
683 .into_results_cursor(body);
684
685 let borrowed_locals = MaybeBorrowedLocals.iterate_to_fixpoint(tcx, body, Some("coroutine"));
687 let mut borrowed_locals_analysis1 = borrowed_locals.analysis;
688 let mut borrowed_locals_analysis2 = borrowed_locals_analysis1.clone(); let borrowed_locals_cursor1 = ResultsCursor::new_borrowing(
690 body,
691 &mut borrowed_locals_analysis1,
692 &borrowed_locals.results,
693 );
694 let mut borrowed_locals_cursor2 = ResultsCursor::new_borrowing(
695 body,
696 &mut borrowed_locals_analysis2,
697 &borrowed_locals.results,
698 );
699
700 let mut requires_storage =
702 MaybeRequiresStorage::new(borrowed_locals_cursor1).iterate_to_fixpoint(tcx, body, None);
703 let mut requires_storage_cursor = ResultsCursor::new_borrowing(
704 body,
705 &mut requires_storage.analysis,
706 &requires_storage.results,
707 );
708
709 let mut liveness =
711 MaybeLiveLocals.iterate_to_fixpoint(tcx, body, Some("coroutine")).into_results_cursor(body);
712
713 let mut storage_liveness_map = IndexVec::from_elem(None, &body.basic_blocks);
714 let mut live_locals_at_suspension_points = Vec::new();
715 let mut source_info_at_suspension_points = Vec::new();
716 let mut live_locals_at_any_suspension_point = DenseBitSet::new_empty(body.local_decls.len());
717
718 for (block, data) in body.basic_blocks.iter_enumerated() {
719 if let TerminatorKind::Yield { .. } = data.terminator().kind {
720 let loc = Location { block, statement_index: data.statements.len() };
721
722 liveness.seek_to_block_end(block);
723 let mut live_locals = liveness.get().clone();
724
725 if !movable {
726 borrowed_locals_cursor2.seek_before_primary_effect(loc);
737 live_locals.union(borrowed_locals_cursor2.get());
738 }
739
740 storage_live.seek_before_primary_effect(loc);
743 storage_liveness_map[block] = Some(storage_live.get().clone());
744
745 requires_storage_cursor.seek_before_primary_effect(loc);
749 live_locals.intersect(requires_storage_cursor.get());
750
751 live_locals.remove(SELF_ARG);
753
754 debug!("loc = {:?}, live_locals = {:?}", loc, live_locals);
755
756 live_locals_at_any_suspension_point.union(&live_locals);
759
760 live_locals_at_suspension_points.push(live_locals);
761 source_info_at_suspension_points.push(data.terminator().source_info);
762 }
763 }
764
765 debug!("live_locals_anywhere = {:?}", live_locals_at_any_suspension_point);
766 let saved_locals = CoroutineSavedLocals(live_locals_at_any_suspension_point);
767
768 let live_locals_at_suspension_points = live_locals_at_suspension_points
771 .iter()
772 .map(|live_here| saved_locals.renumber_bitset(live_here))
773 .collect();
774
775 let storage_conflicts = compute_storage_conflicts(
776 body,
777 &saved_locals,
778 always_live_locals.clone(),
779 &mut requires_storage.analysis,
780 &requires_storage.results,
781 );
782
783 LivenessInfo {
784 saved_locals,
785 live_locals_at_suspension_points,
786 source_info_at_suspension_points,
787 storage_conflicts,
788 storage_liveness: storage_liveness_map,
789 }
790}
791
792struct CoroutineSavedLocals(DenseBitSet<Local>);
798
799impl CoroutineSavedLocals {
800 fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (CoroutineSavedLocal, Local)> {
803 self.iter().enumerate().map(|(i, l)| (CoroutineSavedLocal::from(i), l))
804 }
805
806 fn renumber_bitset(&self, input: &DenseBitSet<Local>) -> DenseBitSet<CoroutineSavedLocal> {
809 assert!(self.superset(input), "{:?} not a superset of {:?}", self.0, input);
810 let mut out = DenseBitSet::new_empty(self.count());
811 for (saved_local, local) in self.iter_enumerated() {
812 if input.contains(local) {
813 out.insert(saved_local);
814 }
815 }
816 out
817 }
818
819 fn get(&self, local: Local) -> Option<CoroutineSavedLocal> {
820 if !self.contains(local) {
821 return None;
822 }
823
824 let idx = self.iter().take_while(|&l| l < local).count();
825 Some(CoroutineSavedLocal::new(idx))
826 }
827}
828
829impl ops::Deref for CoroutineSavedLocals {
830 type Target = DenseBitSet<Local>;
831
832 fn deref(&self) -> &Self::Target {
833 &self.0
834 }
835}
836
837fn compute_storage_conflicts<'mir, 'tcx>(
842 body: &'mir Body<'tcx>,
843 saved_locals: &'mir CoroutineSavedLocals,
844 always_live_locals: DenseBitSet<Local>,
845 analysis: &mut MaybeRequiresStorage<'mir, 'tcx>,
846 results: &Results<DenseBitSet<Local>>,
847) -> BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal> {
848 assert_eq!(body.local_decls.len(), saved_locals.domain_size());
849
850 debug!("compute_storage_conflicts({:?})", body.span);
851 debug!("always_live = {:?}", always_live_locals);
852
853 let mut ineligible_locals = always_live_locals;
856 ineligible_locals.intersect(&**saved_locals);
857
858 let mut visitor = StorageConflictVisitor {
860 body,
861 saved_locals,
862 local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
863 eligible_storage_live: DenseBitSet::new_empty(body.local_decls.len()),
864 };
865
866 visit_reachable_results(body, analysis, results, &mut visitor);
867
868 let local_conflicts = visitor.local_conflicts;
869
870 let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
878 for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
879 if ineligible_locals.contains(local_a) {
880 storage_conflicts.insert_all_into_row(saved_local_a);
882 } else {
883 for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
885 if local_conflicts.contains(local_a, local_b) {
886 storage_conflicts.insert(saved_local_a, saved_local_b);
887 }
888 }
889 }
890 }
891 storage_conflicts
892}
893
894struct StorageConflictVisitor<'a, 'tcx> {
895 body: &'a Body<'tcx>,
896 saved_locals: &'a CoroutineSavedLocals,
897 local_conflicts: BitMatrix<Local, Local>,
900 eligible_storage_live: DenseBitSet<Local>,
902}
903
904impl<'a, 'tcx> ResultsVisitor<'tcx, MaybeRequiresStorage<'a, 'tcx>>
905 for StorageConflictVisitor<'a, 'tcx>
906{
907 fn visit_after_early_statement_effect(
908 &mut self,
909 _analysis: &mut MaybeRequiresStorage<'a, 'tcx>,
910 state: &DenseBitSet<Local>,
911 _statement: &Statement<'tcx>,
912 loc: Location,
913 ) {
914 self.apply_state(state, loc);
915 }
916
917 fn visit_after_early_terminator_effect(
918 &mut self,
919 _analysis: &mut MaybeRequiresStorage<'a, 'tcx>,
920 state: &DenseBitSet<Local>,
921 _terminator: &Terminator<'tcx>,
922 loc: Location,
923 ) {
924 self.apply_state(state, loc);
925 }
926}
927
928impl StorageConflictVisitor<'_, '_> {
929 fn apply_state(&mut self, state: &DenseBitSet<Local>, loc: Location) {
930 if let TerminatorKind::Unreachable = self.body.basic_blocks[loc.block].terminator().kind {
932 return;
933 }
934
935 self.eligible_storage_live.clone_from(state);
936 self.eligible_storage_live.intersect(&**self.saved_locals);
937
938 for local in self.eligible_storage_live.iter() {
939 self.local_conflicts.union_row_with(&self.eligible_storage_live, local);
940 }
941
942 if self.eligible_storage_live.count() > 1 {
943 trace!("at {:?}, eligible_storage_live={:?}", loc, self.eligible_storage_live);
944 }
945 }
946}
947
948fn compute_layout<'tcx>(
949 liveness: LivenessInfo,
950 body: &Body<'tcx>,
951) -> (
952 IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
953 CoroutineLayout<'tcx>,
954 IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
955) {
956 let LivenessInfo {
957 saved_locals,
958 live_locals_at_suspension_points,
959 source_info_at_suspension_points,
960 storage_conflicts,
961 storage_liveness,
962 } = liveness;
963
964 let mut locals = IndexVec::<CoroutineSavedLocal, _>::new();
966 let mut tys = IndexVec::<CoroutineSavedLocal, _>::new();
967 for (saved_local, local) in saved_locals.iter_enumerated() {
968 debug!("coroutine saved local {:?} => {:?}", saved_local, local);
969
970 locals.push(local);
971 let decl = &body.local_decls[local];
972 debug!(?decl);
973
974 let ignore_for_traits = match decl.local_info {
979 ClearCrossCrate::Set(box LocalInfo::StaticRef { is_thread_local, .. }) => {
982 !is_thread_local
983 }
984 ClearCrossCrate::Set(box LocalInfo::FakeBorrow) => true,
987 _ => false,
988 };
989 let decl =
990 CoroutineSavedTy { ty: decl.ty, source_info: decl.source_info, ignore_for_traits };
991 debug!(?decl);
992
993 tys.push(decl);
994 }
995
996 let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
1000 let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = [
1001 SourceInfo::outermost(body_span.shrink_to_lo()),
1002 SourceInfo::outermost(body_span.shrink_to_hi()),
1003 SourceInfo::outermost(body_span.shrink_to_hi()),
1004 ]
1005 .iter()
1006 .copied()
1007 .collect();
1008
1009 let mut variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1012 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1013 let mut remap = IndexVec::from_elem_n(None, saved_locals.domain_size());
1014 for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
1015 let variant_index =
1016 VariantIdx::from(CoroutineArgs::RESERVED_VARIANTS + suspension_point_idx);
1017 let mut fields = IndexVec::new();
1018 for (idx, saved_local) in live_locals.iter().enumerate() {
1019 fields.push(saved_local);
1020 let idx = FieldIdx::from_usize(idx);
1025 remap[locals[saved_local]] = Some((tys[saved_local].ty, variant_index, idx));
1026 }
1027 variant_fields.push(fields);
1028 variant_source_info.push(source_info_at_suspension_points[suspension_point_idx]);
1029 }
1030 debug!("coroutine variant_fields = {:?}", variant_fields);
1031 debug!("coroutine storage_conflicts = {:#?}", storage_conflicts);
1032
1033 let mut field_names = IndexVec::from_elem(None, &tys);
1034 for var in &body.var_debug_info {
1035 let VarDebugInfoContents::Place(place) = &var.value else { continue };
1036 let Some(local) = place.as_local() else { continue };
1037 let Some(&Some((_, variant, field))) = remap.get(local) else {
1038 continue;
1039 };
1040
1041 let saved_local = variant_fields[variant][field];
1042 field_names.get_or_insert_with(saved_local, || var.name);
1043 }
1044
1045 let layout = CoroutineLayout {
1046 field_tys: tys,
1047 field_names,
1048 variant_fields,
1049 variant_source_info,
1050 storage_conflicts,
1051 };
1052 debug!(?layout);
1053
1054 (remap, layout, storage_liveness)
1055}
1056
1057fn insert_switch<'tcx>(
1062 body: &mut Body<'tcx>,
1063 cases: Vec<(usize, BasicBlock)>,
1064 transform: &TransformVisitor<'tcx>,
1065 default_block: BasicBlock,
1066) {
1067 let (assign, discr) = transform.get_discr(body);
1068 let switch_targets =
1069 SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
1070 let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
1071
1072 let source_info = SourceInfo::outermost(body.span);
1073 body.basic_blocks_mut().raw.insert(
1074 0,
1075 BasicBlockData {
1076 statements: vec![assign],
1077 terminator: Some(Terminator { source_info, kind: switch }),
1078 is_cleanup: false,
1079 },
1080 );
1081
1082 for b in body.basic_blocks_mut().iter_mut() {
1083 b.terminator_mut().successors_mut(|target| *target += 1);
1084 }
1085}
1086
1087fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
1088 let source_info = SourceInfo::outermost(body.span);
1089 body.basic_blocks_mut().push(BasicBlockData {
1090 statements: Vec::new(),
1091 terminator: Some(Terminator { source_info, kind }),
1092 is_cleanup: false,
1093 })
1094}
1095
1096fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
1097 let poll_def_id = tcx.require_lang_item(LangItem::Poll, None);
1099 let args = tcx.mk_args(&[tcx.types.unit.into()]);
1100 let val = Operand::Constant(Box::new(ConstOperand {
1101 span: source_info.span,
1102 user_ty: None,
1103 const_: Const::zero_sized(tcx.types.unit),
1104 }));
1105 let ready_val = Rvalue::Aggregate(
1106 Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
1107 IndexVec::from_raw(vec![val]),
1108 );
1109 Statement {
1110 kind: StatementKind::Assign(Box::new((Place::return_place(), ready_val))),
1111 source_info,
1112 }
1113}
1114
1115fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
1116 let source_info = SourceInfo::outermost(body.span);
1117 body.basic_blocks_mut().push(BasicBlockData {
1118 statements: [return_poll_ready_assign(tcx, source_info)].to_vec(),
1119 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
1120 is_cleanup: false,
1121 })
1122}
1123
1124fn insert_panic_block<'tcx>(
1125 tcx: TyCtxt<'tcx>,
1126 body: &mut Body<'tcx>,
1127 message: AssertMessage<'tcx>,
1128) -> BasicBlock {
1129 let assert_block = body.basic_blocks.next_index();
1130 let kind = TerminatorKind::Assert {
1131 cond: Operand::Constant(Box::new(ConstOperand {
1132 span: body.span,
1133 user_ty: None,
1134 const_: Const::from_bool(tcx, false),
1135 })),
1136 expected: true,
1137 msg: Box::new(message),
1138 target: assert_block,
1139 unwind: UnwindAction::Continue,
1140 };
1141
1142 insert_term_block(body, kind)
1143}
1144
1145fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1146 if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
1148 return false;
1149 }
1150
1151 body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
1153 }
1155
1156fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1157 if tcx.sess.panic_strategy() == PanicStrategy::Abort {
1159 return false;
1160 }
1161
1162 for block in body.basic_blocks.iter() {
1164 match block.terminator().kind {
1165 TerminatorKind::Goto { .. }
1167 | TerminatorKind::SwitchInt { .. }
1168 | TerminatorKind::UnwindTerminate(_)
1169 | TerminatorKind::Return
1170 | TerminatorKind::Unreachable
1171 | TerminatorKind::CoroutineDrop
1172 | TerminatorKind::FalseEdge { .. }
1173 | TerminatorKind::FalseUnwind { .. } => {}
1174
1175 TerminatorKind::UnwindResume => {}
1178
1179 TerminatorKind::Yield { .. } => {
1180 unreachable!("`can_unwind` called before coroutine transform")
1181 }
1182
1183 TerminatorKind::Drop { .. }
1185 | TerminatorKind::Call { .. }
1186 | TerminatorKind::InlineAsm { .. }
1187 | TerminatorKind::Assert { .. } => return true,
1188
1189 TerminatorKind::TailCall { .. } => {
1190 unreachable!("tail calls can't be present in generators")
1191 }
1192 }
1193 }
1194
1195 false
1197}
1198
1199fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
1201 transform: &TransformVisitor<'tcx>,
1202 body: &mut Body<'tcx>,
1203) {
1204 let source_info = SourceInfo::outermost(body.span);
1205 let poison_block = body.basic_blocks_mut().push(BasicBlockData {
1206 statements: vec![
1207 transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info),
1208 ],
1209 terminator: Some(Terminator { source_info, kind: TerminatorKind::UnwindResume }),
1210 is_cleanup: true,
1211 });
1212
1213 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1214 let source_info = block.terminator().source_info;
1215
1216 if let TerminatorKind::UnwindResume = block.terminator().kind {
1217 if idx != poison_block {
1220 *block.terminator_mut() =
1221 Terminator { source_info, kind: TerminatorKind::Goto { target: poison_block } };
1222 }
1223 } else if !block.is_cleanup
1224 && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
1227 {
1228 *unwind = UnwindAction::Cleanup(poison_block);
1229 }
1230 }
1231}
1232
1233fn create_coroutine_resume_function<'tcx>(
1234 tcx: TyCtxt<'tcx>,
1235 transform: TransformVisitor<'tcx>,
1236 body: &mut Body<'tcx>,
1237 can_return: bool,
1238 can_unwind: bool,
1239) {
1240 if can_unwind {
1242 generate_poison_block_and_redirect_unwinds_there(&transform, body);
1243 }
1244
1245 let mut cases = create_cases(body, &transform, Operation::Resume);
1246
1247 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1248
1249 cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
1251
1252 if can_unwind {
1254 cases.insert(
1255 1,
1256 (
1257 CoroutineArgs::POISONED,
1258 insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
1259 ),
1260 );
1261 }
1262
1263 if can_return {
1264 let block = match transform.coroutine_kind {
1265 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
1266 | CoroutineKind::Coroutine(_) => {
1267 if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
1270 insert_poll_ready_block(tcx, body)
1271 } else {
1272 insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
1273 }
1274 }
1275 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
1276 | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1277 transform.insert_none_ret_block(body)
1278 }
1279 };
1280 cases.insert(1, (CoroutineArgs::RETURNED, block));
1281 }
1282
1283 let default_block = insert_term_block(body, TerminatorKind::Unreachable);
1284 insert_switch(body, cases, &transform, default_block);
1285
1286 make_coroutine_state_argument_indirect(tcx, body);
1287
1288 match transform.coroutine_kind {
1289 CoroutineKind::Coroutine(_)
1290 | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
1291 {
1292 make_coroutine_state_argument_pinned(tcx, body);
1293 }
1294 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {}
1297 }
1298
1299 simplify::remove_dead_blocks(body);
1302
1303 pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
1304
1305 dump_mir(tcx, false, "coroutine_resume", &0, body, |_, _| Ok(()));
1306}
1307
1308#[derive(PartialEq, Copy, Clone)]
1310enum Operation {
1311 Resume,
1312 Drop,
1313}
1314
1315impl Operation {
1316 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1317 match self {
1318 Operation::Resume => Some(point.resume),
1319 Operation::Drop => point.drop,
1320 }
1321 }
1322}
1323
1324fn create_cases<'tcx>(
1325 body: &mut Body<'tcx>,
1326 transform: &TransformVisitor<'tcx>,
1327 operation: Operation,
1328) -> Vec<(usize, BasicBlock)> {
1329 let source_info = SourceInfo::outermost(body.span);
1330
1331 transform
1332 .suspension_points
1333 .iter()
1334 .filter_map(|point| {
1335 operation.target_block(point).map(|target| {
1337 let mut statements = Vec::new();
1338
1339 for l in body.local_decls.indices() {
1341 let needs_storage_live = point.storage_liveness.contains(l)
1342 && !transform.remap.contains(l)
1343 && !transform.always_live_locals.contains(l);
1344 if needs_storage_live {
1345 statements
1346 .push(Statement { source_info, kind: StatementKind::StorageLive(l) });
1347 }
1348 }
1349
1350 if operation == Operation::Resume {
1351 let resume_arg = CTX_ARG;
1353 statements.push(Statement {
1354 source_info,
1355 kind: StatementKind::Assign(Box::new((
1356 point.resume_arg,
1357 Rvalue::Use(Operand::Move(resume_arg.into())),
1358 ))),
1359 });
1360 }
1361
1362 let block = body.basic_blocks_mut().push(BasicBlockData {
1364 statements,
1365 terminator: Some(Terminator {
1366 source_info,
1367 kind: TerminatorKind::Goto { target },
1368 }),
1369 is_cleanup: false,
1370 });
1371
1372 (point.state, block)
1373 })
1374 })
1375 .collect()
1376}
1377
1378#[instrument(level = "debug", skip(tcx), ret)]
1379pub(crate) fn mir_coroutine_witnesses<'tcx>(
1380 tcx: TyCtxt<'tcx>,
1381 def_id: LocalDefId,
1382) -> Option<CoroutineLayout<'tcx>> {
1383 let (body, _) = tcx.mir_promoted(def_id);
1384 let body = body.borrow();
1385 let body = &*body;
1386
1387 let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
1389
1390 let movable = match *coroutine_ty.kind() {
1391 ty::Coroutine(def_id, _) => tcx.coroutine_movability(def_id) == hir::Movability::Movable,
1392 ty::Error(_) => return None,
1393 _ => span_bug!(body.span, "unexpected coroutine type {}", coroutine_ty),
1394 };
1395
1396 let always_live_locals = always_storage_live_locals(body);
1399 let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1400
1401 let (_, coroutine_layout, _) = compute_layout(liveness_info, body);
1405
1406 check_suspend_tys(tcx, &coroutine_layout, body);
1407 check_field_tys_sized(tcx, &coroutine_layout, def_id);
1408
1409 Some(coroutine_layout)
1410}
1411
1412fn check_field_tys_sized<'tcx>(
1413 tcx: TyCtxt<'tcx>,
1414 coroutine_layout: &CoroutineLayout<'tcx>,
1415 def_id: LocalDefId,
1416) {
1417 if !tcx.features().unsized_locals() && !tcx.features().unsized_fn_params() {
1420 return;
1421 }
1422
1423 let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
1428 let param_env = tcx.param_env(def_id);
1429
1430 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1431 for field_ty in &coroutine_layout.field_tys {
1432 ocx.register_bound(
1433 ObligationCause::new(
1434 field_ty.source_info.span,
1435 def_id,
1436 ObligationCauseCode::SizedCoroutineInterior(def_id),
1437 ),
1438 param_env,
1439 field_ty.ty,
1440 tcx.require_lang_item(hir::LangItem::Sized, Some(field_ty.source_info.span)),
1441 );
1442 }
1443
1444 let errors = ocx.select_all_or_error();
1445 debug!(?errors);
1446 if !errors.is_empty() {
1447 infcx.err_ctxt().report_fulfillment_errors(errors);
1448 }
1449}
1450
1451impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1452 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1453 let Some(old_yield_ty) = body.yield_ty() else {
1454 return;
1456 };
1457 let old_ret_ty = body.return_ty();
1458
1459 assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1460
1461 dump_mir(tcx, false, "coroutine_before", &0, body, |_, _| Ok(()));
1462
1463 let coroutine_ty = body.local_decls.raw[1].ty;
1465 let coroutine_kind = body.coroutine_kind().unwrap();
1466
1467 let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1469 tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1470 };
1471 let discr_ty = args.as_coroutine().discr_ty(tcx);
1472
1473 let new_ret_ty = match coroutine_kind {
1474 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1475 let poll_did = tcx.require_lang_item(LangItem::Poll, None);
1477 let poll_adt_ref = tcx.adt_def(poll_did);
1478 let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1479 Ty::new_adt(tcx, poll_adt_ref, poll_args)
1480 }
1481 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1482 let option_did = tcx.require_lang_item(LangItem::Option, None);
1484 let option_adt_ref = tcx.adt_def(option_did);
1485 let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1486 Ty::new_adt(tcx, option_adt_ref, option_args)
1487 }
1488 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1489 old_yield_ty
1491 }
1492 CoroutineKind::Coroutine(_) => {
1493 let state_did = tcx.require_lang_item(LangItem::CoroutineState, None);
1495 let state_adt_ref = tcx.adt_def(state_did);
1496 let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1497 Ty::new_adt(tcx, state_adt_ref, state_args)
1498 }
1499 };
1500
1501 let old_ret_local = replace_local(RETURN_PLACE, new_ret_ty, body, tcx);
1504
1505 let has_async_drops = matches!(
1510 coroutine_kind,
1511 CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1512 ) && has_expandable_async_drops(tcx, body, coroutine_ty);
1513
1514 if matches!(
1516 coroutine_kind,
1517 CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1518 ) {
1519 let context_mut_ref = transform_async_context(tcx, body);
1520 expand_async_drops(tcx, body, context_mut_ref, coroutine_kind, coroutine_ty);
1521 dump_mir(tcx, false, "coroutine_async_drop_expand", &0, body, |_, _| Ok(()));
1522 } else {
1523 cleanup_async_drops(body);
1524 }
1525
1526 let resume_local = CTX_ARG;
1531 let resume_ty = body.local_decls[resume_local].ty;
1532 let old_resume_local = replace_local(resume_local, resume_ty, body, tcx);
1533
1534 let source_info = SourceInfo::outermost(body.span);
1537 let stmts = &mut body.basic_blocks_mut()[START_BLOCK].statements;
1538 stmts.insert(
1539 0,
1540 Statement {
1541 source_info,
1542 kind: StatementKind::Assign(Box::new((
1543 old_resume_local.into(),
1544 Rvalue::Use(Operand::Move(resume_local.into())),
1545 ))),
1546 },
1547 );
1548
1549 let always_live_locals = always_storage_live_locals(body);
1550
1551 let movable = coroutine_kind.movability() == hir::Movability::Movable;
1552 let liveness_info =
1553 locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1554
1555 if tcx.sess.opts.unstable_opts.validate_mir {
1556 let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1557 assigned_local: None,
1558 saved_locals: &liveness_info.saved_locals,
1559 storage_conflicts: &liveness_info.storage_conflicts,
1560 };
1561
1562 vis.visit_body(body);
1563 }
1564
1565 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1569
1570 let can_return = can_return(tcx, body, body.typing_env(tcx));
1571
1572 let mut transform = TransformVisitor {
1578 tcx,
1579 coroutine_kind,
1580 remap,
1581 storage_liveness,
1582 always_live_locals,
1583 suspension_points: Vec::new(),
1584 old_ret_local,
1585 discr_ty,
1586 old_ret_ty,
1587 old_yield_ty,
1588 };
1589 transform.visit_body(body);
1590
1591 body.arg_count = 2; body.spread_arg = None;
1594
1595 if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1597 transform_gen_context(body);
1598 }
1599
1600 for var in &mut body.var_debug_info {
1604 var.argument_index = None;
1605 }
1606
1607 body.coroutine.as_mut().unwrap().yield_ty = None;
1608 body.coroutine.as_mut().unwrap().resume_ty = None;
1609 body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1610
1611 let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1619
1620 dump_mir(tcx, false, "coroutine_pre-elab", &0, body, |_, _| Ok(()));
1621
1622 elaborate_coroutine_drops(tcx, body);
1626
1627 dump_mir(tcx, false, "coroutine_post-transform", &0, body, |_, _| Ok(()));
1628
1629 let can_unwind = can_unwind(tcx, body);
1630
1631 if has_async_drops {
1633 let mut drop_shim =
1635 create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1636 deref_finder(tcx, &mut drop_shim);
1638 body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1639 } else {
1640 let mut drop_shim =
1642 create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1643 deref_finder(tcx, &mut drop_shim);
1645 body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1646
1647 let mut proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body);
1649 deref_finder(tcx, &mut proxy_shim);
1650 body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1651 }
1652
1653 create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1655
1656 deref_finder(tcx, body);
1658 }
1659
1660 fn is_required(&self) -> bool {
1661 true
1662 }
1663}
1664
1665struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1678 saved_locals: &'a CoroutineSavedLocals,
1679 storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1680 assigned_local: Option<CoroutineSavedLocal>,
1681}
1682
1683impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1684 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1685 if place.is_indirect() {
1686 return None;
1687 }
1688
1689 self.saved_locals.get(place.local)
1690 }
1691
1692 fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1693 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1694 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1695
1696 self.assigned_local = Some(assigned_local);
1697 f(self);
1698 self.assigned_local = None;
1699 }
1700 }
1701}
1702
1703impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1704 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1705 let Some(lhs) = self.assigned_local else {
1706 assert!(!context.is_use());
1711 return;
1712 };
1713
1714 let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1715
1716 if !self.storage_conflicts.contains(lhs, rhs) {
1717 bug!(
1718 "Assignment between coroutine saved locals whose storage is not \
1719 marked as conflicting: {:?}: {:?} = {:?}",
1720 location,
1721 lhs,
1722 rhs,
1723 );
1724 }
1725 }
1726
1727 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1728 match &statement.kind {
1729 StatementKind::Assign(box (lhs, rhs)) => {
1730 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1731 }
1732
1733 StatementKind::FakeRead(..)
1734 | StatementKind::SetDiscriminant { .. }
1735 | StatementKind::Deinit(..)
1736 | StatementKind::StorageLive(_)
1737 | StatementKind::StorageDead(_)
1738 | StatementKind::Retag(..)
1739 | StatementKind::AscribeUserType(..)
1740 | StatementKind::PlaceMention(..)
1741 | StatementKind::Coverage(..)
1742 | StatementKind::Intrinsic(..)
1743 | StatementKind::ConstEvalCounter
1744 | StatementKind::BackwardIncompatibleDropHint { .. }
1745 | StatementKind::Nop => {}
1746 }
1747 }
1748
1749 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1750 match &terminator.kind {
1753 TerminatorKind::Call {
1754 func,
1755 args,
1756 destination,
1757 target: Some(_),
1758 unwind: _,
1759 call_source: _,
1760 fn_span: _,
1761 } => {
1762 self.check_assigned_place(*destination, |this| {
1763 this.visit_operand(func, location);
1764 for arg in args {
1765 this.visit_operand(&arg.node, location);
1766 }
1767 });
1768 }
1769
1770 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1771 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1772 }
1773
1774 TerminatorKind::InlineAsm { .. } => {}
1776
1777 TerminatorKind::Call { .. }
1778 | TerminatorKind::Goto { .. }
1779 | TerminatorKind::SwitchInt { .. }
1780 | TerminatorKind::UnwindResume
1781 | TerminatorKind::UnwindTerminate(_)
1782 | TerminatorKind::Return
1783 | TerminatorKind::TailCall { .. }
1784 | TerminatorKind::Unreachable
1785 | TerminatorKind::Drop { .. }
1786 | TerminatorKind::Assert { .. }
1787 | TerminatorKind::CoroutineDrop
1788 | TerminatorKind::FalseEdge { .. }
1789 | TerminatorKind::FalseUnwind { .. } => {}
1790 }
1791 }
1792}
1793
1794fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &CoroutineLayout<'tcx>, body: &Body<'tcx>) {
1795 let mut linted_tys = FxHashSet::default();
1796
1797 for (variant, yield_source_info) in
1798 layout.variant_fields.iter().zip(&layout.variant_source_info)
1799 {
1800 debug!(?variant);
1801 for &local in variant {
1802 let decl = &layout.field_tys[local];
1803 debug!(?decl);
1804
1805 if !decl.ignore_for_traits && linted_tys.insert(decl.ty) {
1806 let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else {
1807 continue;
1808 };
1809
1810 check_must_not_suspend_ty(
1811 tcx,
1812 decl.ty,
1813 hir_id,
1814 SuspendCheckData {
1815 source_span: decl.source_info.span,
1816 yield_span: yield_source_info.span,
1817 plural_len: 1,
1818 ..Default::default()
1819 },
1820 );
1821 }
1822 }
1823 }
1824}
1825
1826#[derive(Default)]
1827struct SuspendCheckData<'a> {
1828 source_span: Span,
1829 yield_span: Span,
1830 descr_pre: &'a str,
1831 descr_post: &'a str,
1832 plural_len: usize,
1833}
1834
1835fn check_must_not_suspend_ty<'tcx>(
1842 tcx: TyCtxt<'tcx>,
1843 ty: Ty<'tcx>,
1844 hir_id: hir::HirId,
1845 data: SuspendCheckData<'_>,
1846) -> bool {
1847 if ty.is_unit() {
1848 return false;
1849 }
1850
1851 let plural_suffix = pluralize!(data.plural_len);
1852
1853 debug!("Checking must_not_suspend for {}", ty);
1854
1855 match *ty.kind() {
1856 ty::Adt(_, args) if ty.is_box() => {
1857 let boxed_ty = args.type_at(0);
1858 let allocator_ty = args.type_at(1);
1859 check_must_not_suspend_ty(
1860 tcx,
1861 boxed_ty,
1862 hir_id,
1863 SuspendCheckData { descr_pre: &format!("{}boxed ", data.descr_pre), ..data },
1864 ) || check_must_not_suspend_ty(
1865 tcx,
1866 allocator_ty,
1867 hir_id,
1868 SuspendCheckData { descr_pre: &format!("{}allocator ", data.descr_pre), ..data },
1869 )
1870 }
1871 ty::Adt(def, _) => check_must_not_suspend_def(tcx, def.did(), hir_id, data),
1872 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1874 let mut has_emitted = false;
1875 for &(predicate, _) in tcx.explicit_item_bounds(def).skip_binder() {
1876 if let ty::ClauseKind::Trait(ref poly_trait_predicate) =
1878 predicate.kind().skip_binder()
1879 {
1880 let def_id = poly_trait_predicate.trait_ref.def_id;
1881 let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix);
1882 if check_must_not_suspend_def(
1883 tcx,
1884 def_id,
1885 hir_id,
1886 SuspendCheckData { descr_pre, ..data },
1887 ) {
1888 has_emitted = true;
1889 break;
1890 }
1891 }
1892 }
1893 has_emitted
1894 }
1895 ty::Dynamic(binder, _, _) => {
1896 let mut has_emitted = false;
1897 for predicate in binder.iter() {
1898 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
1899 let def_id = trait_ref.def_id;
1900 let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post);
1901 if check_must_not_suspend_def(
1902 tcx,
1903 def_id,
1904 hir_id,
1905 SuspendCheckData { descr_post, ..data },
1906 ) {
1907 has_emitted = true;
1908 break;
1909 }
1910 }
1911 }
1912 has_emitted
1913 }
1914 ty::Tuple(fields) => {
1915 let mut has_emitted = false;
1916 for (i, ty) in fields.iter().enumerate() {
1917 let descr_post = &format!(" in tuple element {i}");
1918 if check_must_not_suspend_ty(
1919 tcx,
1920 ty,
1921 hir_id,
1922 SuspendCheckData { descr_post, ..data },
1923 ) {
1924 has_emitted = true;
1925 }
1926 }
1927 has_emitted
1928 }
1929 ty::Array(ty, len) => {
1930 let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
1931 check_must_not_suspend_ty(
1932 tcx,
1933 ty,
1934 hir_id,
1935 SuspendCheckData {
1936 descr_pre,
1937 plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1,
1939 ..data
1940 },
1941 )
1942 }
1943 ty::Ref(_region, ty, _mutability) => {
1946 let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix);
1947 check_must_not_suspend_ty(tcx, ty, hir_id, SuspendCheckData { descr_pre, ..data })
1948 }
1949 _ => false,
1950 }
1951}
1952
1953fn check_must_not_suspend_def(
1954 tcx: TyCtxt<'_>,
1955 def_id: DefId,
1956 hir_id: hir::HirId,
1957 data: SuspendCheckData<'_>,
1958) -> bool {
1959 if let Some(attr) = tcx.get_attr(def_id, sym::must_not_suspend) {
1960 let reason = attr.value_str().map(|s| errors::MustNotSuspendReason {
1961 span: data.source_span,
1962 reason: s.as_str().to_string(),
1963 });
1964 tcx.emit_node_span_lint(
1965 rustc_session::lint::builtin::MUST_NOT_SUSPEND,
1966 hir_id,
1967 data.source_span,
1968 errors::MustNotSupend {
1969 tcx,
1970 yield_sp: data.yield_span,
1971 reason,
1972 src_sp: data.source_span,
1973 pre: data.descr_pre,
1974 def_id,
1975 post: data.descr_post,
1976 },
1977 );
1978
1979 true
1980 } else {
1981 false
1982 }
1983}