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_data_structures::thin_vec::ThinVec;
67use rustc_hir::attrs::lang_items::LangItem;
68use rustc_hir::{self as hir, CoroutineDesugaring, CoroutineKind};
69use rustc_index::bit_set::{BitMatrix, DenseBitSet, GrowableBitSet};
70use rustc_index::{Idx, IndexVec, indexvec};
71use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
72use rustc_middle::mir::*;
73use rustc_middle::ty::{
74    self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, ShimKind, Ty, TyCtxt,
75};
76use rustc_middle::{bug, span_bug};
77use rustc_mir_dataflow::impls::always_storage_live_locals;
78use rustc_span::def_id::DefId;
79use tracing::{debug, instrument};
80
81use crate::deref_separator::deref_finder;
82use crate::patch::MirPatch;
83use crate::{PassPolicy, abort_unwinding_calls, pass_manager as pm, simplify};
84
85pub(super) struct StateTransform;
86
87struct RenameLocalVisitor<'tcx> {
88    from: Local,
89    to: Local,
90    tcx: TyCtxt<'tcx>,
91}
92
93impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
94    fn tcx(&self) -> TyCtxt<'tcx> {
95        self.tcx
96    }
97
98    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
99        if *local == self.from {
100            *local = self.to;
101        } else if *local == self.to {
102            *local = self.from;
103        }
104    }
105
106    fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
107        match terminator.kind {
108            TerminatorKind::Return => {
109                // Do not replace the implicit `_0` access here, as that's not possible. The
110                // transform already handles `return` correctly.
111            }
112            _ => self.super_terminator(terminator, location),
113        }
114    }
115}
116
117struct SelfArgVisitor<'tcx> {
118    tcx: TyCtxt<'tcx>,
119    new_base: Place<'tcx>,
120}
121
122impl<'tcx> SelfArgVisitor<'tcx> {
123    fn new(tcx: TyCtxt<'tcx>, new_base: Place<'tcx>) -> Self {
124        Self { tcx, new_base }
125    }
126}
127
128impl<'tcx> MutVisitor<'tcx> for SelfArgVisitor<'tcx> {
129    fn tcx(&self) -> TyCtxt<'tcx> {
130        self.tcx
131    }
132
133    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
134        assert_ne!(*local, SELF_ARG);
135    }
136
137    fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
138        if place.local == SELF_ARG {
139            replace_base(place, self.new_base, self.tcx);
140        }
141
142        for elem in place.projection.iter() {
143            if let PlaceElem::Index(local) = elem {
144                assert_ne!(local, SELF_ARG);
145            }
146        }
147    }
148}
149
150#[tracing::instrument(level = "trace", skip(tcx))]
151fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
152    place.local = new_base.local;
153
154    let mut new_projection = new_base.projection.to_vec();
155    new_projection.append(&mut place.projection.to_vec());
156
157    place.projection = tcx.mk_place_elems(&new_projection);
158    tracing::trace!(?place);
159}
160
161const SELF_ARG: Local = Local::arg(0);
162pub(crate) const CTX_ARG: Local = Local::arg(1);
163
164/// A `yield` point in the coroutine.
165struct SuspensionPoint<'tcx> {
166    /// State discriminant used when suspending or resuming at this point.
167    state: usize,
168    /// The block to jump to after resumption.
169    resume: BasicBlock,
170    /// Where to move the resume argument after resumption.
171    resume_arg: Place<'tcx>,
172    /// Which block to jump to if the coroutine is dropped in this state.
173    drop: Option<BasicBlock>,
174    /// Set of locals that have live storage while at this suspension point.
175    storage_liveness: GrowableBitSet<Local>,
176}
177
178struct TransformVisitor<'tcx> {
179    tcx: TyCtxt<'tcx>,
180    coroutine_kind: hir::CoroutineKind,
181
182    // The type of the discriminant in the coroutine struct
183    discr_ty: Ty<'tcx>,
184
185    // Mapping from Local to (type of local, coroutine struct index)
186    remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
187
188    // A map from a suspension point in a block to the locals which have live storage at that point
189    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
190
191    // A list of suspension points, generated during the transform
192    suspension_points: Vec<SuspensionPoint<'tcx>>,
193
194    // The set of locals that have no `StorageLive`/`StorageDead` annotations.
195    always_live_locals: DenseBitSet<Local>,
196
197    // New local we just create to hold the `CoroutineState` value.
198    new_ret_local: Local,
199
200    old_yield_ty: Ty<'tcx>,
201
202    old_ret_ty: Ty<'tcx>,
203
204    patch: Option<MirPatch<'tcx>>,
205}
206
207impl<'tcx> TransformVisitor<'tcx> {
208    fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
209        let block = body.basic_blocks.next_index();
210        let source_info = SourceInfo::outermost(body.span);
211
212        let none_value = match self.coroutine_kind {
213            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
214                span_bug!(body.span, "`Future`s are not fused inherently")
215            }
216            CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
217            // `gen` continues return `None`
218            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
219                let option_def_id = self.tcx.require_lang_item(LangItem::Option, body.span);
220                make_aggregate_adt(
221                    option_def_id,
222                    VariantIdx::ZERO,
223                    self.tcx.mk_args(&[self.old_yield_ty.into()]),
224                    IndexVec::new(),
225                )
226            }
227            // `async gen` continues to return `Poll::Ready(None)`
228            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
229                let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
230                let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
231                let yield_ty = args.type_at(0);
232                Rvalue::Use(
233                    Operand::Constant(Box::new(ConstOperand {
234                        span: source_info.span,
235                        const_: Const::Unevaluated(
236                            UnevaluatedConst::new(
237                                self.tcx.require_lang_item(LangItem::AsyncGenFinished, body.span),
238                                self.tcx.mk_args(&[yield_ty.into()]),
239                            ),
240                            self.old_yield_ty,
241                        ),
242                        user_ty: None,
243                    })),
244                    WithRetag::Yes,
245                )
246            }
247        };
248
249        let statements = vec![Statement::new(
250            source_info,
251            StatementKind::Assign(Box::new((Place::return_place(), none_value))),
252        )];
253
254        body.basic_blocks_mut().push(BasicBlockData::new_stmts(
255            statements,
256            Some(Terminator {
257                source_info,
258                kind: TerminatorKind::Return,
259                attributes: ThinVec::new(),
260            }),
261            false,
262        ));
263
264        block
265    }
266
267    // Make a `CoroutineState` or `Poll` variant assignment.
268    //
269    // `core::ops::CoroutineState` only has single element tuple variants,
270    // so we can just write to the downcasted first field and then set the
271    // discriminant to the appropriate variant.
272    #[tracing::instrument(level = "trace", skip(self, statements))]
273    fn make_state(
274        &self,
275        val: Operand<'tcx>,
276        source_info: SourceInfo,
277        is_return: bool,
278        statements: &mut Vec<Statement<'tcx>>,
279    ) {
280        const ZERO: VariantIdx = VariantIdx::ZERO;
281        const ONE: VariantIdx = VariantIdx::from_usize(1);
282        let rvalue = match self.coroutine_kind {
283            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
284                let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, source_info.span);
285                let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
286                let (variant_idx, operands) = if is_return {
287                    (ZERO, indexvec![val]) // Poll::Ready(val)
288                } else {
289                    (ONE, IndexVec::new()) // Poll::Pending
290                };
291                make_aggregate_adt(poll_def_id, variant_idx, args, operands)
292            }
293            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
294                let option_def_id = self.tcx.require_lang_item(LangItem::Option, source_info.span);
295                let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
296                let (variant_idx, operands) = if is_return {
297                    (ZERO, IndexVec::new()) // None
298                } else {
299                    (ONE, indexvec![val]) // Some(val)
300                };
301                make_aggregate_adt(option_def_id, variant_idx, args, operands)
302            }
303            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
304                if is_return {
305                    let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
306                    let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
307                    let yield_ty = args.type_at(0);
308                    Rvalue::Use(
309                        Operand::Constant(Box::new(ConstOperand {
310                            span: source_info.span,
311                            const_: Const::Unevaluated(
312                                UnevaluatedConst::new(
313                                    self.tcx.require_lang_item(
314                                        LangItem::AsyncGenFinished,
315                                        source_info.span,
316                                    ),
317                                    self.tcx.mk_args(&[yield_ty.into()]),
318                                ),
319                                self.old_yield_ty,
320                            ),
321                            user_ty: None,
322                        })),
323                        WithRetag::Yes,
324                    )
325                } else {
326                    Rvalue::Use(val, WithRetag::Yes)
327                }
328            }
329            CoroutineKind::Coroutine(_) => {
330                let coroutine_state_def_id =
331                    self.tcx.require_lang_item(LangItem::CoroutineState, source_info.span);
332                let args = self.tcx.mk_args(&[self.old_yield_ty.into(), self.old_ret_ty.into()]);
333                let variant_idx = if is_return {
334                    ONE // CoroutineState::Complete(val)
335                } else {
336                    ZERO // CoroutineState::Yielded(val)
337                };
338                make_aggregate_adt(coroutine_state_def_id, variant_idx, args, indexvec![val])
339            }
340        };
341
342        // Assign to `new_ret_local`, which will be replaced by `RETURN_PLACE` later.
343        statements.push(Statement::new(
344            source_info,
345            StatementKind::Assign(Box::new((self.new_ret_local.into(), rvalue))),
346        ));
347    }
348
349    // Create a Place referencing a coroutine struct field
350    #[tracing::instrument(level = "trace", skip(self), ret)]
351    fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
352        let self_place = Place::from(SELF_ARG);
353        let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
354        let mut projection = base.projection.to_vec();
355        projection.push(ProjectionElem::Field(idx, ty));
356
357        Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
358    }
359
360    // Create a statement which changes the discriminant
361    #[tracing::instrument(level = "trace", skip(self))]
362    fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
363        let self_place = Place::from(SELF_ARG);
364        Statement::new(
365            source_info,
366            StatementKind::SetDiscriminant {
367                place: Box::new(self_place),
368                variant_index: state_disc,
369            },
370        )
371    }
372
373    // Create a statement which reads the discriminant into a temporary
374    #[tracing::instrument(level = "trace", skip(self, body))]
375    fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
376        let temp_decl = LocalDecl::new(self.discr_ty, body.span);
377        let local_decls_len = body.local_decls.push(temp_decl);
378        let temp = Place::from(local_decls_len);
379
380        let self_place = Place::from(SELF_ARG);
381        let assign = Statement::new(
382            SourceInfo::outermost(body.span),
383            StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
384        );
385        (assign, temp)
386    }
387
388    /// Swaps all references of `old_local` and `new_local`.
389    #[tracing::instrument(level = "trace", skip(self, body))]
390    fn replace_local(&mut self, old_local: Local, new_local: Local, body: &mut Body<'tcx>) {
391        body.local_decls.swap(old_local, new_local);
392
393        let mut visitor = RenameLocalVisitor { from: old_local, to: new_local, tcx: self.tcx };
394        visitor.visit_body(body);
395        for suspension in &mut self.suspension_points {
396            let ctxt = PlaceContext::MutatingUse(MutatingUseContext::Yield);
397            let location = Location { block: START_BLOCK, statement_index: 0 };
398            visitor.visit_place(&mut suspension.resume_arg, ctxt, location);
399        }
400    }
401}
402
403impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
404    fn tcx(&self) -> TyCtxt<'tcx> {
405        self.tcx
406    }
407
408    #[tracing::instrument(level = "trace", skip(self), ret)]
409    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _location: Location) {
410        assert!(!self.remap.contains(*local));
411    }
412
413    #[tracing::instrument(level = "trace", skip(self), ret)]
414    fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, location: Location) {
415        // Replace an Local in the remap with a coroutine struct access
416        if let Some(&Some((ty, variant_index, idx))) = self.remap.get(place.local) {
417            replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
418        }
419        if let Some(new_projection) = self.process_projection(&place.projection, location) {
420            place.projection = self.tcx.mk_place_elems(&new_projection);
421        }
422    }
423
424    fn process_projection_elem(
425        &mut self,
426        elem: PlaceElem<'tcx>,
427        location: Location,
428    ) -> Option<PlaceElem<'tcx>> {
429        match elem {
430            PlaceElem::Index(local) => {
431                if let Some(&Some((ty, variant, idx))) = self.remap.get(local) {
432                    // `PlaceElem::Index` only accepts a `Local`, not an arbitrary `Place`.
433                    // If the local in indexing was saved across a yield point and remapped to a
434                    // coroutine struct field, we cannot inline the struct field access into
435                    // the index projection.
436                    // For example, an local storing the counter to track which element to drop in
437                    // an array is one such case.
438                    //
439                    // Instead, we inject an assignment before this location to restore the
440                    // saved local from the coroutine struct (`local = copy $projection`),
441                    // and leave the `PlaceElem::Index(local)` projection unchanged.
442                    let field = self.make_field(variant, idx, ty);
443                    self.patch.as_mut().unwrap().add_assign(
444                        location,
445                        Place::from(local),
446                        Rvalue::Use(Operand::Copy(field), WithRetag::No),
447                    );
448                }
449                None
450            }
451            PlaceElem::Field(..)
452            | PlaceElem::OpaqueCast(..)
453            | PlaceElem::UnwrapUnsafeBinder(..)
454            | PlaceElem::Deref
455            | PlaceElem::ConstantIndex { .. }
456            | PlaceElem::Subslice { .. }
457            | PlaceElem::Downcast(..)
458            | PlaceElem::PhantomDeref => None,
459        }
460    }
461
462    #[tracing::instrument(level = "trace", skip(self, stmt), ret)]
463    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, location: Location) {
464        // Remove StorageLive and StorageDead statements for remapped locals
465        if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
466            && self.remap.contains(l)
467        {
468            stmt.make_nop(true);
469        }
470        self.super_statement(stmt, location);
471    }
472
473    #[tracing::instrument(level = "trace", skip(self, term), ret)]
474    fn visit_terminator(&mut self, term: &mut Terminator<'tcx>, location: Location) {
475        if let TerminatorKind::Return = term.kind {
476            // `visit_basic_block_data` introduces `Return` terminators which read `RETURN_PLACE`.
477            // But this `RETURN_PLACE` is already remapped, so we should not touch it again.
478            return;
479        }
480        self.super_terminator(term, location);
481    }
482
483    #[tracing::instrument(level = "trace", skip(self, data), ret)]
484    fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
485        match data.terminator().kind {
486            TerminatorKind::Return => {
487                let source_info = data.terminator().source_info;
488                // We must assign the value first in case it gets declared dead below
489                self.make_state(
490                    Operand::Move(Place::return_place()),
491                    source_info,
492                    true,
493                    &mut data.statements,
494                );
495                // Return state.
496                let state = VariantIdx::new(CoroutineArgs::RETURNED);
497                data.statements.push(self.set_discr(state, source_info));
498                data.terminator_mut().kind = TerminatorKind::Return;
499            }
500            TerminatorKind::Yield { ref value, resume, mut resume_arg, drop } => {
501                let source_info = data.terminator().source_info;
502                // We must assign the value first in case it gets declared dead below
503                self.make_state(value.clone(), source_info, false, &mut data.statements);
504                // Yield state.
505                let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
506
507                // The resume arg target location might itself be remapped if its base local is
508                // live across a yield.
509                if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
510                    replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
511                }
512
513                let storage_liveness: GrowableBitSet<Local> =
514                    self.storage_liveness[block].clone().unwrap().into();
515
516                for i in 0..self.always_live_locals.domain_size() {
517                    let l = Local::new(i);
518                    let needs_storage_dead = storage_liveness.contains(l)
519                        && !self.remap.contains(l)
520                        && !self.always_live_locals.contains(l);
521                    if needs_storage_dead {
522                        data.statements
523                            .push(Statement::new(source_info, StatementKind::StorageDead(l)));
524                    }
525                }
526
527                self.suspension_points.push(SuspensionPoint {
528                    state,
529                    resume,
530                    resume_arg,
531                    drop,
532                    storage_liveness,
533                });
534
535                let state = VariantIdx::new(state);
536                data.statements.push(self.set_discr(state, source_info));
537                data.terminator_mut().kind = TerminatorKind::Return;
538            }
539            _ => {}
540        }
541
542        self.super_basic_block_data(block, data);
543    }
544}
545
546fn make_aggregate_adt<'tcx>(
547    def_id: DefId,
548    variant_idx: VariantIdx,
549    args: GenericArgsRef<'tcx>,
550    operands: IndexVec<FieldIdx, Operand<'tcx>>,
551) -> Rvalue<'tcx> {
552    Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
553}
554
555#[tracing::instrument(level = "trace", skip(tcx, body))]
556fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
557    let coroutine_ty = body.local_decls[SELF_ARG].ty;
558
559    let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
560
561    // Replace the by value coroutine argument
562    body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
563
564    // Add a deref to accesses of the coroutine state
565    SelfArgVisitor::new(tcx, tcx.mk_place_deref(SELF_ARG.into())).visit_body(body);
566}
567
568#[tracing::instrument(level = "trace", skip(tcx, body))]
569fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
570    let coroutine_ty = body.local_decls[SELF_ARG].ty;
571
572    let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
573
574    let pin_did = tcx.require_lang_item(LangItem::Pin, body.span);
575    let pin_adt_ref = tcx.adt_def(pin_did);
576    let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
577    let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
578
579    // Replace the by ref coroutine argument
580    body.local_decls[SELF_ARG].ty = pin_ref_coroutine_ty;
581
582    let unpinned_local = body.local_decls.push(LocalDecl::new(ref_coroutine_ty, body.span));
583
584    // Add the Pin field access to accesses of the coroutine state
585    SelfArgVisitor::new(tcx, tcx.mk_place_deref(unpinned_local.into())).visit_body(body);
586
587    let source_info = SourceInfo::outermost(body.span);
588    let pin_field = tcx.mk_place_field(SELF_ARG.into(), FieldIdx::ZERO, ref_coroutine_ty);
589
590    let statements = &mut body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements;
591    statements.insert(
592        0,
593        Statement::new(
594            source_info,
595            StatementKind::Assign(Box::new((
596                unpinned_local.into(),
597                Rvalue::Use(Operand::Copy(pin_field), WithRetag::Yes),
598            ))),
599        ),
600    );
601}
602
603/// Async desugaring uses an unsafe binder type `ResumeTy` to circumvert borrow-checking.
604/// The `ResumeTy` hides a `&mut Context<'_>` behind an unsafe raw pointer, and the
605/// `get_context` function is being used to convert that back to a `&mut Context<'_>`.
606///
607/// The actual should be `&mut Context<'_>`. This performs the substitution:
608/// - create a new local `_r` of type `ResumeTy`;
609/// - assign `ResumeTy(transmute::<&mut Context<'_>, NonNull<Context<'_>>>(_2))` to that local;
610/// - let all the code use `_r` instead of `_2`.
611///
612/// Ideally the async lowering would not use the `ResumeTy`/`get_context` indirection,
613/// but rather directly use `&mut Context<'_>`, however that would currently
614/// lead to higher-kinded lifetime errors.
615/// See <https://github.com/rust-lang/rust/issues/105501>.
616///
617/// The async lowering step and the type / lifetime inference / checking are
618/// still using the `ResumeTy` indirection for the time being, and that indirection
619/// is removed here. After this transform, the coroutine body only knows about `&mut Context<'_>`.
620#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
621fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
622    let context_mut_ref = Ty::new_task_context(tcx);
623    let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
624    let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
625        ty::GenericArgs::empty(),
626        body.typing_env(tcx),
627        tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
628    );
629
630    // Replace all occurrences of `CTX_ARG` with `resume_local: ResumeTy`,
631    // and set `CTX_ARG: &mut Context<'_>`.
632    let resume_local = body.local_decls.push(LocalDecl::new(context_mut_ref, body.span));
633    body.local_decls.swap(CTX_ARG, resume_local);
634    RenameLocalVisitor { from: CTX_ARG, to: resume_local, tcx }.visit_body(body);
635
636    // Now `CTX_ARG` is `&mut Context` and `resume_local` is a `ResumeTy`.
637    // Insert a `resume_local = ResumeTy(CTX_ARG as *mut Context<'static>)`
638    // at the function entry to make the bridge.
639    let source_info = SourceInfo::outermost(body.span);
640    let nonnull_local = body.local_decls.push(LocalDecl::new(resume_nonnull_ty, body.span));
641    let nonnull_rhs =
642        Rvalue::Cast(CastKind::Transmute, Operand::Move(CTX_ARG.into()), resume_nonnull_ty);
643    let nonnull_assign = StatementKind::Assign(Box::new((nonnull_local.into(), nonnull_rhs)));
644    let resume_rhs = Rvalue::Aggregate(
645        Box::new(AggregateKind::Adt(
646            resume_ty_def_id,
647            VariantIdx::ZERO,
648            ty::GenericArgs::empty(),
649            None,
650            None,
651        )),
652        indexvec![Operand::Move(nonnull_local.into())],
653    );
654    let resume_assign = StatementKind::Assign(Box::new((resume_local.into(), resume_rhs)));
655    body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements.splice(
656        0..0,
657        [Statement::new(source_info, nonnull_assign), Statement::new(source_info, resume_assign)],
658    );
659}
660
661/// HIR uses `get_context` to unwrap a `&mut Context<'_>` from a `ResumeTy`.
662/// Both types are just a single pointer, but liveness analysis does not know that and
663/// supposes that the operand and the destination are live at the same time.
664/// Forcibly inline those calls to avoid this.
665fn eliminate_get_context_calls<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
666    let context_mut_ref = Ty::new_task_context(tcx);
667    let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
668    let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
669        ty::GenericArgs::empty(),
670        body.typing_env(tcx),
671        tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
672    );
673
674    let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, body.span);
675    for bb_data in body.basic_blocks.as_mut().iter_mut() {
676        if bb_data.is_cleanup {
677            continue;
678        }
679
680        let terminator = bb_data.terminator_mut();
681        if let TerminatorKind::Call { func, args, destination, target, .. } = &terminator.kind
682            && let func_ty = func.ty(&body.local_decls, tcx)
683            && let ty::FnDef(def_id, _) = *func_ty.kind()
684            && def_id == get_context_def_id
685            && let [arg] = &**args
686            && let Some(place) = arg.node.place()
687        {
688            let arg =
689                Rvalue::Cast(
690                    CastKind::Transmute,
691                    Operand::Copy(place.project_deeper(
692                        &[PlaceElem::Field(FieldIdx::ZERO, resume_nonnull_ty)],
693                        tcx,
694                    )),
695                    context_mut_ref,
696                );
697            let assign = Statement::new(
698                terminator.source_info,
699                StatementKind::Assign(Box::new((*destination, arg))),
700            );
701            terminator.kind = TerminatorKind::Goto { target: target.unwrap() };
702            bb_data.statements.push(assign);
703        }
704    }
705}
706
707/// Replaces the entry point of `body` with a block that switches on the coroutine discriminant and
708/// dispatches to blocks according to `cases`.
709///
710/// After this function, the former entry point of the function will be the last block.
711fn insert_switch<'tcx>(
712    body: &mut Body<'tcx>,
713    cases: Vec<(usize, BasicBlock)>,
714    transform: &TransformVisitor<'tcx>,
715    default_block: BasicBlock,
716) {
717    let (assign, discr) = transform.get_discr(body);
718
719    // MIR validation ensures that no block targets `ENTRY_BLOCK`.
720    #[cfg(debug_assertions)]
721    for bb in body.basic_blocks.iter() {
722        for target in bb.terminator().successors() {
723            assert_ne!(target, START_BLOCK);
724        }
725    }
726
727    // Add the switch as entry block, and put the former entry block at the end.
728    let former_entry = std::mem::replace(
729        &mut body.basic_blocks_mut()[START_BLOCK],
730        BasicBlockData::new_stmts(vec![assign], None, false),
731    );
732    let former_entry = body.basic_blocks_mut().push(former_entry);
733
734    // We may point to `START_BLOCK` in our `cases`, replace it with `former_entry`.
735    let mut switch_targets =
736        SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
737    for bb in switch_targets.all_targets_mut() {
738        if *bb == START_BLOCK {
739            *bb = former_entry;
740        }
741    }
742
743    let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
744    body.basic_blocks_mut()[START_BLOCK].terminator = Some(Terminator {
745        source_info: SourceInfo::outermost(body.span),
746        kind: switch,
747        attributes: ThinVec::new(),
748    });
749}
750
751fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
752    let source_info = SourceInfo::outermost(body.span);
753    body.basic_blocks_mut().push(BasicBlockData::new(
754        Some(Terminator { source_info, kind, attributes: ThinVec::new() }),
755        false,
756    ))
757}
758
759fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
760    // Poll::Ready(())
761    let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
762    let args = tcx.mk_args(&[tcx.types.unit.into()]);
763    let val = Operand::Constant(Box::new(ConstOperand {
764        span: source_info.span,
765        user_ty: None,
766        const_: Const::zero_sized(tcx.types.unit),
767    }));
768    let ready_val = Rvalue::Aggregate(
769        Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
770        indexvec![val],
771    );
772    Statement::new(source_info, StatementKind::Assign(Box::new((Place::return_place(), ready_val))))
773}
774
775fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
776    let source_info = SourceInfo::outermost(body.span);
777    body.basic_blocks_mut().push(BasicBlockData::new_stmts(
778        [return_poll_ready_assign(tcx, source_info)].to_vec(),
779        Some(Terminator { source_info, kind: TerminatorKind::Return, attributes: ThinVec::new() }),
780        false,
781    ))
782}
783
784fn insert_panic_block<'tcx>(
785    tcx: TyCtxt<'tcx>,
786    body: &mut Body<'tcx>,
787    message: AssertMessage<'tcx>,
788) -> BasicBlock {
789    let assert_block = body.basic_blocks.next_index();
790    let kind = TerminatorKind::Assert {
791        cond: Operand::Constant(Box::new(ConstOperand {
792            span: body.span,
793            user_ty: None,
794            const_: Const::from_bool(tcx, false),
795        })),
796        expected: true,
797        msg: Box::new(message),
798        target: assert_block,
799        unwind: UnwindAction::Continue,
800    };
801
802    insert_term_block(body, kind)
803}
804
805fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
806    // Returning from a function with an uninhabited return type is undefined behavior.
807    if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
808        return false;
809    }
810
811    // If there's a return terminator the function may return.
812    body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
813    // Otherwise the function can't return.
814}
815
816fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
817    // Nothing can unwind when landing pads are off.
818    if !tcx.sess.panic_strategy().unwinds() {
819        return false;
820    }
821
822    // If we don't find an unwinding terminator, the function cannot unwind.
823    body.basic_blocks.iter().any(|block| block.terminator().unwind().is_some())
824}
825
826// Poison the coroutine when it unwinds
827fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
828    transform: &TransformVisitor<'tcx>,
829    body: &mut Body<'tcx>,
830) {
831    let source_info = SourceInfo::outermost(body.span);
832    let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
833        vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)],
834        Some(Terminator {
835            source_info,
836            kind: TerminatorKind::UnwindResume,
837
838            attributes: ThinVec::new(),
839        }),
840        true,
841    ));
842
843    for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
844        let source_info = block.terminator().source_info;
845
846        if let TerminatorKind::UnwindResume = block.terminator().kind {
847            // An existing `Resume` terminator is redirected to jump to our dedicated
848            // "poisoning block" above.
849            if idx != poison_block {
850                *block.terminator_mut() = Terminator {
851                    source_info,
852                    kind: TerminatorKind::Goto { target: poison_block },
853
854                    attributes: ThinVec::new(),
855                };
856            }
857        } else if !block.is_cleanup
858            // Any terminators that *can* unwind but don't have an unwind target set are also
859            // pointed at our poisoning block (unless they're part of the cleanup path).
860            && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
861        {
862            *unwind = UnwindAction::Cleanup(poison_block);
863        }
864    }
865}
866
867#[tracing::instrument(level = "trace", skip(tcx, transform, body))]
868fn create_coroutine_resume_function<'tcx>(
869    tcx: TyCtxt<'tcx>,
870    transform: TransformVisitor<'tcx>,
871    body: &mut Body<'tcx>,
872    can_return: bool,
873    can_unwind: bool,
874) {
875    // Poison the coroutine when it unwinds
876    if can_unwind {
877        generate_poison_block_and_redirect_unwinds_there(&transform, body);
878    }
879
880    let mut cases = create_cases(body, &transform, Operation::Resume);
881
882    use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
883
884    // Jump to the entry point on the unresumed
885    cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
886
887    // Panic when resumed on the returned or poisoned state
888    if can_unwind {
889        cases.insert(
890            1,
891            (
892                CoroutineArgs::POISONED,
893                insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
894            ),
895        );
896    }
897
898    if can_return {
899        let block = match transform.coroutine_kind {
900            CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
901            | CoroutineKind::Coroutine(_) => {
902                // For `async_drop_in_place<T>::{closure}` we just keep return Poll::Ready,
903                // because async drop of such coroutine keeps polling original coroutine
904                if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
905                    insert_poll_ready_block(tcx, body)
906                } else {
907                    insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
908                }
909            }
910            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
911            | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
912                transform.insert_none_ret_block(body)
913            }
914        };
915        cases.insert(1, (CoroutineArgs::RETURNED, block));
916    }
917
918    let default_block = insert_term_block(body, TerminatorKind::Unreachable);
919    insert_switch(body, cases, &transform, default_block);
920
921    match transform.coroutine_kind {
922        CoroutineKind::Coroutine(_)
923        | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
924        {
925            make_coroutine_state_argument_pinned(tcx, body);
926        }
927        // Iterator::next doesn't accept a pinned argument,
928        // unlike for all other coroutine kinds.
929        CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
930            make_coroutine_state_argument_indirect(tcx, body);
931        }
932    }
933
934    // Make sure we remove dead blocks to remove
935    // unrelated code from the drop part of the function
936    simplify::remove_dead_blocks(body);
937
938    pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
939
940    // Run derefer to fix Derefs that are not in the first place
941    deref_finder(tcx, body, false);
942
943    if transform.coroutine_kind.is_async_desugaring() {
944        transform_async_context(tcx, body);
945    }
946
947    if let Some(dumper) = MirDumper::new(tcx, "coroutine_resume", body) {
948        dumper.dump_mir(body);
949    }
950}
951
952/// An operation that can be performed on a coroutine.
953#[derive(PartialEq, Copy, Clone, Debug)]
954enum Operation {
955    Resume,
956    Drop,
957    AsyncDrop,
958}
959
960impl Operation {
961    fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
962        match self {
963            Operation::Resume => Some(point.resume),
964            Operation::Drop | Operation::AsyncDrop => point.drop,
965        }
966    }
967
968    fn resume_place<'tcx>(self, point: &SuspensionPoint<'tcx>) -> Option<Place<'tcx>> {
969        match self {
970            Operation::Resume | Operation::AsyncDrop => Some(point.resume_arg),
971            Operation::Drop => None,
972        }
973    }
974}
975
976#[tracing::instrument(level = "trace", skip(transform, body))]
977fn create_cases<'tcx>(
978    body: &mut Body<'tcx>,
979    transform: &TransformVisitor<'tcx>,
980    operation: Operation,
981) -> Vec<(usize, BasicBlock)> {
982    let source_info = SourceInfo::outermost(body.span);
983
984    transform
985        .suspension_points
986        .iter()
987        .filter_map(|point| {
988            // Find the target for this suspension point, if applicable
989            operation.target_block(point).map(|target| {
990                let mut statements = Vec::new();
991
992                // Create StorageLive instructions for locals with live storage
993                for l in body.local_decls.indices() {
994                    let needs_storage_live = point.storage_liveness.contains(l)
995                        && !transform.remap.contains(l)
996                        && !transform.always_live_locals.contains(l);
997                    if needs_storage_live {
998                        statements.push(Statement::new(source_info, StatementKind::StorageLive(l)));
999                    }
1000                }
1001
1002                // Move the resume argument to the destination place of the `Yield` terminator
1003                if let Some(resume_arg) = operation.resume_place(point)
1004                    && resume_arg != CTX_ARG.into()
1005                {
1006                    statements.push(Statement::new(
1007                        source_info,
1008                        StatementKind::Assign(Box::new((
1009                            resume_arg,
1010                            Rvalue::Use(Operand::Move(CTX_ARG.into()), WithRetag::Yes),
1011                        ))),
1012                    ));
1013                }
1014
1015                // Then jump to the real target
1016                let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1017                    statements,
1018                    Some(Terminator {
1019                        source_info,
1020                        kind: TerminatorKind::Goto { target },
1021
1022                        attributes: ThinVec::new(),
1023                    }),
1024                    false,
1025                ));
1026
1027                (point.state, block)
1028            })
1029        })
1030        .collect()
1031}
1032
1033impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1034    #[instrument(level = "debug", skip(self, tcx, body), ret)]
1035    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1036        debug!(def_id = ?body.source.def_id());
1037
1038        let Some(old_yield_ty) = body.yield_ty() else {
1039            // This only applies to coroutines
1040            return;
1041        };
1042        tracing::trace!(def_id = ?body.source.def_id());
1043
1044        let old_ret_ty = body.return_ty();
1045
1046        assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1047
1048        if let Some(dumper) = MirDumper::new(tcx, "coroutine_before", body) {
1049            dumper.dump_mir(body);
1050        }
1051
1052        // The first argument is the coroutine type passed by value
1053        let coroutine_ty = body.local_decls.raw[1].ty;
1054        let coroutine_kind = body.coroutine_kind().unwrap();
1055
1056        // Get the discriminant type and args which typeck computed
1057        let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1058            tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1059        };
1060        let discr_ty = args.as_coroutine().discr_ty(tcx);
1061
1062        let new_ret_ty = match coroutine_kind {
1063            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1064                // Compute Poll<return_ty>
1065                let poll_did = tcx.require_lang_item(LangItem::Poll, body.span);
1066                let poll_adt_ref = tcx.adt_def(poll_did);
1067                let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1068                Ty::new_adt(tcx, poll_adt_ref, poll_args)
1069            }
1070            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1071                // Compute Option<yield_ty>
1072                let option_did = tcx.require_lang_item(LangItem::Option, body.span);
1073                let option_adt_ref = tcx.adt_def(option_did);
1074                let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1075                Ty::new_adt(tcx, option_adt_ref, option_args)
1076            }
1077            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1078                // The yield ty is already `Poll<Option<yield_ty>>`
1079                old_yield_ty
1080            }
1081            CoroutineKind::Coroutine(_) => {
1082                // Compute CoroutineState<yield_ty, return_ty>
1083                let state_did = tcx.require_lang_item(LangItem::CoroutineState, body.span);
1084                let state_adt_ref = tcx.adt_def(state_did);
1085                let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1086                Ty::new_adt(tcx, state_adt_ref, state_args)
1087            }
1088        };
1089
1090        // We need to insert clean drop for unresumed state and perform drop elaboration
1091        // (finally in open_drop_for_tuple) before async drop expansion.
1092        // Async drops, produced by this drop elaboration, will be expanded,
1093        // and corresponding futures kept in layout.
1094        let has_async_drops = has_async_drops(body);
1095
1096        if coroutine_kind.is_async_desugaring() {
1097            eliminate_get_context_calls(tcx, body);
1098        }
1099
1100        let always_live_locals = always_storage_live_locals(body);
1101        let movable = coroutine_kind.movability() == hir::Movability::Movable;
1102        let liveness_info =
1103            locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1104
1105        if tcx.sess.opts.unstable_opts.validate_mir {
1106            let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1107                assigned_local: None,
1108                saved_locals: &liveness_info.saved_locals,
1109                storage_conflicts: &liveness_info.storage_conflicts,
1110            };
1111
1112            vis.visit_body(body);
1113        }
1114
1115        // Extract locals which are live across suspension point into `layout`
1116        // `remap` gives a mapping from local indices onto coroutine struct indices
1117        // `storage_liveness` tells us which locals have live storage at suspension points
1118        let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1119
1120        let can_return = can_return(tcx, body, body.typing_env(tcx));
1121
1122        // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1123        // RETURN_PLACE then is a fresh unused local with type ret_ty.
1124        let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1125        tracing::trace!(?new_ret_local);
1126
1127        // Run the transformation which converts Places from Local to coroutine struct
1128        // accesses for locals in `remap`.
1129        // It also rewrites `return x` and `yield y` as writing a new coroutine state and returning
1130        // either `CoroutineState::Complete(x)` and `CoroutineState::Yielded(y)`,
1131        // or `Poll::Ready(x)` and `Poll::Pending` respectively depending on the coroutine kind.
1132        let mut transform = TransformVisitor {
1133            tcx,
1134            coroutine_kind,
1135            remap,
1136            storage_liveness,
1137            always_live_locals,
1138            suspension_points: Vec::new(),
1139            discr_ty,
1140            new_ret_local,
1141            old_ret_ty,
1142            old_yield_ty,
1143            patch: Some(MirPatch::new(body)),
1144        };
1145        transform.visit_body(body);
1146
1147        // Swap the actual `RETURN_PLACE` and the provisional `new_ret_local`.
1148        transform.replace_local(RETURN_PLACE, new_ret_local, body);
1149
1150        // MIR parameters are not explicitly assigned-to when entering the MIR body.
1151        // If we want to save their values inside the coroutine state, we need to do so explicitly.
1152        let source_info = SourceInfo::outermost(body.span);
1153        let args_iter = body.args_iter();
1154        body.basic_blocks.as_mut()[START_BLOCK].statements.splice(
1155            0..0,
1156            args_iter.filter_map(|local| {
1157                let (ty, variant_index, idx) = transform.remap[local]?;
1158                let lhs = transform.make_field(variant_index, idx, ty);
1159                let rhs = Rvalue::Use(Operand::Move(local.into()), WithRetag::Yes);
1160                let assign = StatementKind::Assign(Box::new((lhs, rhs)));
1161                Some(Statement::new(source_info, assign))
1162            }),
1163        );
1164        transform.patch.take().unwrap().apply(body);
1165
1166        // Remove the context argument within generator bodies.
1167        if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1168            body.arg_count = 1;
1169        }
1170
1171        // The original arguments to the function are no longer arguments, mark them as such.
1172        // Otherwise they'll conflict with our new arguments, which although they don't have
1173        // argument_index set, will get emitted as unnamed arguments.
1174        for var in &mut body.var_debug_info {
1175            var.argument_index = None;
1176        }
1177
1178        body.coroutine.as_mut().unwrap().yield_ty = None;
1179        body.coroutine.as_mut().unwrap().resume_ty = None;
1180        body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1181
1182        // Insert `drop(coroutine_struct)` which is used to drop upvars for coroutines in
1183        // the unresumed state.
1184        // This is expanded to a drop ladder in `elaborate_coroutine_drops`.
1185        let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1186
1187        if let Some(dumper) = MirDumper::new(tcx, "coroutine_pre-elab", body) {
1188            dumper.dump_mir(body);
1189        }
1190
1191        // Expand `drop(coroutine_struct)` to a drop ladder which destroys upvars.
1192        // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1193        // However we need to also elaborate the code generated by `insert_clean_drop`.
1194        elaborate_coroutine_drops(tcx, body);
1195
1196        if let Some(dumper) = MirDumper::new(tcx, "coroutine_post-transform", body) {
1197            dumper.dump_mir(body);
1198        }
1199
1200        let can_unwind = can_unwind(tcx, body);
1201
1202        // Create a copy of our MIR and use it to create the drop shim for the coroutine
1203        if has_async_drops {
1204            // If coroutine has async drops, generating async drop shim
1205            let drop_shim =
1206                create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1207            body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1208        } else {
1209            // If coroutine has no async drops, generating sync drop shim
1210            let drop_shim =
1211                create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1212            body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1213
1214            // For coroutine with sync drop, generating async proxy for `future_drop_poll` call
1215            let proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body, coroutine_kind);
1216            body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1217        }
1218
1219        // Create the Coroutine::resume / Future::poll function
1220        create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1221    }
1222
1223    fn policy(&self, _sess: &rustc_session::Session) -> PassPolicy {
1224        // Implements coroutine semantics by lowering the coroutine body to a state machine.
1225        PassPolicy::Required
1226    }
1227}
1228
1229/// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1230/// in the coroutine state machine but whose storage is not marked as conflicting
1231///
1232/// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1233///
1234/// This condition would arise when the assignment is the last use of `_5` but the initial
1235/// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1236/// conflicting. Non-conflicting coroutine saved locals may be stored at the same location within
1237/// the coroutine state machine, which would result in ill-formed MIR: the left-hand and right-hand
1238/// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1239///
1240/// [#73137]: https://github.com/rust-lang/rust/issues/73137
1241struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1242    saved_locals: &'a CoroutineSavedLocals,
1243    storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1244    assigned_local: Option<CoroutineSavedLocal>,
1245}
1246
1247impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1248    fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1249        if place.is_indirect() {
1250            return None;
1251        }
1252
1253        self.saved_locals.get(place.local)
1254    }
1255
1256    fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1257        if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1258            assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1259
1260            self.assigned_local = Some(assigned_local);
1261            f(self);
1262            self.assigned_local = None;
1263        }
1264    }
1265}
1266
1267impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1268    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1269        let Some(lhs) = self.assigned_local else {
1270            // This visitor only invokes `visit_place` for the right-hand side of an assignment
1271            // and only after setting `self.assigned_local`. However, the default impl of
1272            // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1273            // with debuginfo. Ignore them here.
1274            assert!(!context.is_use());
1275            return;
1276        };
1277
1278        let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1279
1280        if !self.storage_conflicts.contains(lhs, rhs) {
1281            bug!(
1282                "Assignment between coroutine saved locals whose storage is not \
1283                    marked as conflicting: {:?}: {:?} = {:?}",
1284                location,
1285                lhs,
1286                rhs,
1287            );
1288        }
1289    }
1290
1291    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1292        match &statement.kind {
1293            StatementKind::Assign((lhs, rhs)) => {
1294                self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1295            }
1296
1297            StatementKind::FakeRead(..)
1298            | StatementKind::SetDiscriminant { .. }
1299            | StatementKind::StorageLive(_)
1300            | StatementKind::StorageDead(_)
1301            | StatementKind::AscribeUserType(..)
1302            | StatementKind::PlaceMention(..)
1303            | StatementKind::Coverage(..)
1304            | StatementKind::Intrinsic(..)
1305            | StatementKind::ConstEvalCounter
1306            | StatementKind::BackwardIncompatibleDropHint { .. }
1307            | StatementKind::Nop => {}
1308        }
1309    }
1310
1311    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1312        // Checking for aliasing in terminators is probably overkill, but until we have actual
1313        // semantics, we should be conservative here.
1314        match &terminator.kind {
1315            TerminatorKind::Call {
1316                func,
1317                args,
1318                destination,
1319                target: Some(_),
1320                unwind: _,
1321                call_source: _,
1322                fn_span: _,
1323            } => {
1324                self.check_assigned_place(*destination, |this| {
1325                    this.visit_operand(func, location);
1326                    for arg in args {
1327                        this.visit_operand(&arg.node, location);
1328                    }
1329                });
1330            }
1331
1332            TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1333                self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1334            }
1335
1336            // FIXME: Does `asm!` have any aliasing requirements?
1337            TerminatorKind::InlineAsm { .. } => {}
1338
1339            TerminatorKind::Call { .. }
1340            | TerminatorKind::Goto { .. }
1341            | TerminatorKind::SwitchInt { .. }
1342            | TerminatorKind::UnwindResume
1343            | TerminatorKind::UnwindTerminate(_)
1344            | TerminatorKind::Return
1345            | TerminatorKind::TailCall { .. }
1346            | TerminatorKind::Unreachable
1347            | TerminatorKind::Drop { .. }
1348            | TerminatorKind::Assert { .. }
1349            | TerminatorKind::CoroutineDrop
1350            | TerminatorKind::FalseEdge { .. }
1351            | TerminatorKind::FalseUnwind { .. } => {}
1352        }
1353    }
1354}