1mod by_move_body;
54mod drop;
55mod layout;
56
57pub(super) use by_move_body::coroutine_by_move_body_def_id;
58use drop::{
59 create_coroutine_drop_shim, create_coroutine_drop_shim_async,
60 create_coroutine_drop_shim_proxy_async, elaborate_coroutine_drops, has_async_drops,
61 insert_clean_drop,
62};
63pub(super) use layout::mir_coroutine_witnesses;
64use layout::{CoroutineSavedLocals, compute_layout, locals_live_across_suspend_points};
65use rustc_abi::{FieldIdx, VariantIdx};
66use rustc_data_structures::thin_vec::ThinVec;
67use rustc_hir::attrs::lang_items::LangItem;
68use rustc_hir::{self as hir, CoroutineDesugaring, CoroutineKind};
69use rustc_index::bit_set::{BitMatrix, DenseBitSet, GrowableBitSet};
70use rustc_index::{Idx, IndexVec, indexvec};
71use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
72use rustc_middle::mir::*;
73use rustc_middle::ty::{
74 self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, ShimKind, Ty, TyCtxt,
75};
76use rustc_middle::{bug, span_bug};
77use rustc_mir_dataflow::impls::always_storage_live_locals;
78use rustc_span::def_id::DefId;
79use tracing::{debug, instrument};
80
81use crate::deref_separator::deref_finder;
82use crate::patch::MirPatch;
83use crate::{PassPolicy, abort_unwinding_calls, pass_manager as pm, simplify};
84
85pub(super) struct StateTransform;
86
87struct RenameLocalVisitor<'tcx> {
88 from: Local,
89 to: Local,
90 tcx: TyCtxt<'tcx>,
91}
92
93impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
94 fn tcx(&self) -> TyCtxt<'tcx> {
95 self.tcx
96 }
97
98 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
99 if *local == self.from {
100 *local = self.to;
101 } else if *local == self.to {
102 *local = self.from;
103 }
104 }
105
106 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
107 match terminator.kind {
108 TerminatorKind::Return => {
109 }
112 _ => self.super_terminator(terminator, location),
113 }
114 }
115}
116
117struct SelfArgVisitor<'tcx> {
118 tcx: TyCtxt<'tcx>,
119 new_base: Place<'tcx>,
120}
121
122impl<'tcx> SelfArgVisitor<'tcx> {
123 fn new(tcx: TyCtxt<'tcx>, new_base: Place<'tcx>) -> Self {
124 Self { tcx, new_base }
125 }
126}
127
128impl<'tcx> MutVisitor<'tcx> for SelfArgVisitor<'tcx> {
129 fn tcx(&self) -> TyCtxt<'tcx> {
130 self.tcx
131 }
132
133 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
134 assert_ne!(*local, SELF_ARG);
135 }
136
137 fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
138 if place.local == SELF_ARG {
139 replace_base(place, self.new_base, self.tcx);
140 }
141
142 for elem in place.projection.iter() {
143 if let PlaceElem::Index(local) = elem {
144 assert_ne!(local, SELF_ARG);
145 }
146 }
147 }
148}
149
150#[tracing::instrument(level = "trace", skip(tcx))]
151fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
152 place.local = new_base.local;
153
154 let mut new_projection = new_base.projection.to_vec();
155 new_projection.append(&mut place.projection.to_vec());
156
157 place.projection = tcx.mk_place_elems(&new_projection);
158 tracing::trace!(?place);
159}
160
161const SELF_ARG: Local = Local::arg(0);
162pub(crate) const CTX_ARG: Local = Local::arg(1);
163
164struct SuspensionPoint<'tcx> {
166 state: usize,
168 resume: BasicBlock,
170 resume_arg: Place<'tcx>,
172 drop: Option<BasicBlock>,
174 storage_liveness: GrowableBitSet<Local>,
176}
177
178struct TransformVisitor<'tcx> {
179 tcx: TyCtxt<'tcx>,
180 coroutine_kind: hir::CoroutineKind,
181
182 discr_ty: Ty<'tcx>,
184
185 remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
187
188 storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
190
191 suspension_points: Vec<SuspensionPoint<'tcx>>,
193
194 always_live_locals: DenseBitSet<Local>,
196
197 new_ret_local: Local,
199
200 old_yield_ty: Ty<'tcx>,
201
202 old_ret_ty: Ty<'tcx>,
203
204 patch: Option<MirPatch<'tcx>>,
205}
206
207impl<'tcx> TransformVisitor<'tcx> {
208 fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
209 let block = body.basic_blocks.next_index();
210 let source_info = SourceInfo::outermost(body.span);
211
212 let none_value = match self.coroutine_kind {
213 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
214 span_bug!(body.span, "`Future`s are not fused inherently")
215 }
216 CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
217 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
219 let option_def_id = self.tcx.require_lang_item(LangItem::Option, body.span);
220 make_aggregate_adt(
221 option_def_id,
222 VariantIdx::ZERO,
223 self.tcx.mk_args(&[self.old_yield_ty.into()]),
224 IndexVec::new(),
225 )
226 }
227 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
229 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
230 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
231 let yield_ty = args.type_at(0);
232 Rvalue::Use(
233 Operand::Constant(Box::new(ConstOperand {
234 span: source_info.span,
235 const_: Const::Unevaluated(
236 UnevaluatedConst::new(
237 self.tcx.require_lang_item(LangItem::AsyncGenFinished, body.span),
238 self.tcx.mk_args(&[yield_ty.into()]),
239 ),
240 self.old_yield_ty,
241 ),
242 user_ty: None,
243 })),
244 WithRetag::Yes,
245 )
246 }
247 };
248
249 let statements = vec![Statement::new(
250 source_info,
251 StatementKind::Assign(Box::new((Place::return_place(), none_value))),
252 )];
253
254 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
255 statements,
256 Some(Terminator {
257 source_info,
258 kind: TerminatorKind::Return,
259 attributes: ThinVec::new(),
260 }),
261 false,
262 ));
263
264 block
265 }
266
267 #[tracing::instrument(level = "trace", skip(self, statements))]
273 fn make_state(
274 &self,
275 val: Operand<'tcx>,
276 source_info: SourceInfo,
277 is_return: bool,
278 statements: &mut Vec<Statement<'tcx>>,
279 ) {
280 const ZERO: VariantIdx = VariantIdx::ZERO;
281 const ONE: VariantIdx = VariantIdx::from_usize(1);
282 let rvalue = match self.coroutine_kind {
283 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
284 let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, source_info.span);
285 let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
286 let (variant_idx, operands) = if is_return {
287 (ZERO, indexvec![val]) } else {
289 (ONE, IndexVec::new()) };
291 make_aggregate_adt(poll_def_id, variant_idx, args, operands)
292 }
293 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
294 let option_def_id = self.tcx.require_lang_item(LangItem::Option, source_info.span);
295 let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
296 let (variant_idx, operands) = if is_return {
297 (ZERO, IndexVec::new()) } else {
299 (ONE, indexvec![val]) };
301 make_aggregate_adt(option_def_id, variant_idx, args, operands)
302 }
303 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
304 if is_return {
305 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
306 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
307 let yield_ty = args.type_at(0);
308 Rvalue::Use(
309 Operand::Constant(Box::new(ConstOperand {
310 span: source_info.span,
311 const_: Const::Unevaluated(
312 UnevaluatedConst::new(
313 self.tcx.require_lang_item(
314 LangItem::AsyncGenFinished,
315 source_info.span,
316 ),
317 self.tcx.mk_args(&[yield_ty.into()]),
318 ),
319 self.old_yield_ty,
320 ),
321 user_ty: None,
322 })),
323 WithRetag::Yes,
324 )
325 } else {
326 Rvalue::Use(val, WithRetag::Yes)
327 }
328 }
329 CoroutineKind::Coroutine(_) => {
330 let coroutine_state_def_id =
331 self.tcx.require_lang_item(LangItem::CoroutineState, source_info.span);
332 let args = self.tcx.mk_args(&[self.old_yield_ty.into(), self.old_ret_ty.into()]);
333 let variant_idx = if is_return {
334 ONE } else {
336 ZERO };
338 make_aggregate_adt(coroutine_state_def_id, variant_idx, args, indexvec![val])
339 }
340 };
341
342 statements.push(Statement::new(
344 source_info,
345 StatementKind::Assign(Box::new((self.new_ret_local.into(), rvalue))),
346 ));
347 }
348
349 #[tracing::instrument(level = "trace", skip(self), ret)]
351 fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
352 let self_place = Place::from(SELF_ARG);
353 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
354 let mut projection = base.projection.to_vec();
355 projection.push(ProjectionElem::Field(idx, ty));
356
357 Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
358 }
359
360 #[tracing::instrument(level = "trace", skip(self))]
362 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
363 let self_place = Place::from(SELF_ARG);
364 Statement::new(
365 source_info,
366 StatementKind::SetDiscriminant {
367 place: Box::new(self_place),
368 variant_index: state_disc,
369 },
370 )
371 }
372
373 #[tracing::instrument(level = "trace", skip(self, body))]
375 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
376 let temp_decl = LocalDecl::new(self.discr_ty, body.span);
377 let local_decls_len = body.local_decls.push(temp_decl);
378 let temp = Place::from(local_decls_len);
379
380 let self_place = Place::from(SELF_ARG);
381 let assign = Statement::new(
382 SourceInfo::outermost(body.span),
383 StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
384 );
385 (assign, temp)
386 }
387
388 #[tracing::instrument(level = "trace", skip(self, body))]
390 fn replace_local(&mut self, old_local: Local, new_local: Local, body: &mut Body<'tcx>) {
391 body.local_decls.swap(old_local, new_local);
392
393 let mut visitor = RenameLocalVisitor { from: old_local, to: new_local, tcx: self.tcx };
394 visitor.visit_body(body);
395 for suspension in &mut self.suspension_points {
396 let ctxt = PlaceContext::MutatingUse(MutatingUseContext::Yield);
397 let location = Location { block: START_BLOCK, statement_index: 0 };
398 visitor.visit_place(&mut suspension.resume_arg, ctxt, location);
399 }
400 }
401}
402
403impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
404 fn tcx(&self) -> TyCtxt<'tcx> {
405 self.tcx
406 }
407
408 #[tracing::instrument(level = "trace", skip(self), ret)]
409 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _location: Location) {
410 assert!(!self.remap.contains(*local));
411 }
412
413 #[tracing::instrument(level = "trace", skip(self), ret)]
414 fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, location: Location) {
415 if let Some(&Some((ty, variant_index, idx))) = self.remap.get(place.local) {
417 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
418 }
419 if let Some(new_projection) = self.process_projection(&place.projection, location) {
420 place.projection = self.tcx.mk_place_elems(&new_projection);
421 }
422 }
423
424 fn process_projection_elem(
425 &mut self,
426 elem: PlaceElem<'tcx>,
427 location: Location,
428 ) -> Option<PlaceElem<'tcx>> {
429 match elem {
430 PlaceElem::Index(local) => {
431 if let Some(&Some((ty, variant, idx))) = self.remap.get(local) {
432 let field = self.make_field(variant, idx, ty);
443 self.patch.as_mut().unwrap().add_assign(
444 location,
445 Place::from(local),
446 Rvalue::Use(Operand::Copy(field), WithRetag::No),
447 );
448 }
449 None
450 }
451 PlaceElem::Field(..)
452 | PlaceElem::OpaqueCast(..)
453 | PlaceElem::UnwrapUnsafeBinder(..)
454 | PlaceElem::Deref
455 | PlaceElem::ConstantIndex { .. }
456 | PlaceElem::Subslice { .. }
457 | PlaceElem::Downcast(..)
458 | PlaceElem::PhantomDeref => None,
459 }
460 }
461
462 #[tracing::instrument(level = "trace", skip(self, stmt), ret)]
463 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, location: Location) {
464 if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
466 && self.remap.contains(l)
467 {
468 stmt.make_nop(true);
469 }
470 self.super_statement(stmt, location);
471 }
472
473 #[tracing::instrument(level = "trace", skip(self, term), ret)]
474 fn visit_terminator(&mut self, term: &mut Terminator<'tcx>, location: Location) {
475 if let TerminatorKind::Return = term.kind {
476 return;
479 }
480 self.super_terminator(term, location);
481 }
482
483 #[tracing::instrument(level = "trace", skip(self, data), ret)]
484 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
485 match data.terminator().kind {
486 TerminatorKind::Return => {
487 let source_info = data.terminator().source_info;
488 self.make_state(
490 Operand::Move(Place::return_place()),
491 source_info,
492 true,
493 &mut data.statements,
494 );
495 let state = VariantIdx::new(CoroutineArgs::RETURNED);
497 data.statements.push(self.set_discr(state, source_info));
498 data.terminator_mut().kind = TerminatorKind::Return;
499 }
500 TerminatorKind::Yield { ref value, resume, mut resume_arg, drop } => {
501 let source_info = data.terminator().source_info;
502 self.make_state(value.clone(), source_info, false, &mut data.statements);
504 let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
506
507 if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
510 replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
511 }
512
513 let storage_liveness: GrowableBitSet<Local> =
514 self.storage_liveness[block].clone().unwrap().into();
515
516 for i in 0..self.always_live_locals.domain_size() {
517 let l = Local::new(i);
518 let needs_storage_dead = storage_liveness.contains(l)
519 && !self.remap.contains(l)
520 && !self.always_live_locals.contains(l);
521 if needs_storage_dead {
522 data.statements
523 .push(Statement::new(source_info, StatementKind::StorageDead(l)));
524 }
525 }
526
527 self.suspension_points.push(SuspensionPoint {
528 state,
529 resume,
530 resume_arg,
531 drop,
532 storage_liveness,
533 });
534
535 let state = VariantIdx::new(state);
536 data.statements.push(self.set_discr(state, source_info));
537 data.terminator_mut().kind = TerminatorKind::Return;
538 }
539 _ => {}
540 }
541
542 self.super_basic_block_data(block, data);
543 }
544}
545
546fn make_aggregate_adt<'tcx>(
547 def_id: DefId,
548 variant_idx: VariantIdx,
549 args: GenericArgsRef<'tcx>,
550 operands: IndexVec<FieldIdx, Operand<'tcx>>,
551) -> Rvalue<'tcx> {
552 Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
553}
554
555#[tracing::instrument(level = "trace", skip(tcx, body))]
556fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
557 let coroutine_ty = body.local_decls[SELF_ARG].ty;
558
559 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
560
561 body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
563
564 SelfArgVisitor::new(tcx, tcx.mk_place_deref(SELF_ARG.into())).visit_body(body);
566}
567
568#[tracing::instrument(level = "trace", skip(tcx, body))]
569fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
570 let coroutine_ty = body.local_decls[SELF_ARG].ty;
571
572 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
573
574 let pin_did = tcx.require_lang_item(LangItem::Pin, body.span);
575 let pin_adt_ref = tcx.adt_def(pin_did);
576 let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
577 let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
578
579 body.local_decls[SELF_ARG].ty = pin_ref_coroutine_ty;
581
582 let unpinned_local = body.local_decls.push(LocalDecl::new(ref_coroutine_ty, body.span));
583
584 SelfArgVisitor::new(tcx, tcx.mk_place_deref(unpinned_local.into())).visit_body(body);
586
587 let source_info = SourceInfo::outermost(body.span);
588 let pin_field = tcx.mk_place_field(SELF_ARG.into(), FieldIdx::ZERO, ref_coroutine_ty);
589
590 let statements = &mut body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements;
591 statements.insert(
592 0,
593 Statement::new(
594 source_info,
595 StatementKind::Assign(Box::new((
596 unpinned_local.into(),
597 Rvalue::Use(Operand::Copy(pin_field), WithRetag::Yes),
598 ))),
599 ),
600 );
601}
602
603#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
621fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
622 let context_mut_ref = Ty::new_task_context(tcx);
623 let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
624 let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
625 ty::GenericArgs::empty(),
626 body.typing_env(tcx),
627 tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
628 );
629
630 let resume_local = body.local_decls.push(LocalDecl::new(context_mut_ref, body.span));
633 body.local_decls.swap(CTX_ARG, resume_local);
634 RenameLocalVisitor { from: CTX_ARG, to: resume_local, tcx }.visit_body(body);
635
636 let source_info = SourceInfo::outermost(body.span);
640 let nonnull_local = body.local_decls.push(LocalDecl::new(resume_nonnull_ty, body.span));
641 let nonnull_rhs =
642 Rvalue::Cast(CastKind::Transmute, Operand::Move(CTX_ARG.into()), resume_nonnull_ty);
643 let nonnull_assign = StatementKind::Assign(Box::new((nonnull_local.into(), nonnull_rhs)));
644 let resume_rhs = Rvalue::Aggregate(
645 Box::new(AggregateKind::Adt(
646 resume_ty_def_id,
647 VariantIdx::ZERO,
648 ty::GenericArgs::empty(),
649 None,
650 None,
651 )),
652 indexvec![Operand::Move(nonnull_local.into())],
653 );
654 let resume_assign = StatementKind::Assign(Box::new((resume_local.into(), resume_rhs)));
655 body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements.splice(
656 0..0,
657 [Statement::new(source_info, nonnull_assign), Statement::new(source_info, resume_assign)],
658 );
659}
660
661fn eliminate_get_context_calls<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
666 let context_mut_ref = Ty::new_task_context(tcx);
667 let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
668 let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
669 ty::GenericArgs::empty(),
670 body.typing_env(tcx),
671 tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
672 );
673
674 let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, body.span);
675 for bb_data in body.basic_blocks.as_mut().iter_mut() {
676 if bb_data.is_cleanup {
677 continue;
678 }
679
680 let terminator = bb_data.terminator_mut();
681 if let TerminatorKind::Call { func, args, destination, target, .. } = &terminator.kind
682 && let func_ty = func.ty(&body.local_decls, tcx)
683 && let ty::FnDef(def_id, _) = *func_ty.kind()
684 && def_id == get_context_def_id
685 && let [arg] = &**args
686 && let Some(place) = arg.node.place()
687 {
688 let arg =
689 Rvalue::Cast(
690 CastKind::Transmute,
691 Operand::Copy(place.project_deeper(
692 &[PlaceElem::Field(FieldIdx::ZERO, resume_nonnull_ty)],
693 tcx,
694 )),
695 context_mut_ref,
696 );
697 let assign = Statement::new(
698 terminator.source_info,
699 StatementKind::Assign(Box::new((*destination, arg))),
700 );
701 terminator.kind = TerminatorKind::Goto { target: target.unwrap() };
702 bb_data.statements.push(assign);
703 }
704 }
705}
706
707fn insert_switch<'tcx>(
712 body: &mut Body<'tcx>,
713 cases: Vec<(usize, BasicBlock)>,
714 transform: &TransformVisitor<'tcx>,
715 default_block: BasicBlock,
716) {
717 let (assign, discr) = transform.get_discr(body);
718
719 #[cfg(debug_assertions)]
721 for bb in body.basic_blocks.iter() {
722 for target in bb.terminator().successors() {
723 assert_ne!(target, START_BLOCK);
724 }
725 }
726
727 let former_entry = std::mem::replace(
729 &mut body.basic_blocks_mut()[START_BLOCK],
730 BasicBlockData::new_stmts(vec![assign], None, false),
731 );
732 let former_entry = body.basic_blocks_mut().push(former_entry);
733
734 let mut switch_targets =
736 SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
737 for bb in switch_targets.all_targets_mut() {
738 if *bb == START_BLOCK {
739 *bb = former_entry;
740 }
741 }
742
743 let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
744 body.basic_blocks_mut()[START_BLOCK].terminator = Some(Terminator {
745 source_info: SourceInfo::outermost(body.span),
746 kind: switch,
747 attributes: ThinVec::new(),
748 });
749}
750
751fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
752 let source_info = SourceInfo::outermost(body.span);
753 body.basic_blocks_mut().push(BasicBlockData::new(
754 Some(Terminator { source_info, kind, attributes: ThinVec::new() }),
755 false,
756 ))
757}
758
759fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
760 let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
762 let args = tcx.mk_args(&[tcx.types.unit.into()]);
763 let val = Operand::Constant(Box::new(ConstOperand {
764 span: source_info.span,
765 user_ty: None,
766 const_: Const::zero_sized(tcx.types.unit),
767 }));
768 let ready_val = Rvalue::Aggregate(
769 Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
770 indexvec![val],
771 );
772 Statement::new(source_info, StatementKind::Assign(Box::new((Place::return_place(), ready_val))))
773}
774
775fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
776 let source_info = SourceInfo::outermost(body.span);
777 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
778 [return_poll_ready_assign(tcx, source_info)].to_vec(),
779 Some(Terminator { source_info, kind: TerminatorKind::Return, attributes: ThinVec::new() }),
780 false,
781 ))
782}
783
784fn insert_panic_block<'tcx>(
785 tcx: TyCtxt<'tcx>,
786 body: &mut Body<'tcx>,
787 message: AssertMessage<'tcx>,
788) -> BasicBlock {
789 let assert_block = body.basic_blocks.next_index();
790 let kind = TerminatorKind::Assert {
791 cond: Operand::Constant(Box::new(ConstOperand {
792 span: body.span,
793 user_ty: None,
794 const_: Const::from_bool(tcx, false),
795 })),
796 expected: true,
797 msg: Box::new(message),
798 target: assert_block,
799 unwind: UnwindAction::Continue,
800 };
801
802 insert_term_block(body, kind)
803}
804
805fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
806 if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
808 return false;
809 }
810
811 body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
813 }
815
816fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
817 if !tcx.sess.panic_strategy().unwinds() {
819 return false;
820 }
821
822 body.basic_blocks.iter().any(|block| block.terminator().unwind().is_some())
824}
825
826fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
828 transform: &TransformVisitor<'tcx>,
829 body: &mut Body<'tcx>,
830) {
831 let source_info = SourceInfo::outermost(body.span);
832 let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
833 vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)],
834 Some(Terminator {
835 source_info,
836 kind: TerminatorKind::UnwindResume,
837
838 attributes: ThinVec::new(),
839 }),
840 true,
841 ));
842
843 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
844 let source_info = block.terminator().source_info;
845
846 if let TerminatorKind::UnwindResume = block.terminator().kind {
847 if idx != poison_block {
850 *block.terminator_mut() = Terminator {
851 source_info,
852 kind: TerminatorKind::Goto { target: poison_block },
853
854 attributes: ThinVec::new(),
855 };
856 }
857 } else if !block.is_cleanup
858 && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
861 {
862 *unwind = UnwindAction::Cleanup(poison_block);
863 }
864 }
865}
866
867#[tracing::instrument(level = "trace", skip(tcx, transform, body))]
868fn create_coroutine_resume_function<'tcx>(
869 tcx: TyCtxt<'tcx>,
870 transform: TransformVisitor<'tcx>,
871 body: &mut Body<'tcx>,
872 can_return: bool,
873 can_unwind: bool,
874) {
875 if can_unwind {
877 generate_poison_block_and_redirect_unwinds_there(&transform, body);
878 }
879
880 let mut cases = create_cases(body, &transform, Operation::Resume);
881
882 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
883
884 cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
886
887 if can_unwind {
889 cases.insert(
890 1,
891 (
892 CoroutineArgs::POISONED,
893 insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
894 ),
895 );
896 }
897
898 if can_return {
899 let block = match transform.coroutine_kind {
900 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
901 | CoroutineKind::Coroutine(_) => {
902 if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
905 insert_poll_ready_block(tcx, body)
906 } else {
907 insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
908 }
909 }
910 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
911 | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
912 transform.insert_none_ret_block(body)
913 }
914 };
915 cases.insert(1, (CoroutineArgs::RETURNED, block));
916 }
917
918 let default_block = insert_term_block(body, TerminatorKind::Unreachable);
919 insert_switch(body, cases, &transform, default_block);
920
921 match transform.coroutine_kind {
922 CoroutineKind::Coroutine(_)
923 | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
924 {
925 make_coroutine_state_argument_pinned(tcx, body);
926 }
927 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
930 make_coroutine_state_argument_indirect(tcx, body);
931 }
932 }
933
934 simplify::remove_dead_blocks(body);
937
938 pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
939
940 deref_finder(tcx, body, false);
942
943 if transform.coroutine_kind.is_async_desugaring() {
944 transform_async_context(tcx, body);
945 }
946
947 if let Some(dumper) = MirDumper::new(tcx, "coroutine_resume", body) {
948 dumper.dump_mir(body);
949 }
950}
951
952#[derive(PartialEq, Copy, Clone, Debug)]
954enum Operation {
955 Resume,
956 Drop,
957 AsyncDrop,
958}
959
960impl Operation {
961 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
962 match self {
963 Operation::Resume => Some(point.resume),
964 Operation::Drop | Operation::AsyncDrop => point.drop,
965 }
966 }
967
968 fn resume_place<'tcx>(self, point: &SuspensionPoint<'tcx>) -> Option<Place<'tcx>> {
969 match self {
970 Operation::Resume | Operation::AsyncDrop => Some(point.resume_arg),
971 Operation::Drop => None,
972 }
973 }
974}
975
976#[tracing::instrument(level = "trace", skip(transform, body))]
977fn create_cases<'tcx>(
978 body: &mut Body<'tcx>,
979 transform: &TransformVisitor<'tcx>,
980 operation: Operation,
981) -> Vec<(usize, BasicBlock)> {
982 let source_info = SourceInfo::outermost(body.span);
983
984 transform
985 .suspension_points
986 .iter()
987 .filter_map(|point| {
988 operation.target_block(point).map(|target| {
990 let mut statements = Vec::new();
991
992 for l in body.local_decls.indices() {
994 let needs_storage_live = point.storage_liveness.contains(l)
995 && !transform.remap.contains(l)
996 && !transform.always_live_locals.contains(l);
997 if needs_storage_live {
998 statements.push(Statement::new(source_info, StatementKind::StorageLive(l)));
999 }
1000 }
1001
1002 if let Some(resume_arg) = operation.resume_place(point)
1004 && resume_arg != CTX_ARG.into()
1005 {
1006 statements.push(Statement::new(
1007 source_info,
1008 StatementKind::Assign(Box::new((
1009 resume_arg,
1010 Rvalue::Use(Operand::Move(CTX_ARG.into()), WithRetag::Yes),
1011 ))),
1012 ));
1013 }
1014
1015 let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1017 statements,
1018 Some(Terminator {
1019 source_info,
1020 kind: TerminatorKind::Goto { target },
1021
1022 attributes: ThinVec::new(),
1023 }),
1024 false,
1025 ));
1026
1027 (point.state, block)
1028 })
1029 })
1030 .collect()
1031}
1032
1033impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1034 #[instrument(level = "debug", skip(self, tcx, body), ret)]
1035 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1036 debug!(def_id = ?body.source.def_id());
1037
1038 let Some(old_yield_ty) = body.yield_ty() else {
1039 return;
1041 };
1042 tracing::trace!(def_id = ?body.source.def_id());
1043
1044 let old_ret_ty = body.return_ty();
1045
1046 assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1047
1048 if let Some(dumper) = MirDumper::new(tcx, "coroutine_before", body) {
1049 dumper.dump_mir(body);
1050 }
1051
1052 let coroutine_ty = body.local_decls.raw[1].ty;
1054 let coroutine_kind = body.coroutine_kind().unwrap();
1055
1056 let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1058 tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1059 };
1060 let discr_ty = args.as_coroutine().discr_ty(tcx);
1061
1062 let new_ret_ty = match coroutine_kind {
1063 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1064 let poll_did = tcx.require_lang_item(LangItem::Poll, body.span);
1066 let poll_adt_ref = tcx.adt_def(poll_did);
1067 let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1068 Ty::new_adt(tcx, poll_adt_ref, poll_args)
1069 }
1070 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1071 let option_did = tcx.require_lang_item(LangItem::Option, body.span);
1073 let option_adt_ref = tcx.adt_def(option_did);
1074 let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1075 Ty::new_adt(tcx, option_adt_ref, option_args)
1076 }
1077 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1078 old_yield_ty
1080 }
1081 CoroutineKind::Coroutine(_) => {
1082 let state_did = tcx.require_lang_item(LangItem::CoroutineState, body.span);
1084 let state_adt_ref = tcx.adt_def(state_did);
1085 let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1086 Ty::new_adt(tcx, state_adt_ref, state_args)
1087 }
1088 };
1089
1090 let has_async_drops = has_async_drops(body);
1095
1096 if coroutine_kind.is_async_desugaring() {
1097 eliminate_get_context_calls(tcx, body);
1098 }
1099
1100 let always_live_locals = always_storage_live_locals(body);
1101 let movable = coroutine_kind.movability() == hir::Movability::Movable;
1102 let liveness_info =
1103 locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1104
1105 if tcx.sess.opts.unstable_opts.validate_mir {
1106 let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1107 assigned_local: None,
1108 saved_locals: &liveness_info.saved_locals,
1109 storage_conflicts: &liveness_info.storage_conflicts,
1110 };
1111
1112 vis.visit_body(body);
1113 }
1114
1115 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1119
1120 let can_return = can_return(tcx, body, body.typing_env(tcx));
1121
1122 let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1125 tracing::trace!(?new_ret_local);
1126
1127 let mut transform = TransformVisitor {
1133 tcx,
1134 coroutine_kind,
1135 remap,
1136 storage_liveness,
1137 always_live_locals,
1138 suspension_points: Vec::new(),
1139 discr_ty,
1140 new_ret_local,
1141 old_ret_ty,
1142 old_yield_ty,
1143 patch: Some(MirPatch::new(body)),
1144 };
1145 transform.visit_body(body);
1146
1147 transform.replace_local(RETURN_PLACE, new_ret_local, body);
1149
1150 let source_info = SourceInfo::outermost(body.span);
1153 let args_iter = body.args_iter();
1154 body.basic_blocks.as_mut()[START_BLOCK].statements.splice(
1155 0..0,
1156 args_iter.filter_map(|local| {
1157 let (ty, variant_index, idx) = transform.remap[local]?;
1158 let lhs = transform.make_field(variant_index, idx, ty);
1159 let rhs = Rvalue::Use(Operand::Move(local.into()), WithRetag::Yes);
1160 let assign = StatementKind::Assign(Box::new((lhs, rhs)));
1161 Some(Statement::new(source_info, assign))
1162 }),
1163 );
1164 transform.patch.take().unwrap().apply(body);
1165
1166 if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1168 body.arg_count = 1;
1169 }
1170
1171 for var in &mut body.var_debug_info {
1175 var.argument_index = None;
1176 }
1177
1178 body.coroutine.as_mut().unwrap().yield_ty = None;
1179 body.coroutine.as_mut().unwrap().resume_ty = None;
1180 body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1181
1182 let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1186
1187 if let Some(dumper) = MirDumper::new(tcx, "coroutine_pre-elab", body) {
1188 dumper.dump_mir(body);
1189 }
1190
1191 elaborate_coroutine_drops(tcx, body);
1195
1196 if let Some(dumper) = MirDumper::new(tcx, "coroutine_post-transform", body) {
1197 dumper.dump_mir(body);
1198 }
1199
1200 let can_unwind = can_unwind(tcx, body);
1201
1202 if has_async_drops {
1204 let drop_shim =
1206 create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1207 body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1208 } else {
1209 let drop_shim =
1211 create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1212 body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1213
1214 let proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body, coroutine_kind);
1216 body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1217 }
1218
1219 create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1221 }
1222
1223 fn policy(&self, _sess: &rustc_session::Session) -> PassPolicy {
1224 PassPolicy::Required
1226 }
1227}
1228
1229struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1242 saved_locals: &'a CoroutineSavedLocals,
1243 storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1244 assigned_local: Option<CoroutineSavedLocal>,
1245}
1246
1247impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1248 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1249 if place.is_indirect() {
1250 return None;
1251 }
1252
1253 self.saved_locals.get(place.local)
1254 }
1255
1256 fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1257 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1258 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1259
1260 self.assigned_local = Some(assigned_local);
1261 f(self);
1262 self.assigned_local = None;
1263 }
1264 }
1265}
1266
1267impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1268 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1269 let Some(lhs) = self.assigned_local else {
1270 assert!(!context.is_use());
1275 return;
1276 };
1277
1278 let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1279
1280 if !self.storage_conflicts.contains(lhs, rhs) {
1281 bug!(
1282 "Assignment between coroutine saved locals whose storage is not \
1283 marked as conflicting: {:?}: {:?} = {:?}",
1284 location,
1285 lhs,
1286 rhs,
1287 );
1288 }
1289 }
1290
1291 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1292 match &statement.kind {
1293 StatementKind::Assign((lhs, rhs)) => {
1294 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1295 }
1296
1297 StatementKind::FakeRead(..)
1298 | StatementKind::SetDiscriminant { .. }
1299 | StatementKind::StorageLive(_)
1300 | StatementKind::StorageDead(_)
1301 | StatementKind::AscribeUserType(..)
1302 | StatementKind::PlaceMention(..)
1303 | StatementKind::Coverage(..)
1304 | StatementKind::Intrinsic(..)
1305 | StatementKind::ConstEvalCounter
1306 | StatementKind::BackwardIncompatibleDropHint { .. }
1307 | StatementKind::Nop => {}
1308 }
1309 }
1310
1311 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1312 match &terminator.kind {
1315 TerminatorKind::Call {
1316 func,
1317 args,
1318 destination,
1319 target: Some(_),
1320 unwind: _,
1321 call_source: _,
1322 fn_span: _,
1323 } => {
1324 self.check_assigned_place(*destination, |this| {
1325 this.visit_operand(func, location);
1326 for arg in args {
1327 this.visit_operand(&arg.node, location);
1328 }
1329 });
1330 }
1331
1332 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1333 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1334 }
1335
1336 TerminatorKind::InlineAsm { .. } => {}
1338
1339 TerminatorKind::Call { .. }
1340 | TerminatorKind::Goto { .. }
1341 | TerminatorKind::SwitchInt { .. }
1342 | TerminatorKind::UnwindResume
1343 | TerminatorKind::UnwindTerminate(_)
1344 | TerminatorKind::Return
1345 | TerminatorKind::TailCall { .. }
1346 | TerminatorKind::Unreachable
1347 | TerminatorKind::Drop { .. }
1348 | TerminatorKind::Assert { .. }
1349 | TerminatorKind::CoroutineDrop
1350 | TerminatorKind::FalseEdge { .. }
1351 | TerminatorKind::FalseUnwind { .. } => {}
1352 }
1353 }
1354}