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, 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                // 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, 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
163/// A `yield` point in the coroutine.
164struct SuspensionPoint<'tcx> {
165    /// State discriminant used when suspending or resuming at this point.
166    state: usize,
167    /// The block to jump to after resumption.
168    resume: BasicBlock,
169    /// Where to move the resume argument after resumption.
170    resume_arg: Place<'tcx>,
171    /// Which block to jump to if the coroutine is dropped in this state.
172    drop: Option<BasicBlock>,
173    /// Set of locals that have live storage while at this suspension point.
174    storage_liveness: DenseBitSet<Local>,
175}
176
177struct TransformVisitor<'tcx> {
178    tcx: TyCtxt<'tcx>,
179    coroutine_kind: hir::CoroutineKind,
180
181    // The type of the discriminant in the coroutine struct
182    discr_ty: Ty<'tcx>,
183
184    // Mapping from Local to (type of local, coroutine struct index)
185    remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
186
187    // A map from a suspension point in a block to the locals which have live storage at that point
188    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
189
190    // A list of suspension points, generated during the transform
191    suspension_points: Vec<SuspensionPoint<'tcx>>,
192
193    // The set of locals that have no `StorageLive`/`StorageDead` annotations.
194    always_live_locals: DenseBitSet<Local>,
195
196    // New local we just create to hold the `CoroutineState` value.
197    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            // `gen` continues return `None`
217            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            // `async gen` continues to return `Poll::Ready(None)`
227            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    // Make a `CoroutineState` or `Poll` variant assignment.
263    //
264    // `core::ops::CoroutineState` only has single element tuple variants,
265    // so we can just write to the downcasted first field and then set the
266    // discriminant to the appropriate variant.
267    #[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]) // Poll::Ready(val)
283                } else {
284                    (ONE, IndexVec::new()) // Poll::Pending
285                };
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()) // None
293                } else {
294                    (ONE, indexvec![val]) // Some(val)
295                };
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 // CoroutineState::Complete(val)
330                } else {
331                    ZERO // CoroutineState::Yielded(val)
332                };
333                make_aggregate_adt(coroutine_state_def_id, variant_idx, args, indexvec![val])
334            }
335        };
336
337        // Assign to `new_ret_local`, which will be replaced by `RETURN_PLACE` later.
338        statements.push(Statement::new(
339            source_info,
340            StatementKind::Assign(Box::new((self.new_ret_local.into(), rvalue))),
341        ));
342    }
343
344    // Create a Place referencing a coroutine struct field
345    #[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    // Create a statement which changes the discriminant
356    #[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    // Create a statement which reads the discriminant into a temporary
369    #[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    /// Swaps all references of `old_local` and `new_local`.
384    #[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        // Replace an Local in the remap with a coroutine struct access
411        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                    // `PlaceElem::Index` only accepts a `Local`, not an arbitrary `Place`.
428                    // If the local in indexing was saved across a yield point and remapped to a
429                    // coroutine struct field, we cannot inline the struct field access into
430                    // the index projection.
431                    // For example, an local storing the counter to track which element to drop in
432                    // an array is one such case.
433                    //
434                    // Instead, we inject an assignment before this location to restore the
435                    // saved local from the coroutine struct (`local = copy $projection`),
436                    // and leave the `PlaceElem::Index(local)` projection unchanged.
437                    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        // Remove StorageLive and StorageDead statements for remapped locals
460        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            // `visit_basic_block_data` introduces `Return` terminators which read `RETURN_PLACE`.
472            // But this `RETURN_PLACE` is already remapped, so we should not touch it again.
473            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                // We must assign the value first in case it gets declared dead below
484                self.make_state(
485                    Operand::Move(Place::return_place()),
486                    source_info,
487                    true,
488                    &mut data.statements,
489                );
490                // Return state.
491                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                // We must assign the value first in case it gets declared dead below
498                self.make_state(value.clone(), source_info, false, &mut data.statements);
499                // Yield state.
500                let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
501
502                // The resume arg target location might itself be remapped if its base local is
503                // live across a yield.
504                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    // Replace the by value coroutine argument
557    body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
558
559    // Add a deref to accesses of the coroutine state
560    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    // Replace the by ref coroutine argument
575    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    // Add the Pin field access to accesses of the coroutine state
580    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/// 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    // Add the switch as entry block, and put the former entry block at the end.
723    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    // We may point to `START_BLOCK` in our `cases`, replace it with `former_entry`.
730    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    // Poll::Ready(())
750    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    // Returning from a function with an uninhabited return type is undefined behavior.
796    if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
797        return false;
798    }
799
800    // If there's a return terminator the function may return.
801    body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
802    // Otherwise the function can't return.
803}
804
805fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
806    // Nothing can unwind when landing pads are off.
807    if !tcx.sess.panic_strategy().unwinds() {
808        return false;
809    }
810
811    // If we don't find an unwinding terminator, the function cannot unwind.
812    body.basic_blocks.iter().any(|block| block.terminator().unwind().is_some())
813}
814
815// Poison the coroutine when it unwinds
816fn 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            // An existing `Resume` terminator is redirected to jump to our dedicated
832            // "poisoning block" above.
833            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            // Any terminators that *can* unwind but don't have an unwind target set are also
839            // pointed at our poisoning block (unless they're part of the cleanup path).
840            && 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    // Poison the coroutine when it unwinds
856    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    // Jump to the entry point on the unresumed
865    cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
866
867    // Panic when resumed on the returned or poisoned state
868    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                // For `async_drop_in_place<T>::{closure}` we just keep return Poll::Ready,
883                // because async drop of such coroutine keeps polling original coroutine
884                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        // Iterator::next doesn't accept a pinned argument,
908        // unlike for all other coroutine kinds.
909        CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
910            make_coroutine_state_argument_indirect(tcx, body);
911        }
912    }
913
914    // Make sure we remove dead blocks to remove
915    // unrelated code from the drop part of the function
916    simplify::remove_dead_blocks(body);
917
918    pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
919
920    // Run derefer to fix Derefs that are not in the first place
921    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/// An operation that can be performed on a coroutine.
933#[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            // Find the target for this suspension point, if applicable
969            operation.target_block(point).map(|target| {
970                let mut statements = Vec::new();
971
972                // Create StorageLive instructions for locals with live storage
973                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                // Move the resume argument to the destination place of the `Yield` terminator
983                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                // Then jump to the real target
996                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            // This only applies to coroutines
1015            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        // The first argument is the coroutine type passed by value
1028        let coroutine_ty = body.local_decls.raw[1].ty;
1029        let coroutine_kind = body.coroutine_kind().unwrap();
1030
1031        // Get the discriminant type and args which typeck computed
1032        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                // Compute Poll<return_ty>
1040                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                // Compute Option<yield_ty>
1047                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                // The yield ty is already `Poll<Option<yield_ty>>`
1054                old_yield_ty
1055            }
1056            CoroutineKind::Coroutine(_) => {
1057                // Compute CoroutineState<yield_ty, return_ty>
1058                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        // We need to insert clean drop for unresumed state and perform drop elaboration
1066        // (finally in open_drop_for_tuple) before async drop expansion.
1067        // Async drops, produced by this drop elaboration, will be expanded,
1068        // and corresponding futures kept in layout.
1069        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        // Extract locals which are live across suspension point into `layout`
1091        // `remap` gives a mapping from local indices onto coroutine struct indices
1092        // `storage_liveness` tells us which locals have live storage at suspension points
1093        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        // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1098        // RETURN_PLACE then is a fresh unused local with type ret_ty.
1099        let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1100        tracing::trace!(?new_ret_local);
1101
1102        // Run the transformation which converts Places from Local to coroutine struct
1103        // accesses for locals in `remap`.
1104        // It also rewrites `return x` and `yield y` as writing a new coroutine state and returning
1105        // either `CoroutineState::Complete(x)` and `CoroutineState::Yielded(y)`,
1106        // or `Poll::Ready(x)` and `Poll::Pending` respectively depending on the coroutine kind.
1107        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        // Swap the actual `RETURN_PLACE` and the provisional `new_ret_local`.
1123        transform.replace_local(RETURN_PLACE, new_ret_local, body);
1124
1125        // MIR parameters are not explicitly assigned-to when entering the MIR body.
1126        // If we want to save their values inside the coroutine state, we need to do so explicitly.
1127        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        // Remove the context argument within generator bodies.
1142        if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1143            body.arg_count = 1;
1144        }
1145
1146        // The original arguments to the function are no longer arguments, mark them as such.
1147        // Otherwise they'll conflict with our new arguments, which although they don't have
1148        // argument_index set, will get emitted as unnamed arguments.
1149        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        // Insert `drop(coroutine_struct)` which is used to drop upvars for coroutines in
1158        // the unresumed state.
1159        // This is expanded to a drop ladder in `elaborate_coroutine_drops`.
1160        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        // Expand `drop(coroutine_struct)` to a drop ladder which destroys upvars.
1167        // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1168        // However we need to also elaborate the code generated by `insert_clean_drop`.
1169        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        // Create a copy of our MIR and use it to create the drop shim for the coroutine
1178        if has_async_drops {
1179            // If coroutine has async drops, generating async drop shim
1180            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            // If coroutine has no async drops, generating sync drop shim
1185            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            // For coroutine with sync drop, generating async proxy for `future_drop_poll` call
1190            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 the Coroutine::resume / Future::poll function
1195        create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1196    }
1197
1198    fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
1199        // Implements coroutine semantics by lowering the coroutine body to a state machine.
1200        PassPolicy::Required
1201    }
1202}
1203
1204/// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1205/// in the coroutine state machine but whose storage is not marked as conflicting
1206///
1207/// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1208///
1209/// This condition would arise when the assignment is the last use of `_5` but the initial
1210/// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1211/// conflicting. Non-conflicting coroutine saved locals may be stored at the same location within
1212/// the coroutine state machine, which would result in ill-formed MIR: the left-hand and right-hand
1213/// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1214///
1215/// [#73137]: https://github.com/rust-lang/rust/issues/73137
1216struct 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            // This visitor only invokes `visit_place` for the right-hand side of an assignment
1246            // and only after setting `self.assigned_local`. However, the default impl of
1247            // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1248            // with debuginfo. Ignore them here.
1249            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        // Checking for aliasing in terminators is probably overkill, but until we have actual
1288        // semantics, we should be conservative here.
1289        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            // FIXME: Does `asm!` have any aliasing requirements?
1312            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}