Skip to main content

rustc_mir_transform/coroutine/
mod.rs

1//! This is the implementation of the pass which transforms coroutines into state machines.
2//!
3//! MIR generation for coroutines creates a function which has a self argument which
4//! passes by value. This argument is effectively a coroutine type which only contains upvars and
5//! is only used for this argument inside the MIR for the coroutine.
6//! It is passed by value to enable upvars to be moved out of it. Drop elaboration runs on that
7//! MIR before this pass and creates drop flags for MIR locals.
8//! It will also drop the coroutine argument (which only consists of upvars) if any of the upvars
9//! are moved out of. This pass elaborates the drops of upvars / coroutine argument in the case
10//! that none of the upvars were moved out of. This is because we cannot have any drops of this
11//! coroutine in the MIR, since it is used to create the drop glue for the coroutine. We'd get
12//! infinite recursion otherwise.
13//!
14//! This pass creates the implementation for either the `Coroutine::resume` or `Future::poll`
15//! function and the drop shim for the coroutine based on the MIR input.
16//! It converts the coroutine argument from Self to &mut Self adding derefs in the MIR as needed.
17//! It computes the final layout of the coroutine struct which looks like this:
18//!     First upvars are stored
19//!     It is followed by the coroutine state field.
20//!     Then finally the MIR locals which are live across a suspension point are stored.
21//!     ```ignore (illustrative)
22//!     struct Coroutine {
23//!         upvars...,
24//!         state: u32,
25//!         mir_locals...,
26//!     }
27//!     ```
28//! This pass computes the meaning of the state field and the MIR locals which are live
29//! across a suspension point. There are however three hardcoded coroutine states:
30//!     0 - Coroutine have not been resumed yet
31//!     1 - Coroutine has returned / is completed
32//!     2 - Coroutine has been poisoned
33//!
34//! It also rewrites `return x` and `yield y` as setting a new coroutine state and returning
35//! `CoroutineState::Complete(x)` and `CoroutineState::Yielded(y)`,
36//! or `Poll::Ready(x)` and `Poll::Pending` respectively.
37//! MIR locals which are live across a suspension point are moved to the coroutine struct
38//! with references to them being updated with references to the coroutine struct.
39//!
40//! The pass creates two functions which have a switch on the coroutine state giving
41//! the action to take.
42//!
43//! One of them is the implementation of `Coroutine::resume` / `Future::poll`.
44//! For coroutines with state 0 (unresumed) it starts the execution of the coroutine.
45//! For coroutines with state 1 (returned) and state 2 (poisoned) it panics.
46//! Otherwise it continues the execution from the last suspension point.
47//!
48//! The other function is the drop glue for the coroutine.
49//! For coroutines with state 0 (unresumed) it drops the upvars of the coroutine.
50//! For coroutines with state 1 (returned) and state 2 (poisoned) it does nothing.
51//! Otherwise it drops all the values in scope at the last suspension point.
52
53mod 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                // Do not replace the implicit `_0` access here, as that's not possible. The
109                // transform already handles `return` correctly.
110            }
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
162/// A `yield` point in the coroutine.
163struct SuspensionPoint<'tcx> {
164    /// State discriminant used when suspending or resuming at this point.
165    state: usize,
166    /// The block to jump to after resumption.
167    resume: BasicBlock,
168    /// Where to move the resume argument after resumption.
169    resume_arg: Place<'tcx>,
170    /// Which block to jump to if the coroutine is dropped in this state.
171    drop: Option<BasicBlock>,
172    /// Set of locals that have live storage while at this suspension point.
173    storage_liveness: DenseBitSet<Local>,
174}
175
176struct TransformVisitor<'tcx> {
177    tcx: TyCtxt<'tcx>,
178    coroutine_kind: hir::CoroutineKind,
179
180    // The type of the discriminant in the coroutine struct
181    discr_ty: Ty<'tcx>,
182
183    // Mapping from Local to (type of local, coroutine struct index)
184    remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
185
186    // A map from a suspension point in a block to the locals which have live storage at that point
187    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
188
189    // A list of suspension points, generated during the transform
190    suspension_points: Vec<SuspensionPoint<'tcx>>,
191
192    // The set of locals that have no `StorageLive`/`StorageDead` annotations.
193    always_live_locals: DenseBitSet<Local>,
194
195    // New local we just create to hold the `CoroutineState` value.
196    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            // `gen` continues return `None`
216            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            // `async gen` continues to return `Poll::Ready(None)`
226            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    // Make a `CoroutineState` or `Poll` variant assignment.
262    //
263    // `core::ops::CoroutineState` only has single element tuple variants,
264    // so we can just write to the downcasted first field and then set the
265    // discriminant to the appropriate variant.
266    #[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]) // Poll::Ready(val)
282                } else {
283                    (ONE, IndexVec::new()) // Poll::Pending
284                };
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()) // None
292                } else {
293                    (ONE, indexvec![val]) // Some(val)
294                };
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 // CoroutineState::Complete(val)
329                } else {
330                    ZERO // CoroutineState::Yielded(val)
331                };
332                make_aggregate_adt(coroutine_state_def_id, variant_idx, args, indexvec![val])
333            }
334        };
335
336        // Assign to `new_ret_local`, which will be replaced by `RETURN_PLACE` later.
337        statements.push(Statement::new(
338            source_info,
339            StatementKind::Assign(Box::new((self.new_ret_local.into(), rvalue))),
340        ));
341    }
342
343    // Create a Place referencing a coroutine struct field
344    #[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    // Create a statement which changes the discriminant
355    #[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    // Create a statement which reads the discriminant into a temporary
368    #[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    /// Swaps all references of `old_local` and `new_local`.
383    #[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        // Replace an Local in the remap with a coroutine struct access
410        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                    // `PlaceElem::Index` only accepts a `Local`, not an arbitrary `Place`.
427                    // If the local in indexing was saved across a yield point and remapped to a
428                    // coroutine struct field, we cannot inline the struct field access into
429                    // the index projection.
430                    // For example, an local storing the counter to track which element to drop in
431                    // an array is one such case.
432                    //
433                    // Instead, we inject an assignment before this location to restore the
434                    // saved local from the coroutine struct (`local = copy $projection`),
435                    // and leave the `PlaceElem::Index(local)` projection unchanged.
436                    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        // Remove StorageLive and StorageDead statements for remapped locals
459        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            // `visit_basic_block_data` introduces `Return` terminators which read `RETURN_PLACE`.
471            // But this `RETURN_PLACE` is already remapped, so we should not touch it again.
472            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                // We must assign the value first in case it gets declared dead below
483                self.make_state(
484                    Operand::Move(Place::return_place()),
485                    source_info,
486                    true,
487                    &mut data.statements,
488                );
489                // Return state.
490                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                // We must assign the value first in case it gets declared dead below
497                self.make_state(value.clone(), source_info, false, &mut data.statements);
498                // Yield state.
499                let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
500
501                // The resume arg target location might itself be remapped if its base local is
502                // live across a yield.
503                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    // Replace the by value coroutine argument
556    body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty = ref_coroutine_ty;
557
558    // Add a deref to accesses of the coroutine state
559    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    // Replace the by ref coroutine argument
574    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    // Add the Pin field access to accesses of the coroutine state
579    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/// Async desugaring uses an unsafe binder type `ResumeTy` to circumvert borrow-checking.
599/// The `ResumeTy` hides a `&mut Context<'_>` behind an unsafe raw pointer, and the
600/// `get_context` function is being used to convert that back to a `&mut Context<'_>`.
601///
602/// The actual should be `&mut Context<'_>`. This performs the substitution:
603/// - create a new local `_r` of type `ResumeTy`;
604/// - assign `ResumeTy(transmute::<&mut Context<'_>, NonNull<Context<'_>>>(_2))` to that local;
605/// - let all the code use `_r` instead of `_2`.
606///
607/// Ideally the async lowering would not use the `ResumeTy`/`get_context` indirection,
608/// but rather directly use `&mut Context<'_>`, however that would currently
609/// lead to higher-kinded lifetime errors.
610/// See <https://github.com/rust-lang/rust/issues/105501>.
611///
612/// The async lowering step and the type / lifetime inference / checking are
613/// still using the `ResumeTy` indirection for the time being, and that indirection
614/// is removed here. After this transform, the coroutine body only knows about `&mut Context<'_>`.
615#[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    // Replace all occurrences of `CTX_ARG` with `resume_local: ResumeTy`,
626    // and set `CTX_ARG: &mut Context<'_>`.
627    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    // Now `CTX_ARG` is `&mut Context` and `resume_local` is a `ResumeTy`.
632    // Insert a `resume_local = ResumeTy(CTX_ARG as *mut Context<'static>)`
633    // at the function entry to make the bridge.
634    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
656/// HIR uses `get_context` to unwrap a `&mut Context<'_>` from a `ResumeTy`.
657/// Both types are just a single pointer, but liveness analysis does not know that and
658/// supposes that the operand and the destination are live at the same time.
659/// Forcibly inline those calls to avoid this.
660fn 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
702/// Replaces the entry point of `body` with a block that switches on the coroutine discriminant and
703/// dispatches to blocks according to `cases`.
704///
705/// After this function, the former entry point of the function will be the last block.
706fn 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    // MIR validation ensures that no block targets `ENTRY_BLOCK`.
715    #[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    // Add the switch as entry block, and put the former entry block at the end.
724    body.basic_blocks_mut().push_with(|new_index_for_former_entry, blocks| {
725        // We may point to `START_BLOCK` in our `cases`, replace it with `former_entry`.
726        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    // Poll::Ready(())
752    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    // Poll::Pending
803    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    // Returning from a function with an uninhabited return type is undefined behavior.
830    if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
831        return false;
832    }
833
834    // If there's a return terminator the function may return.
835    body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
836    // Otherwise the function can't return.
837}
838
839fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
840    // Nothing can unwind when landing pads are off.
841    if !tcx.sess.panic_strategy().unwinds() {
842        return false;
843    }
844
845    // If we don't find an unwinding terminator, the function cannot unwind.
846    body.basic_blocks.iter().any(|block| block.terminator().unwind().is_some())
847}
848
849// Poison the coroutine when it unwinds
850fn 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            // An existing `Resume` terminator is redirected to jump to our dedicated
866            // "poisoning block" above.
867            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            // Any terminators that *can* unwind but don't have an unwind target set are also
873            // pointed at our poisoning block (unless they're part of the cleanup path).
874            && 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    // Poison the coroutine when it unwinds
890    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    // Jump to the entry point on the unresumed
899    cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
900
901    // Panic when resumed on the returned or poisoned state
902    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                // For `async_drop_in_place<T>::{closure}` we just keep return Poll::Ready,
921                // because async drop of such coroutine keeps polling original coroutine
922                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        // Iterator::next doesn't accept a pinned argument,
950        // unlike for all other coroutine kinds.
951        CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
952            make_coroutine_state_argument_indirect(tcx, body);
953        }
954    }
955
956    // Iterator::next has no resume argument, so initialize the unit resume
957    // local at the start of each invocation.
958    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    // Make sure we remove dead blocks to remove
976    // unrelated code from the drop part of the function
977    simplify::remove_dead_blocks(body);
978
979    pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
980
981    // Run derefer to fix Derefs that are not in the first place
982    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/// An operation that can be performed on a coroutine.
994#[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            // Find the target for this suspension point, if applicable
1030            operation.target_block(point).map(|target| {
1031                let mut statements = Vec::new();
1032
1033                // Create StorageLive instructions for locals with live storage
1034                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                // Move the resume argument to the destination place of the `Yield` terminator
1044                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                // Then jump to the real target
1057                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            // This only applies to coroutines
1076            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        // The first argument is the coroutine type passed by value
1089        let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
1090        let coroutine_kind = body.coroutine_kind().unwrap();
1091
1092        // Get the discriminant type and args which typeck computed
1093        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                // Compute Poll<return_ty>
1101                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                // Compute Option<yield_ty>
1108                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                // The yield ty is already `Poll<Option<yield_ty>>`
1115                old_yield_ty
1116            }
1117            CoroutineKind::Coroutine(_) => {
1118                // Compute CoroutineState<yield_ty, return_ty>
1119                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        // We need to insert clean drop for unresumed state and perform drop elaboration
1127        // (finally in open_drop_for_tuple) before async drop expansion.
1128        // Async drops, produced by this drop elaboration, will be expanded,
1129        // and corresponding futures kept in layout.
1130        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        // Extract locals which are live across suspension point into `layout`
1152        // `remap` gives a mapping from local indices onto coroutine struct indices
1153        // `storage_liveness` tells us which locals have live storage at suspension points
1154        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        // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1159        // RETURN_PLACE then is a fresh unused local with type ret_ty.
1160        let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1161        tracing::trace!(?new_ret_local);
1162
1163        // Run the transformation which converts Places from Local to coroutine struct
1164        // accesses for locals in `remap`.
1165        // It also rewrites `return x` and `yield y` as writing a new coroutine state and returning
1166        // either `CoroutineState::Complete(x)` and `CoroutineState::Yielded(y)`,
1167        // or `Poll::Ready(x)` and `Poll::Pending` respectively depending on the coroutine kind.
1168        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        // Swap the actual `RETURN_PLACE` and the provisional `new_ret_local`.
1184        transform.replace_local(RETURN_PLACE, new_ret_local, body);
1185
1186        // MIR parameters are not explicitly assigned-to when entering the MIR body.
1187        // If we want to save their values inside the coroutine state, we need to do so explicitly.
1188        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        // Remove the context argument within generator bodies.
1203        if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1204            body.arg_count = 1;
1205        }
1206
1207        // The original arguments to the function are no longer arguments, mark them as such.
1208        // Otherwise they'll conflict with our new arguments, which although they don't have
1209        // argument_index set, will get emitted as unnamed arguments.
1210        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        // Insert `drop(coroutine_struct)` which is used to drop upvars for coroutines in
1219        // the unresumed state.
1220        // This is expanded to a drop ladder in `elaborate_coroutine_drops`.
1221        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        // Expand `drop(coroutine_struct)` to a drop ladder which destroys upvars.
1228        // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1229        // However we need to also elaborate the code generated by `insert_clean_drop`.
1230        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        // Create a copy of our MIR and use it to create the drop shim for the coroutine
1239        if has_async_drops {
1240            // If coroutine has async drops, generating async drop shim
1241            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            // If coroutine has no async drops, generating sync drop shim
1246            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            // For coroutine with sync drop, generating async proxy for `future_drop_poll` call
1251            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 the Coroutine::resume / Future::poll function
1256        create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1257    }
1258
1259    fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
1260        // Implements coroutine semantics by lowering the coroutine body to a state machine.
1261        PassPolicy::Required
1262    }
1263}
1264
1265/// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1266/// in the coroutine state machine but whose storage is not marked as conflicting
1267///
1268/// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1269///
1270/// This condition would arise when the assignment is the last use of `_5` but the initial
1271/// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1272/// conflicting. Non-conflicting coroutine saved locals may be stored at the same location within
1273/// the coroutine state machine, which would result in ill-formed MIR: the left-hand and right-hand
1274/// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1275///
1276/// [#73137]: https://github.com/rust-lang/rust/issues/73137
1277struct 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            // This visitor only invokes `visit_place` for the right-hand side of an assignment
1307            // and only after setting `self.assigned_local`. However, the default impl of
1308            // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1309            // with debuginfo. Ignore them here.
1310            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        // Checking for aliasing in terminators is probably overkill, but until we have actual
1349        // semantics, we should be conservative here.
1350        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            // FIXME: Does `asm!` have any aliasing requirements?
1373            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}