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, GenericArgsRef, 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, SELF_ARG);
134 }
135
136 fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
137 if place.local == SELF_ARG {
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, SELF_ARG);
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
160const SELF_ARG: Local = Local::arg(0);
161pub(crate) const CTX_ARG: Local = Local::arg(1);
162
163struct SuspensionPoint<'tcx> {
165 state: usize,
167 resume: BasicBlock,
169 resume_arg: Place<'tcx>,
171 drop: Option<BasicBlock>,
173 storage_liveness: DenseBitSet<Local>,
175}
176
177struct TransformVisitor<'tcx> {
178 tcx: TyCtxt<'tcx>,
179 coroutine_kind: hir::CoroutineKind,
180
181 discr_ty: Ty<'tcx>,
183
184 remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
186
187 storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
189
190 suspension_points: Vec<SuspensionPoint<'tcx>>,
192
193 always_live_locals: DenseBitSet<Local>,
195
196 new_ret_local: Local,
198
199 old_yield_ty: Ty<'tcx>,
200
201 old_ret_ty: Ty<'tcx>,
202
203 patch: Option<MirPatch<'tcx>>,
204}
205
206impl<'tcx> TransformVisitor<'tcx> {
207 fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
208 let block = body.basic_blocks.next_index();
209 let source_info = SourceInfo::outermost(body.span);
210
211 let none_value = match self.coroutine_kind {
212 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
213 span_bug!(body.span, "`Future`s are not fused inherently")
214 }
215 CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
216 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
218 let option_def_id = self.tcx.require_lang_item(LangItem::Option, body.span);
219 make_aggregate_adt(
220 option_def_id,
221 VariantIdx::ZERO,
222 self.tcx.mk_args(&[self.old_yield_ty.into()]),
223 IndexVec::new(),
224 )
225 }
226 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
228 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
229 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
230 let yield_ty = args.type_at(0);
231 Rvalue::Use(
232 Operand::Constant(Box::new(ConstOperand {
233 span: source_info.span,
234 const_: Const::Unevaluated(
235 UnevaluatedConst::new(
236 self.tcx.require_lang_item(LangItem::AsyncGenFinished, body.span),
237 self.tcx.mk_args(&[yield_ty.into()]),
238 ),
239 self.old_yield_ty,
240 ),
241 user_ty: None,
242 })),
243 WithRetag::Yes,
244 )
245 }
246 };
247
248 let statements = vec![Statement::new(
249 source_info,
250 StatementKind::Assign(Box::new((Place::return_place(), none_value))),
251 )];
252
253 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
254 statements,
255 Some(Terminator { source_info, kind: TerminatorKind::Return }),
256 false,
257 ));
258
259 block
260 }
261
262 #[tracing::instrument(level = "trace", skip(self, statements))]
268 fn make_state(
269 &self,
270 val: Operand<'tcx>,
271 source_info: SourceInfo,
272 is_return: bool,
273 statements: &mut Vec<Statement<'tcx>>,
274 ) {
275 const ZERO: VariantIdx = VariantIdx::ZERO;
276 const ONE: VariantIdx = VariantIdx::from_usize(1);
277 let rvalue = match self.coroutine_kind {
278 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
279 let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, source_info.span);
280 let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
281 let (variant_idx, operands) = if is_return {
282 (ZERO, indexvec![val]) } else {
284 (ONE, IndexVec::new()) };
286 make_aggregate_adt(poll_def_id, variant_idx, args, operands)
287 }
288 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
289 let option_def_id = self.tcx.require_lang_item(LangItem::Option, source_info.span);
290 let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
291 let (variant_idx, operands) = if is_return {
292 (ZERO, IndexVec::new()) } else {
294 (ONE, indexvec![val]) };
296 make_aggregate_adt(option_def_id, variant_idx, args, operands)
297 }
298 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
299 if is_return {
300 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
301 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
302 let yield_ty = args.type_at(0);
303 Rvalue::Use(
304 Operand::Constant(Box::new(ConstOperand {
305 span: source_info.span,
306 const_: Const::Unevaluated(
307 UnevaluatedConst::new(
308 self.tcx.require_lang_item(
309 LangItem::AsyncGenFinished,
310 source_info.span,
311 ),
312 self.tcx.mk_args(&[yield_ty.into()]),
313 ),
314 self.old_yield_ty,
315 ),
316 user_ty: None,
317 })),
318 WithRetag::Yes,
319 )
320 } else {
321 Rvalue::Use(val, WithRetag::Yes)
322 }
323 }
324 CoroutineKind::Coroutine(_) => {
325 let coroutine_state_def_id =
326 self.tcx.require_lang_item(LangItem::CoroutineState, source_info.span);
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(coroutine_state_def_id, variant_idx, args, indexvec![val])
334 }
335 };
336
337 statements.push(Statement::new(
339 source_info,
340 StatementKind::Assign(Box::new((self.new_ret_local.into(), rvalue))),
341 ));
342 }
343
344 #[tracing::instrument(level = "trace", skip(self), ret)]
346 fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
347 let self_place = Place::from(SELF_ARG);
348 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
349 let mut projection = base.projection.to_vec();
350 projection.push(ProjectionElem::Field(idx, ty));
351
352 Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
353 }
354
355 #[tracing::instrument(level = "trace", skip(self))]
357 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
358 let self_place = Place::from(SELF_ARG);
359 Statement::new(
360 source_info,
361 StatementKind::SetDiscriminant {
362 place: Box::new(self_place),
363 variant_index: state_disc,
364 },
365 )
366 }
367
368 #[tracing::instrument(level = "trace", skip(self, body))]
370 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
371 let temp_decl = LocalDecl::new(self.discr_ty, body.span);
372 let local_decls_len = body.local_decls.push(temp_decl);
373 let temp = Place::from(local_decls_len);
374
375 let self_place = Place::from(SELF_ARG);
376 let assign = Statement::new(
377 SourceInfo::outermost(body.span),
378 StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
379 );
380 (assign, temp)
381 }
382
383 #[tracing::instrument(level = "trace", skip(self, body))]
385 fn replace_local(&mut self, old_local: Local, new_local: Local, body: &mut Body<'tcx>) {
386 body.local_decls.swap(old_local, new_local);
387
388 let mut visitor = RenameLocalVisitor { from: old_local, to: new_local, tcx: self.tcx };
389 visitor.visit_body(body);
390 for suspension in &mut self.suspension_points {
391 let ctxt = PlaceContext::MutatingUse(MutatingUseContext::Yield);
392 let location = Location::START;
393 visitor.visit_place(&mut suspension.resume_arg, ctxt, location);
394 }
395 }
396}
397
398impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
399 fn tcx(&self) -> TyCtxt<'tcx> {
400 self.tcx
401 }
402
403 #[tracing::instrument(level = "trace", skip(self), ret)]
404 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _location: Location) {
405 assert!(!self.remap.contains(*local));
406 }
407
408 #[tracing::instrument(level = "trace", skip(self), ret)]
409 fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, location: Location) {
410 if let Some(&Some((ty, variant_index, idx))) = self.remap.get(place.local) {
412 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
413 }
414 if let Some(new_projection) = self.process_projection(&place.projection, location) {
415 place.projection = self.tcx.mk_place_elems(&new_projection);
416 }
417 }
418
419 fn process_projection_elem(
420 &mut self,
421 elem: PlaceElem<'tcx>,
422 location: Location,
423 ) -> Option<PlaceElem<'tcx>> {
424 match elem {
425 PlaceElem::Index(local) => {
426 if let Some(&Some((ty, variant, idx))) = self.remap.get(local) {
427 let field = self.make_field(variant, idx, ty);
438 self.patch.as_mut().unwrap().add_assign(
439 location,
440 Place::from(local),
441 Rvalue::Use(Operand::Copy(field), WithRetag::No),
442 );
443 }
444 None
445 }
446 PlaceElem::Field(..)
447 | PlaceElem::OpaqueCast(..)
448 | PlaceElem::UnwrapUnsafeBinder(..)
449 | PlaceElem::Deref
450 | PlaceElem::ConstantIndex { .. }
451 | PlaceElem::Subslice { .. }
452 | PlaceElem::Downcast(..)
453 | PlaceElem::PhantomDeref => None,
454 }
455 }
456
457 #[tracing::instrument(level = "trace", skip(self, stmt), ret)]
458 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, location: Location) {
459 if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
461 && self.remap.contains(l)
462 {
463 stmt.make_nop(true);
464 }
465 self.super_statement(stmt, location);
466 }
467
468 #[tracing::instrument(level = "trace", skip(self, term), ret)]
469 fn visit_terminator(&mut self, term: &mut Terminator<'tcx>, location: Location) {
470 if let TerminatorKind::Return = term.kind {
471 return;
474 }
475 self.super_terminator(term, location);
476 }
477
478 #[tracing::instrument(level = "trace", skip(self, data), ret)]
479 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
480 match data.terminator().kind {
481 TerminatorKind::Return => {
482 let source_info = data.terminator().source_info;
483 self.make_state(
485 Operand::Move(Place::return_place()),
486 source_info,
487 true,
488 &mut data.statements,
489 );
490 let state = VariantIdx::new(CoroutineArgs::RETURNED);
492 data.statements.push(self.set_discr(state, source_info));
493 data.terminator_mut().kind = TerminatorKind::Return;
494 }
495 TerminatorKind::Yield { ref value, resume, mut resume_arg, drop } => {
496 let source_info = data.terminator().source_info;
497 self.make_state(value.clone(), source_info, false, &mut data.statements);
499 let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
501
502 if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
505 replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
506 }
507
508 let storage_liveness: DenseBitSet<Local> =
509 self.storage_liveness[block].clone().unwrap();
510
511 for i in 0..self.always_live_locals.domain_size() {
512 let l = Local::new(i);
513 let needs_storage_dead = storage_liveness.contains(l)
514 && !self.remap.contains(l)
515 && !self.always_live_locals.contains(l);
516 if needs_storage_dead {
517 data.statements
518 .push(Statement::new(source_info, StatementKind::StorageDead(l)));
519 }
520 }
521
522 self.suspension_points.push(SuspensionPoint {
523 state,
524 resume,
525 resume_arg,
526 drop,
527 storage_liveness,
528 });
529
530 let state = VariantIdx::new(state);
531 data.statements.push(self.set_discr(state, source_info));
532 data.terminator_mut().kind = TerminatorKind::Return;
533 }
534 _ => {}
535 }
536
537 self.super_basic_block_data(block, data);
538 }
539}
540
541fn make_aggregate_adt<'tcx>(
542 def_id: DefId,
543 variant_idx: VariantIdx,
544 args: GenericArgsRef<'tcx>,
545 operands: IndexVec<FieldIdx, Operand<'tcx>>,
546) -> Rvalue<'tcx> {
547 Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
548}
549
550#[tracing::instrument(level = "trace", skip(tcx, body))]
551fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
552 let coroutine_ty = body.local_decls[SELF_ARG].ty;
553
554 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
555
556 body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
558
559 SelfArgVisitor::new(tcx, tcx.mk_place_deref(SELF_ARG.into())).visit_body(body);
561}
562
563#[tracing::instrument(level = "trace", skip(tcx, body))]
564fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
565 let coroutine_ty = body.local_decls[SELF_ARG].ty;
566
567 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
568
569 let pin_did = tcx.require_lang_item(LangItem::Pin, body.span);
570 let pin_adt_ref = tcx.adt_def(pin_did);
571 let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
572 let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
573
574 body.local_decls[SELF_ARG].ty = pin_ref_coroutine_ty;
576
577 let unpinned_local = body.local_decls.push(LocalDecl::new(ref_coroutine_ty, body.span));
578
579 SelfArgVisitor::new(tcx, tcx.mk_place_deref(unpinned_local.into())).visit_body(body);
581
582 let source_info = SourceInfo::outermost(body.span);
583 let pin_field = tcx.mk_place_field(SELF_ARG.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 former_entry = std::mem::replace(
724 &mut body.basic_blocks_mut()[START_BLOCK],
725 BasicBlockData::new_stmts(vec![assign], None, false),
726 );
727 let former_entry = body.basic_blocks_mut().push(former_entry);
728
729 let mut switch_targets =
731 SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
732 for bb in switch_targets.all_targets_mut() {
733 if *bb == START_BLOCK {
734 *bb = former_entry;
735 }
736 }
737
738 let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
739 body.basic_blocks_mut()[START_BLOCK].terminator =
740 Some(Terminator { source_info: SourceInfo::outermost(body.span), kind: switch });
741}
742
743fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
744 let source_info = SourceInfo::outermost(body.span);
745 body.basic_blocks_mut().push(BasicBlockData::new(Some(Terminator { source_info, kind }), false))
746}
747
748fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
749 let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
751 let args = tcx.mk_args(&[tcx.types.unit.into()]);
752 let val = Operand::Constant(Box::new(ConstOperand {
753 span: source_info.span,
754 user_ty: None,
755 const_: Const::zero_sized(tcx.types.unit),
756 }));
757 let ready_val = Rvalue::Aggregate(
758 Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
759 indexvec![val],
760 );
761 Statement::new(source_info, StatementKind::Assign(Box::new((Place::return_place(), ready_val))))
762}
763
764fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
765 let source_info = SourceInfo::outermost(body.span);
766 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
767 [return_poll_ready_assign(tcx, source_info)].to_vec(),
768 Some(Terminator { source_info, kind: TerminatorKind::Return }),
769 false,
770 ))
771}
772
773fn insert_panic_block<'tcx>(
774 tcx: TyCtxt<'tcx>,
775 body: &mut Body<'tcx>,
776 message: AssertMessage<'tcx>,
777) -> BasicBlock {
778 let assert_block = body.basic_blocks.next_index();
779 let kind = TerminatorKind::Assert {
780 cond: Operand::Constant(Box::new(ConstOperand {
781 span: body.span,
782 user_ty: None,
783 const_: Const::from_bool(tcx, false),
784 })),
785 expected: true,
786 msg: Box::new(message),
787 target: assert_block,
788 unwind: UnwindAction::Continue,
789 };
790
791 insert_term_block(body, kind)
792}
793
794fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
795 if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
797 return false;
798 }
799
800 body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
802 }
804
805fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
806 if !tcx.sess.panic_strategy().unwinds() {
808 return false;
809 }
810
811 body.basic_blocks.iter().any(|block| block.terminator().unwind().is_some())
813}
814
815fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
817 transform: &TransformVisitor<'tcx>,
818 body: &mut Body<'tcx>,
819) {
820 let source_info = SourceInfo::outermost(body.span);
821 let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
822 vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)],
823 Some(Terminator { source_info, kind: TerminatorKind::UnwindResume }),
824 true,
825 ));
826
827 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
828 let source_info = block.terminator().source_info;
829
830 if let TerminatorKind::UnwindResume = block.terminator().kind {
831 if idx != poison_block {
834 *block.terminator_mut() =
835 Terminator { source_info, kind: TerminatorKind::goto(poison_block) };
836 }
837 } else if !block.is_cleanup
838 && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
841 {
842 *unwind = UnwindAction::Cleanup(poison_block);
843 }
844 }
845}
846
847#[tracing::instrument(level = "trace", skip(tcx, transform, body))]
848fn create_coroutine_resume_function<'tcx>(
849 tcx: TyCtxt<'tcx>,
850 transform: TransformVisitor<'tcx>,
851 body: &mut Body<'tcx>,
852 can_return: bool,
853 can_unwind: bool,
854) {
855 if can_unwind {
857 generate_poison_block_and_redirect_unwinds_there(&transform, body);
858 }
859
860 let mut cases = create_cases(body, &transform, Operation::Resume);
861
862 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
863
864 cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
866
867 if can_unwind {
869 cases.insert(
870 1,
871 (
872 CoroutineArgs::POISONED,
873 insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
874 ),
875 );
876 }
877
878 if can_return {
879 let block = match transform.coroutine_kind {
880 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
881 | CoroutineKind::Coroutine(_) => {
882 if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
885 insert_poll_ready_block(tcx, body)
886 } else {
887 insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
888 }
889 }
890 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
891 | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
892 transform.insert_none_ret_block(body)
893 }
894 };
895 cases.insert(1, (CoroutineArgs::RETURNED, block));
896 }
897
898 let default_block = insert_term_block(body, TerminatorKind::Unreachable);
899 insert_switch(body, cases, &transform, default_block);
900
901 match transform.coroutine_kind {
902 CoroutineKind::Coroutine(_)
903 | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
904 {
905 make_coroutine_state_argument_pinned(tcx, body);
906 }
907 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
910 make_coroutine_state_argument_indirect(tcx, body);
911 }
912 }
913
914 simplify::remove_dead_blocks(body);
917
918 pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
919
920 deref_finder(tcx, body, false);
922
923 if transform.coroutine_kind.is_async_desugaring() {
924 transform_async_context(tcx, body);
925 }
926
927 if let Some(dumper) = MirDumper::new(tcx, "coroutine_resume", body) {
928 dumper.dump_mir(body);
929 }
930}
931
932#[derive(PartialEq, Copy, Clone, Debug)]
934enum Operation {
935 Resume,
936 Drop,
937 AsyncDrop,
938}
939
940impl Operation {
941 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
942 match self {
943 Operation::Resume => Some(point.resume),
944 Operation::Drop | Operation::AsyncDrop => point.drop,
945 }
946 }
947
948 fn resume_place<'tcx>(self, point: &SuspensionPoint<'tcx>) -> Option<Place<'tcx>> {
949 match self {
950 Operation::Resume | Operation::AsyncDrop => Some(point.resume_arg),
951 Operation::Drop => None,
952 }
953 }
954}
955
956#[tracing::instrument(level = "trace", skip(transform, body))]
957fn create_cases<'tcx>(
958 body: &mut Body<'tcx>,
959 transform: &TransformVisitor<'tcx>,
960 operation: Operation,
961) -> Vec<(usize, BasicBlock)> {
962 let source_info = SourceInfo::outermost(body.span);
963
964 transform
965 .suspension_points
966 .iter()
967 .filter_map(|point| {
968 operation.target_block(point).map(|target| {
970 let mut statements = Vec::new();
971
972 for l in body.local_decls.indices() {
974 let needs_storage_live = point.storage_liveness.contains_loose(l)
975 && !transform.remap.contains(l)
976 && !transform.always_live_locals.contains(l);
977 if needs_storage_live {
978 statements.push(Statement::new(source_info, StatementKind::StorageLive(l)));
979 }
980 }
981
982 if let Some(resume_arg) = operation.resume_place(point)
984 && resume_arg != CTX_ARG.into()
985 {
986 statements.push(Statement::new(
987 source_info,
988 StatementKind::Assign(Box::new((
989 resume_arg,
990 Rvalue::Use(Operand::Move(CTX_ARG.into()), WithRetag::Yes),
991 ))),
992 ));
993 }
994
995 let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
997 statements,
998 Some(Terminator { source_info, kind: TerminatorKind::goto(target) }),
999 false,
1000 ));
1001
1002 (point.state, block)
1003 })
1004 })
1005 .collect()
1006}
1007
1008impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1009 #[instrument(level = "debug", skip(self, tcx, body), ret)]
1010 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1011 debug!(def_id = ?body.source.def_id());
1012
1013 let Some(old_yield_ty) = body.yield_ty() else {
1014 return;
1016 };
1017 tracing::trace!(def_id = ?body.source.def_id());
1018
1019 let old_ret_ty = body.return_ty();
1020
1021 assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1022
1023 if let Some(dumper) = MirDumper::new(tcx, "coroutine_before", body) {
1024 dumper.dump_mir(body);
1025 }
1026
1027 let coroutine_ty = body.local_decls.raw[1].ty;
1029 let coroutine_kind = body.coroutine_kind().unwrap();
1030
1031 let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1033 tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1034 };
1035 let discr_ty = args.as_coroutine().discr_ty(tcx);
1036
1037 let new_ret_ty = match coroutine_kind {
1038 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1039 let poll_did = tcx.require_lang_item(LangItem::Poll, body.span);
1041 let poll_adt_ref = tcx.adt_def(poll_did);
1042 let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1043 Ty::new_adt(tcx, poll_adt_ref, poll_args)
1044 }
1045 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1046 let option_did = tcx.require_lang_item(LangItem::Option, body.span);
1048 let option_adt_ref = tcx.adt_def(option_did);
1049 let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1050 Ty::new_adt(tcx, option_adt_ref, option_args)
1051 }
1052 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1053 old_yield_ty
1055 }
1056 CoroutineKind::Coroutine(_) => {
1057 let state_did = tcx.require_lang_item(LangItem::CoroutineState, body.span);
1059 let state_adt_ref = tcx.adt_def(state_did);
1060 let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1061 Ty::new_adt(tcx, state_adt_ref, state_args)
1062 }
1063 };
1064
1065 let has_async_drops = has_async_drops(body);
1070
1071 if coroutine_kind.is_async_desugaring() {
1072 eliminate_get_context_calls(tcx, body);
1073 }
1074
1075 let always_live_locals = always_storage_live_locals(body);
1076 let movable = coroutine_kind.movability() == hir::Movability::Movable;
1077 let liveness_info =
1078 locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1079
1080 if tcx.sess.opts.unstable_opts.validate_mir {
1081 let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1082 assigned_local: None,
1083 saved_locals: &liveness_info.saved_locals,
1084 storage_conflicts: &liveness_info.storage_conflicts,
1085 };
1086
1087 vis.visit_body(body);
1088 }
1089
1090 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1094
1095 let can_return = can_return(tcx, body, body.typing_env(tcx));
1096
1097 let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1100 tracing::trace!(?new_ret_local);
1101
1102 let mut transform = TransformVisitor {
1108 tcx,
1109 coroutine_kind,
1110 remap,
1111 storage_liveness,
1112 always_live_locals,
1113 suspension_points: Vec::new(),
1114 discr_ty,
1115 new_ret_local,
1116 old_ret_ty,
1117 old_yield_ty,
1118 patch: Some(MirPatch::new(body)),
1119 };
1120 transform.visit_body(body);
1121
1122 transform.replace_local(RETURN_PLACE, new_ret_local, body);
1124
1125 let source_info = SourceInfo::outermost(body.span);
1128 let args_iter = body.args_iter();
1129 body.basic_blocks.as_mut()[START_BLOCK].statements.splice(
1130 0..0,
1131 args_iter.filter_map(|local| {
1132 let (ty, variant_index, idx) = transform.remap[local]?;
1133 let lhs = transform.make_field(variant_index, idx, ty);
1134 let rhs = Rvalue::Use(Operand::Move(local.into()), WithRetag::Yes);
1135 let assign = StatementKind::Assign(Box::new((lhs, rhs)));
1136 Some(Statement::new(source_info, assign))
1137 }),
1138 );
1139 transform.patch.take().unwrap().apply(body);
1140
1141 if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1143 body.arg_count = 1;
1144 }
1145
1146 for var in &mut body.var_debug_info {
1150 var.argument_index = None;
1151 }
1152
1153 body.coroutine.as_mut().unwrap().yield_ty = None;
1154 body.coroutine.as_mut().unwrap().resume_ty = None;
1155 body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1156
1157 let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1161
1162 if let Some(dumper) = MirDumper::new(tcx, "coroutine_pre-elab", body) {
1163 dumper.dump_mir(body);
1164 }
1165
1166 elaborate_coroutine_drops(tcx, body);
1170
1171 if let Some(dumper) = MirDumper::new(tcx, "coroutine_post-transform", body) {
1172 dumper.dump_mir(body);
1173 }
1174
1175 let can_unwind = can_unwind(tcx, body);
1176
1177 if has_async_drops {
1179 let drop_shim =
1181 create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1182 body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1183 } else {
1184 let drop_shim =
1186 create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1187 body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1188
1189 let proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body, coroutine_kind);
1191 body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1192 }
1193
1194 create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1196 }
1197
1198 fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
1199 PassPolicy::Required
1201 }
1202}
1203
1204struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1217 saved_locals: &'a CoroutineSavedLocals,
1218 storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1219 assigned_local: Option<CoroutineSavedLocal>,
1220}
1221
1222impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1223 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1224 if place.is_indirect() {
1225 return None;
1226 }
1227
1228 self.saved_locals.get(place.local)
1229 }
1230
1231 fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1232 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1233 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1234
1235 self.assigned_local = Some(assigned_local);
1236 f(self);
1237 self.assigned_local = None;
1238 }
1239 }
1240}
1241
1242impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1243 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1244 let Some(lhs) = self.assigned_local else {
1245 assert!(!context.is_use());
1250 return;
1251 };
1252
1253 let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1254
1255 if !self.storage_conflicts.contains(lhs, rhs) {
1256 bug!(
1257 "Assignment between coroutine saved locals whose storage is not \
1258 marked as conflicting: {:?}: {:?} = {:?}",
1259 location,
1260 lhs,
1261 rhs,
1262 );
1263 }
1264 }
1265
1266 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1267 match &statement.kind {
1268 StatementKind::Assign((lhs, rhs)) => {
1269 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1270 }
1271
1272 StatementKind::FakeRead(..)
1273 | StatementKind::SetDiscriminant { .. }
1274 | StatementKind::StorageLive(_)
1275 | StatementKind::StorageDead(_)
1276 | StatementKind::AscribeUserType(..)
1277 | StatementKind::PlaceMention(..)
1278 | StatementKind::Coverage(..)
1279 | StatementKind::Intrinsic(..)
1280 | StatementKind::ConstEvalCounter
1281 | StatementKind::BackwardIncompatibleDropHint { .. }
1282 | StatementKind::Nop => {}
1283 }
1284 }
1285
1286 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1287 match &terminator.kind {
1290 TerminatorKind::Call {
1291 func,
1292 args,
1293 destination,
1294 target: Some(_),
1295 unwind: _,
1296 call_source: _,
1297 fn_span: _,
1298 } => {
1299 self.check_assigned_place(*destination, |this| {
1300 this.visit_operand(func, location);
1301 for arg in args {
1302 this.visit_operand(&arg.node, location);
1303 }
1304 });
1305 }
1306
1307 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1308 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1309 }
1310
1311 TerminatorKind::InlineAsm { .. } => {}
1313
1314 TerminatorKind::Call { .. }
1315 | TerminatorKind::Goto { .. }
1316 | TerminatorKind::SwitchInt { .. }
1317 | TerminatorKind::UnwindResume
1318 | TerminatorKind::UnwindTerminate(_)
1319 | TerminatorKind::Return
1320 | TerminatorKind::TailCall { .. }
1321 | TerminatorKind::Unreachable
1322 | TerminatorKind::Drop { .. }
1323 | TerminatorKind::Assert { .. }
1324 | TerminatorKind::CoroutineDrop
1325 | TerminatorKind::FalseEdge { .. }
1326 | TerminatorKind::FalseUnwind { .. } => {}
1327 }
1328 }
1329}