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