Skip to main content

rustc_mir_transform/
coroutine.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;
55use std::ops;
56
57pub(super) use by_move_body::coroutine_by_move_body_def_id;
58use drop::{
59    cleanup_async_drops, create_coroutine_drop_shim, create_coroutine_drop_shim_async,
60    create_coroutine_drop_shim_proxy_async, elaborate_coroutine_drops, expand_async_drops,
61    has_expandable_async_drops, insert_clean_drop,
62};
63use itertools::izip;
64use rustc_abi::{FieldIdx, VariantIdx};
65use rustc_data_structures::fx::FxHashSet;
66use rustc_errors::pluralize;
67use rustc_hir::lang_items::LangItem;
68use rustc_hir::{self as hir, CoroutineDesugaring, CoroutineKind, find_attr};
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::util::Discr;
74use rustc_middle::ty::{
75    self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, Ty, TyCtxt, TypingMode,
76};
77use rustc_middle::{bug, span_bug};
78use rustc_mir_dataflow::impls::{
79    MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
80    always_storage_live_locals,
81};
82use rustc_mir_dataflow::{
83    Analysis, Results, ResultsCursor, ResultsVisitor, visit_reachable_results,
84};
85use rustc_span::def_id::{DefId, LocalDefId};
86use rustc_span::{DUMMY_SP, Span, dummy_spanned};
87use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
88use rustc_trait_selection::infer::TyCtxtInferExt as _;
89use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt};
90use tracing::{debug, instrument, trace};
91
92use crate::deref_separator::deref_finder;
93use crate::{abort_unwinding_calls, errors, pass_manager as pm, simplify};
94
95pub(super) struct StateTransform;
96
97struct RenameLocalVisitor<'tcx> {
98    from: Local,
99    to: Local,
100    tcx: TyCtxt<'tcx>,
101}
102
103impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
104    fn tcx(&self) -> TyCtxt<'tcx> {
105        self.tcx
106    }
107
108    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
109        if *local == self.from {
110            *local = self.to;
111        } else if *local == self.to {
112            *local = self.from;
113        }
114    }
115
116    fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
117        match terminator.kind {
118            TerminatorKind::Return => {
119                // Do not replace the implicit `_0` access here, as that's not possible. The
120                // transform already handles `return` correctly.
121            }
122            _ => self.super_terminator(terminator, location),
123        }
124    }
125}
126
127struct SelfArgVisitor<'tcx> {
128    tcx: TyCtxt<'tcx>,
129    new_base: Place<'tcx>,
130}
131
132impl<'tcx> SelfArgVisitor<'tcx> {
133    fn new(tcx: TyCtxt<'tcx>, new_base: Place<'tcx>) -> Self {
134        Self { tcx, new_base }
135    }
136}
137
138impl<'tcx> MutVisitor<'tcx> for SelfArgVisitor<'tcx> {
139    fn tcx(&self) -> TyCtxt<'tcx> {
140        self.tcx
141    }
142
143    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
144        assert_ne!(*local, SELF_ARG);
145    }
146
147    fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
148        if place.local == SELF_ARG {
149            replace_base(place, self.new_base, self.tcx);
150        }
151
152        for elem in place.projection.iter() {
153            if let PlaceElem::Index(local) = elem {
154                assert_ne!(local, SELF_ARG);
155            }
156        }
157    }
158}
159
160#[tracing::instrument(level = "trace", skip(tcx))]
161fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
162    place.local = new_base.local;
163
164    let mut new_projection = new_base.projection.to_vec();
165    new_projection.append(&mut place.projection.to_vec());
166
167    place.projection = tcx.mk_place_elems(&new_projection);
168    tracing::trace!(?place);
169}
170
171const SELF_ARG: Local = Local::from_u32(1);
172const CTX_ARG: Local = Local::from_u32(2);
173
174/// A `yield` point in the coroutine.
175struct SuspensionPoint<'tcx> {
176    /// State discriminant used when suspending or resuming at this point.
177    state: usize,
178    /// The block to jump to after resumption.
179    resume: BasicBlock,
180    /// Where to move the resume argument after resumption.
181    resume_arg: Place<'tcx>,
182    /// Which block to jump to if the coroutine is dropped in this state.
183    drop: Option<BasicBlock>,
184    /// Set of locals that have live storage while at this suspension point.
185    storage_liveness: GrowableBitSet<Local>,
186}
187
188struct TransformVisitor<'tcx> {
189    tcx: TyCtxt<'tcx>,
190    coroutine_kind: hir::CoroutineKind,
191
192    // The type of the discriminant in the coroutine struct
193    discr_ty: Ty<'tcx>,
194
195    // Mapping from Local to (type of local, coroutine struct index)
196    remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
197
198    // A map from a suspension point in a block to the locals which have live storage at that point
199    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
200
201    // A list of suspension points, generated during the transform
202    suspension_points: Vec<SuspensionPoint<'tcx>>,
203
204    // The set of locals that have no `StorageLive`/`StorageDead` annotations.
205    always_live_locals: DenseBitSet<Local>,
206
207    // New local we just create to hold the `CoroutineState` value.
208    new_ret_local: Local,
209
210    old_yield_ty: Ty<'tcx>,
211
212    old_ret_ty: Ty<'tcx>,
213}
214
215impl<'tcx> TransformVisitor<'tcx> {
216    fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
217        let block = body.basic_blocks.next_index();
218        let source_info = SourceInfo::outermost(body.span);
219
220        let none_value = match self.coroutine_kind {
221            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
222                span_bug!(body.span, "`Future`s are not fused inherently")
223            }
224            CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
225            // `gen` continues return `None`
226            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
227                let option_def_id = self.tcx.require_lang_item(LangItem::Option, body.span);
228                make_aggregate_adt(
229                    option_def_id,
230                    VariantIdx::ZERO,
231                    self.tcx.mk_args(&[self.old_yield_ty.into()]),
232                    IndexVec::new(),
233                )
234            }
235            // `async gen` continues to return `Poll::Ready(None)`
236            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
237                let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
238                let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
239                let yield_ty = args.type_at(0);
240                Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
241                    span: source_info.span,
242                    const_: Const::Unevaluated(
243                        UnevaluatedConst::new(
244                            self.tcx.require_lang_item(LangItem::AsyncGenFinished, body.span),
245                            self.tcx.mk_args(&[yield_ty.into()]),
246                        ),
247                        self.old_yield_ty,
248                    ),
249                    user_ty: None,
250                })))
251            }
252        };
253
254        let statements = vec![Statement::new(
255            source_info,
256            StatementKind::Assign(Box::new((Place::return_place(), none_value))),
257        )];
258
259        body.basic_blocks_mut().push(BasicBlockData::new_stmts(
260            statements,
261            Some(Terminator { source_info, kind: TerminatorKind::Return }),
262            false,
263        ));
264
265        block
266    }
267
268    // Make a `CoroutineState` or `Poll` variant assignment.
269    //
270    // `core::ops::CoroutineState` only has single element tuple variants,
271    // so we can just write to the downcasted first field and then set the
272    // discriminant to the appropriate variant.
273    #[tracing::instrument(level = "trace", skip(self, statements))]
274    fn make_state(
275        &self,
276        val: Operand<'tcx>,
277        source_info: SourceInfo,
278        is_return: bool,
279        statements: &mut Vec<Statement<'tcx>>,
280    ) {
281        const ZERO: VariantIdx = VariantIdx::ZERO;
282        const ONE: VariantIdx = VariantIdx::from_usize(1);
283        let rvalue = match self.coroutine_kind {
284            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
285                let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, source_info.span);
286                let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
287                let (variant_idx, operands) = if is_return {
288                    (ZERO, indexvec![val]) // Poll::Ready(val)
289                } else {
290                    (ONE, IndexVec::new()) // Poll::Pending
291                };
292                make_aggregate_adt(poll_def_id, variant_idx, args, operands)
293            }
294            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
295                let option_def_id = self.tcx.require_lang_item(LangItem::Option, source_info.span);
296                let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
297                let (variant_idx, operands) = if is_return {
298                    (ZERO, IndexVec::new()) // None
299                } else {
300                    (ONE, indexvec![val]) // Some(val)
301                };
302                make_aggregate_adt(option_def_id, variant_idx, args, operands)
303            }
304            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
305                if is_return {
306                    let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
307                    let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
308                    let yield_ty = args.type_at(0);
309                    Rvalue::Use(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                } else {
324                    Rvalue::Use(val)
325                }
326            }
327            CoroutineKind::Coroutine(_) => {
328                let coroutine_state_def_id =
329                    self.tcx.require_lang_item(LangItem::CoroutineState, source_info.span);
330                let args = self.tcx.mk_args(&[self.old_yield_ty.into(), self.old_ret_ty.into()]);
331                let variant_idx = if is_return {
332                    ONE // CoroutineState::Complete(val)
333                } else {
334                    ZERO // CoroutineState::Yielded(val)
335                };
336                make_aggregate_adt(coroutine_state_def_id, variant_idx, args, indexvec![val])
337            }
338        };
339
340        // Assign to `new_ret_local`, which will be replaced by `RETURN_PLACE` later.
341        statements.push(Statement::new(
342            source_info,
343            StatementKind::Assign(Box::new((self.new_ret_local.into(), rvalue))),
344        ));
345    }
346
347    // Create a Place referencing a coroutine struct field
348    #[tracing::instrument(level = "trace", skip(self), ret)]
349    fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
350        let self_place = Place::from(SELF_ARG);
351        let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
352        let mut projection = base.projection.to_vec();
353        projection.push(ProjectionElem::Field(idx, ty));
354
355        Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
356    }
357
358    // Create a statement which changes the discriminant
359    #[tracing::instrument(level = "trace", skip(self))]
360    fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
361        let self_place = Place::from(SELF_ARG);
362        Statement::new(
363            source_info,
364            StatementKind::SetDiscriminant {
365                place: Box::new(self_place),
366                variant_index: state_disc,
367            },
368        )
369    }
370
371    // Create a statement which reads the discriminant into a temporary
372    #[tracing::instrument(level = "trace", skip(self, body))]
373    fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
374        let temp_decl = LocalDecl::new(self.discr_ty, body.span);
375        let local_decls_len = body.local_decls.push(temp_decl);
376        let temp = Place::from(local_decls_len);
377
378        let self_place = Place::from(SELF_ARG);
379        let assign = Statement::new(
380            SourceInfo::outermost(body.span),
381            StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
382        );
383        (assign, temp)
384    }
385
386    /// Swaps all references of `old_local` and `new_local`.
387    #[tracing::instrument(level = "trace", skip(self, body))]
388    fn replace_local(&mut self, old_local: Local, new_local: Local, body: &mut Body<'tcx>) {
389        body.local_decls.swap(old_local, new_local);
390
391        let mut visitor = RenameLocalVisitor { from: old_local, to: new_local, tcx: self.tcx };
392        visitor.visit_body(body);
393        for suspension in &mut self.suspension_points {
394            let ctxt = PlaceContext::MutatingUse(MutatingUseContext::Yield);
395            let location = Location { block: START_BLOCK, statement_index: 0 };
396            visitor.visit_place(&mut suspension.resume_arg, ctxt, location);
397        }
398    }
399}
400
401impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
402    fn tcx(&self) -> TyCtxt<'tcx> {
403        self.tcx
404    }
405
406    #[tracing::instrument(level = "trace", skip(self), ret)]
407    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _location: Location) {
408        assert!(!self.remap.contains(*local));
409    }
410
411    #[tracing::instrument(level = "trace", skip(self), ret)]
412    fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _location: Location) {
413        // Replace an Local in the remap with a coroutine struct access
414        if let Some(&Some((ty, variant_index, idx))) = self.remap.get(place.local) {
415            replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
416        }
417    }
418
419    #[tracing::instrument(level = "trace", skip(self, stmt), ret)]
420    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, location: Location) {
421        // Remove StorageLive and StorageDead statements for remapped locals
422        if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
423            && self.remap.contains(l)
424        {
425            stmt.make_nop(true);
426        }
427        self.super_statement(stmt, location);
428    }
429
430    #[tracing::instrument(level = "trace", skip(self, term), ret)]
431    fn visit_terminator(&mut self, term: &mut Terminator<'tcx>, location: Location) {
432        if let TerminatorKind::Return = term.kind {
433            // `visit_basic_block_data` introduces `Return` terminators which read `RETURN_PLACE`.
434            // But this `RETURN_PLACE` is already remapped, so we should not touch it again.
435            return;
436        }
437        self.super_terminator(term, location);
438    }
439
440    #[tracing::instrument(level = "trace", skip(self, data), ret)]
441    fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
442        match data.terminator().kind {
443            TerminatorKind::Return => {
444                let source_info = data.terminator().source_info;
445                // We must assign the value first in case it gets declared dead below
446                self.make_state(
447                    Operand::Move(Place::return_place()),
448                    source_info,
449                    true,
450                    &mut data.statements,
451                );
452                // Return state.
453                let state = VariantIdx::new(CoroutineArgs::RETURNED);
454                data.statements.push(self.set_discr(state, source_info));
455                data.terminator_mut().kind = TerminatorKind::Return;
456            }
457            TerminatorKind::Yield { ref value, resume, mut resume_arg, drop } => {
458                let source_info = data.terminator().source_info;
459                // We must assign the value first in case it gets declared dead below
460                self.make_state(value.clone(), source_info, false, &mut data.statements);
461                // Yield state.
462                let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
463
464                // The resume arg target location might itself be remapped if its base local is
465                // live across a yield.
466                if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
467                    replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
468                }
469
470                let storage_liveness: GrowableBitSet<Local> =
471                    self.storage_liveness[block].clone().unwrap().into();
472
473                for i in 0..self.always_live_locals.domain_size() {
474                    let l = Local::new(i);
475                    let needs_storage_dead = storage_liveness.contains(l)
476                        && !self.remap.contains(l)
477                        && !self.always_live_locals.contains(l);
478                    if needs_storage_dead {
479                        data.statements
480                            .push(Statement::new(source_info, StatementKind::StorageDead(l)));
481                    }
482                }
483
484                self.suspension_points.push(SuspensionPoint {
485                    state,
486                    resume,
487                    resume_arg,
488                    drop,
489                    storage_liveness,
490                });
491
492                let state = VariantIdx::new(state);
493                data.statements.push(self.set_discr(state, source_info));
494                data.terminator_mut().kind = TerminatorKind::Return;
495            }
496            _ => {}
497        }
498
499        self.super_basic_block_data(block, data);
500    }
501}
502
503fn make_aggregate_adt<'tcx>(
504    def_id: DefId,
505    variant_idx: VariantIdx,
506    args: GenericArgsRef<'tcx>,
507    operands: IndexVec<FieldIdx, Operand<'tcx>>,
508) -> Rvalue<'tcx> {
509    Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
510}
511
512#[tracing::instrument(level = "trace", skip(tcx, body))]
513fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
514    let coroutine_ty = body.local_decls[SELF_ARG].ty;
515
516    let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
517
518    // Replace the by value coroutine argument
519    body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
520
521    // Add a deref to accesses of the coroutine state
522    SelfArgVisitor::new(tcx, tcx.mk_place_deref(SELF_ARG.into())).visit_body(body);
523}
524
525#[tracing::instrument(level = "trace", skip(tcx, body))]
526fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
527    let coroutine_ty = body.local_decls[SELF_ARG].ty;
528
529    let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
530
531    let pin_did = tcx.require_lang_item(LangItem::Pin, body.span);
532    let pin_adt_ref = tcx.adt_def(pin_did);
533    let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
534    let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
535
536    // Replace the by ref coroutine argument
537    body.local_decls[SELF_ARG].ty = pin_ref_coroutine_ty;
538
539    let unpinned_local = body.local_decls.push(LocalDecl::new(ref_coroutine_ty, body.span));
540
541    // Add the Pin field access to accesses of the coroutine state
542    SelfArgVisitor::new(tcx, tcx.mk_place_deref(unpinned_local.into())).visit_body(body);
543
544    let source_info = SourceInfo::outermost(body.span);
545    let pin_field = tcx.mk_place_field(SELF_ARG.into(), FieldIdx::ZERO, ref_coroutine_ty);
546
547    let statements = &mut body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements;
548    // Miri requires retags to be the very first thing in the body.
549    // We insert this assignment just after.
550    let insert_point = statements
551        .iter()
552        .position(|stmt| !matches!(stmt.kind, StatementKind::Retag(..)))
553        .unwrap_or(statements.len());
554    statements.insert(
555        insert_point,
556        Statement::new(
557            source_info,
558            StatementKind::Assign(Box::new((
559                unpinned_local.into(),
560                Rvalue::Use(Operand::Copy(pin_field)),
561            ))),
562        ),
563    );
564}
565
566/// Transforms the `body` of the coroutine applying the following transforms:
567///
568/// - Eliminates all the `get_context` calls that async lowering created.
569/// - Replace all `Local` `ResumeTy` types with `&mut Context<'_>` (`context_mut_ref`).
570///
571/// The `Local`s that have their types replaced are:
572/// - The `resume` argument itself.
573/// - The argument to `get_context`.
574/// - The yielded value of a `yield`.
575///
576/// The `ResumeTy` hides a `&mut Context<'_>` behind an unsafe raw pointer, and the
577/// `get_context` function is being used to convert that back to a `&mut Context<'_>`.
578///
579/// Ideally the async lowering would not use the `ResumeTy`/`get_context` indirection,
580/// but rather directly use `&mut Context<'_>`, however that would currently
581/// lead to higher-kinded lifetime errors.
582/// See <https://github.com/rust-lang/rust/issues/105501>.
583///
584/// The async lowering step and the type / lifetime inference / checking are
585/// still using the `ResumeTy` indirection for the time being, and that indirection
586/// is removed here. After this transform, the coroutine body only knows about `&mut Context<'_>`.
587#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
588fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> Ty<'tcx> {
589    let context_mut_ref = Ty::new_task_context(tcx);
590
591    // replace the type of the `resume` argument
592    replace_resume_ty_local(tcx, body, CTX_ARG, context_mut_ref);
593
594    let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, body.span);
595
596    for bb in body.basic_blocks.indices() {
597        let bb_data = &body[bb];
598        if bb_data.is_cleanup {
599            continue;
600        }
601
602        match &bb_data.terminator().kind {
603            TerminatorKind::Call { func, .. } => {
604                let func_ty = func.ty(body, tcx);
605                if let ty::FnDef(def_id, _) = *func_ty.kind()
606                    && def_id == get_context_def_id
607                {
608                    let local = eliminate_get_context_call(&mut body[bb]);
609                    replace_resume_ty_local(tcx, body, local, context_mut_ref);
610                }
611            }
612            TerminatorKind::Yield { resume_arg, .. } => {
613                replace_resume_ty_local(tcx, body, resume_arg.local, context_mut_ref);
614            }
615            _ => {}
616        }
617    }
618    context_mut_ref
619}
620
621fn eliminate_get_context_call<'tcx>(bb_data: &mut BasicBlockData<'tcx>) -> Local {
622    let terminator = bb_data.terminator.take().unwrap();
623    let TerminatorKind::Call { args, destination, target, .. } = terminator.kind else {
624        bug!();
625    };
626    let [arg] = *Box::try_from(args).unwrap();
627    let local = arg.node.place().unwrap().local;
628
629    let arg = Rvalue::Use(arg.node);
630    let assign =
631        Statement::new(terminator.source_info, StatementKind::Assign(Box::new((destination, arg))));
632    bb_data.statements.push(assign);
633    bb_data.terminator = Some(Terminator {
634        source_info: terminator.source_info,
635        kind: TerminatorKind::Goto { target: target.unwrap() },
636    });
637    local
638}
639
640#[cfg_attr(not(debug_assertions), allow(unused))]
641#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
642fn replace_resume_ty_local<'tcx>(
643    tcx: TyCtxt<'tcx>,
644    body: &mut Body<'tcx>,
645    local: Local,
646    context_mut_ref: Ty<'tcx>,
647) {
648    let local_ty = std::mem::replace(&mut body.local_decls[local].ty, context_mut_ref);
649    // We have to replace the `ResumeTy` that is used for type and borrow checking
650    // with `&mut Context<'_>` in MIR.
651    #[cfg(debug_assertions)]
652    {
653        if let ty::Adt(resume_ty_adt, _) = local_ty.kind() {
654            let expected_adt = tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, body.span));
655            assert_eq!(*resume_ty_adt, expected_adt);
656        } else {
657            panic!("expected `ResumeTy`, found `{:?}`", local_ty);
658        };
659    }
660}
661
662/// Transforms the `body` of the coroutine applying the following transform:
663///
664/// - Remove the `resume` argument.
665///
666/// Ideally the async lowering would not add the `resume` argument.
667///
668/// The async lowering step and the type / lifetime inference / checking are
669/// still using the `resume` argument for the time being. After this transform,
670/// the coroutine body doesn't have the `resume` argument.
671fn transform_gen_context<'tcx>(body: &mut Body<'tcx>) {
672    // This leaves the local representing the `resume` argument in place,
673    // but turns it into a regular local variable. This is cheaper than
674    // adjusting all local references in the body after removing it.
675    body.arg_count = 1;
676}
677
678struct LivenessInfo {
679    /// Which locals are live across any suspension point.
680    saved_locals: CoroutineSavedLocals,
681
682    /// The set of saved locals live at each suspension point.
683    live_locals_at_suspension_points: Vec<DenseBitSet<CoroutineSavedLocal>>,
684
685    /// Parallel vec to the above with SourceInfo for each yield terminator.
686    source_info_at_suspension_points: Vec<SourceInfo>,
687
688    /// For every saved local, the set of other saved locals that are
689    /// storage-live at the same time as this local. We cannot overlap locals in
690    /// the layout which have conflicting storage.
691    storage_conflicts: BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
692
693    /// For every suspending block, the locals which are storage-live across
694    /// that suspension point.
695    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
696}
697
698/// Computes which locals have to be stored in the state-machine for the
699/// given coroutine.
700///
701/// The basic idea is as follows:
702/// - a local is live until we encounter a `StorageDead` statement. In
703///   case none exist, the local is considered to be always live.
704/// - a local has to be stored if it is either directly used after the
705///   the suspend point, or if it is live and has been previously borrowed.
706#[tracing::instrument(level = "trace", skip(tcx, body))]
707fn locals_live_across_suspend_points<'tcx>(
708    tcx: TyCtxt<'tcx>,
709    body: &Body<'tcx>,
710    always_live_locals: &DenseBitSet<Local>,
711    movable: bool,
712) -> LivenessInfo {
713    // Calculate when MIR locals have live storage. This gives us an upper bound of their
714    // lifetimes.
715    let mut storage_live = MaybeStorageLive::new(std::borrow::Cow::Borrowed(always_live_locals))
716        .iterate_to_fixpoint(tcx, body, None)
717        .into_results_cursor(body);
718
719    // Calculate the MIR locals that have been previously borrowed (even if they are still active).
720    let borrowed_locals = MaybeBorrowedLocals.iterate_to_fixpoint(tcx, body, Some("coroutine"));
721    let borrowed_locals_cursor1 = ResultsCursor::new_borrowing(body, &borrowed_locals);
722    let mut borrowed_locals_cursor2 = ResultsCursor::new_borrowing(body, &borrowed_locals);
723
724    // Calculate the MIR locals that we need to keep storage around for.
725    let requires_storage =
726        MaybeRequiresStorage::new(borrowed_locals_cursor1).iterate_to_fixpoint(tcx, body, None);
727    let mut requires_storage_cursor = ResultsCursor::new_borrowing(body, &requires_storage);
728
729    // Calculate the liveness of MIR locals ignoring borrows.
730    let mut liveness =
731        MaybeLiveLocals.iterate_to_fixpoint(tcx, body, Some("coroutine")).into_results_cursor(body);
732
733    let mut storage_liveness_map = IndexVec::from_elem(None, &body.basic_blocks);
734    let mut live_locals_at_suspension_points = Vec::new();
735    let mut source_info_at_suspension_points = Vec::new();
736    let mut live_locals_at_any_suspension_point = DenseBitSet::new_empty(body.local_decls.len());
737
738    for (block, data) in body.basic_blocks.iter_enumerated() {
739        let TerminatorKind::Yield { .. } = data.terminator().kind else { continue };
740
741        let loc = Location { block, statement_index: data.statements.len() };
742
743        liveness.seek_to_block_end(block);
744        let mut live_locals = liveness.get().clone();
745
746        if !movable {
747            // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
748            // This is correct for movable coroutines since borrows cannot live across
749            // suspension points. However for immovable coroutines we need to account for
750            // borrows, so we conservatively assume that all borrowed locals are live until
751            // we find a StorageDead statement referencing the locals.
752            // To do this we just union our `liveness` result with `borrowed_locals`, which
753            // contains all the locals which has been borrowed before this suspension point.
754            // If a borrow is converted to a raw reference, we must also assume that it lives
755            // forever. Note that the final liveness is still bounded by the storage liveness
756            // of the local, which happens using the `intersect` operation below.
757            borrowed_locals_cursor2.seek_before_primary_effect(loc);
758            live_locals.union(borrowed_locals_cursor2.get());
759        }
760
761        // Store the storage liveness for later use so we can restore the state
762        // after a suspension point
763        storage_live.seek_before_primary_effect(loc);
764        storage_liveness_map[block] = Some(storage_live.get().clone());
765
766        // Locals live are live at this point only if they are used across
767        // suspension points (the `liveness` variable)
768        // and their storage is required (the `storage_required` variable)
769        requires_storage_cursor.seek_before_primary_effect(loc);
770        live_locals.intersect(requires_storage_cursor.get());
771
772        // The coroutine argument is ignored.
773        live_locals.remove(SELF_ARG);
774
775        debug!(?loc, ?live_locals);
776
777        // Add the locals live at this suspension point to the set of locals which live across
778        // any suspension points
779        live_locals_at_any_suspension_point.union(&live_locals);
780
781        live_locals_at_suspension_points.push(live_locals);
782        source_info_at_suspension_points.push(data.terminator().source_info);
783    }
784
785    debug!(?live_locals_at_any_suspension_point);
786    let saved_locals = CoroutineSavedLocals(live_locals_at_any_suspension_point);
787
788    // Renumber our liveness_map bitsets to include only the locals we are
789    // saving.
790    let live_locals_at_suspension_points = live_locals_at_suspension_points
791        .iter()
792        .map(|live_here| saved_locals.renumber_bitset(live_here))
793        .collect();
794
795    let storage_conflicts = compute_storage_conflicts(
796        body,
797        &saved_locals,
798        always_live_locals.clone(),
799        &requires_storage,
800    );
801
802    LivenessInfo {
803        saved_locals,
804        live_locals_at_suspension_points,
805        source_info_at_suspension_points,
806        storage_conflicts,
807        storage_liveness: storage_liveness_map,
808    }
809}
810
811/// The set of `Local`s that must be saved across yield points.
812///
813/// `CoroutineSavedLocal` is indexed in terms of the elements in this set;
814/// i.e. `CoroutineSavedLocal::new(1)` corresponds to the second local
815/// included in this set.
816struct CoroutineSavedLocals(DenseBitSet<Local>);
817
818impl CoroutineSavedLocals {
819    /// Returns an iterator over each `CoroutineSavedLocal` along with the `Local` it corresponds
820    /// to.
821    fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (CoroutineSavedLocal, Local)> {
822        self.iter().enumerate().map(|(i, l)| (CoroutineSavedLocal::from(i), l))
823    }
824
825    /// Transforms a `DenseBitSet<Local>` that contains only locals saved across yield points to the
826    /// equivalent `DenseBitSet<CoroutineSavedLocal>`.
827    fn renumber_bitset(&self, input: &DenseBitSet<Local>) -> DenseBitSet<CoroutineSavedLocal> {
828        assert!(self.superset(input), "{:?} not a superset of {:?}", self.0, input);
829        let mut out = DenseBitSet::new_empty(self.count());
830        for (saved_local, local) in self.iter_enumerated() {
831            if input.contains(local) {
832                out.insert(saved_local);
833            }
834        }
835        out
836    }
837
838    fn get(&self, local: Local) -> Option<CoroutineSavedLocal> {
839        if !self.contains(local) {
840            return None;
841        }
842
843        let idx = self.iter().take_while(|&l| l < local).count();
844        Some(CoroutineSavedLocal::new(idx))
845    }
846}
847
848impl ops::Deref for CoroutineSavedLocals {
849    type Target = DenseBitSet<Local>;
850
851    fn deref(&self) -> &Self::Target {
852        &self.0
853    }
854}
855
856/// For every saved local, looks for which locals are StorageLive at the same
857/// time. Generates a bitset for every local of all the other locals that may be
858/// StorageLive simultaneously with that local. This is used in the layout
859/// computation; see `CoroutineLayout` for more.
860fn compute_storage_conflicts<'mir, 'tcx>(
861    body: &'mir Body<'tcx>,
862    saved_locals: &'mir CoroutineSavedLocals,
863    always_live_locals: DenseBitSet<Local>,
864    results: &Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
865) -> BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal> {
866    assert_eq!(body.local_decls.len(), saved_locals.domain_size());
867
868    debug!("compute_storage_conflicts({:?})", body.span);
869    debug!("always_live = {:?}", always_live_locals);
870
871    // Locals that are always live or ones that need to be stored across
872    // suspension points are not eligible for overlap.
873    let mut ineligible_locals = always_live_locals;
874    ineligible_locals.intersect(&**saved_locals);
875
876    // Compute the storage conflicts for all eligible locals.
877    let mut visitor = StorageConflictVisitor {
878        body,
879        saved_locals,
880        local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
881        eligible_storage_live: DenseBitSet::new_empty(body.local_decls.len()),
882    };
883
884    visit_reachable_results(body, results, &mut visitor);
885
886    let local_conflicts = visitor.local_conflicts;
887
888    // Compress the matrix using only stored locals (Local -> CoroutineSavedLocal).
889    //
890    // NOTE: Today we store a full conflict bitset for every local. Technically
891    // this is twice as many bits as we need, since the relation is symmetric.
892    // However, in practice these bitsets are not usually large. The layout code
893    // also needs to keep track of how many conflicts each local has, so it's
894    // simpler to keep it this way for now.
895    let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
896    for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
897        if ineligible_locals.contains(local_a) {
898            // Conflicts with everything.
899            storage_conflicts.insert_all_into_row(saved_local_a);
900        } else {
901            // Keep overlap information only for stored locals.
902            for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
903                if local_conflicts.contains(local_a, local_b) {
904                    storage_conflicts.insert(saved_local_a, saved_local_b);
905                }
906            }
907        }
908    }
909    storage_conflicts
910}
911
912struct StorageConflictVisitor<'a, 'tcx> {
913    body: &'a Body<'tcx>,
914    saved_locals: &'a CoroutineSavedLocals,
915    // FIXME(tmandry): Consider using sparse bitsets here once we have good
916    // benchmarks for coroutines.
917    local_conflicts: BitMatrix<Local, Local>,
918    // We keep this bitset as a buffer to avoid reallocating memory.
919    eligible_storage_live: DenseBitSet<Local>,
920}
921
922impl<'a, 'tcx> ResultsVisitor<'tcx, MaybeRequiresStorage<'a, 'tcx>>
923    for StorageConflictVisitor<'a, 'tcx>
924{
925    fn visit_after_early_statement_effect(
926        &mut self,
927        _analysis: &MaybeRequiresStorage<'a, 'tcx>,
928        state: &DenseBitSet<Local>,
929        _statement: &Statement<'tcx>,
930        loc: Location,
931    ) {
932        self.apply_state(state, loc);
933    }
934
935    fn visit_after_early_terminator_effect(
936        &mut self,
937        _analysis: &MaybeRequiresStorage<'a, 'tcx>,
938        state: &DenseBitSet<Local>,
939        _terminator: &Terminator<'tcx>,
940        loc: Location,
941    ) {
942        self.apply_state(state, loc);
943    }
944}
945
946impl StorageConflictVisitor<'_, '_> {
947    fn apply_state(&mut self, state: &DenseBitSet<Local>, loc: Location) {
948        // Ignore unreachable blocks.
949        if let TerminatorKind::Unreachable = self.body.basic_blocks[loc.block].terminator().kind {
950            return;
951        }
952
953        self.eligible_storage_live.clone_from(state);
954        self.eligible_storage_live.intersect(&**self.saved_locals);
955
956        for local in self.eligible_storage_live.iter() {
957            self.local_conflicts.union_row_with(&self.eligible_storage_live, local);
958        }
959
960        if self.eligible_storage_live.count() > 1 {
961            trace!("at {:?}, eligible_storage_live={:?}", loc, self.eligible_storage_live);
962        }
963    }
964}
965
966#[tracing::instrument(level = "trace", skip(liveness, body))]
967fn compute_layout<'tcx>(
968    liveness: LivenessInfo,
969    body: &Body<'tcx>,
970) -> (
971    IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
972    CoroutineLayout<'tcx>,
973    IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
974) {
975    let LivenessInfo {
976        saved_locals,
977        live_locals_at_suspension_points,
978        source_info_at_suspension_points,
979        storage_conflicts,
980        storage_liveness,
981    } = liveness;
982
983    // Gather live local types and their indices.
984    let mut locals = IndexVec::<CoroutineSavedLocal, _>::with_capacity(saved_locals.domain_size());
985    let mut tys = IndexVec::<CoroutineSavedLocal, _>::with_capacity(saved_locals.domain_size());
986    for (saved_local, local) in saved_locals.iter_enumerated() {
987        debug!("coroutine saved local {:?} => {:?}", saved_local, local);
988
989        locals.push(local);
990        let decl = &body.local_decls[local];
991        debug!(?decl);
992
993        // Do not `unwrap_crate_local` here, as post-borrowck cleanup may have already cleared
994        // the information. This is alright, since `ignore_for_traits` is only relevant when
995        // this code runs on pre-cleanup MIR, and `ignore_for_traits = false` is the safer
996        // default.
997        let ignore_for_traits = match decl.local_info {
998            // Do not include raw pointers created from accessing `static` items, as those could
999            // well be re-created by another access to the same static.
1000            ClearCrossCrate::Set(box LocalInfo::StaticRef { is_thread_local, .. }) => {
1001                !is_thread_local
1002            }
1003            // Fake borrows are only read by fake reads, so do not have any reality in
1004            // post-analysis MIR.
1005            ClearCrossCrate::Set(box LocalInfo::FakeBorrow) => true,
1006            _ => false,
1007        };
1008        let decl =
1009            CoroutineSavedTy { ty: decl.ty, source_info: decl.source_info, ignore_for_traits };
1010        debug!(?decl);
1011
1012        tys.push(decl);
1013    }
1014
1015    // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
1016    // In debuginfo, these will correspond to the beginning (UNRESUMED) or end
1017    // (RETURNED, POISONED) of the function.
1018    let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
1019    let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = IndexVec::with_capacity(
1020        CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
1021    );
1022    variant_source_info.extend([
1023        SourceInfo::outermost(body_span.shrink_to_lo()),
1024        SourceInfo::outermost(body_span.shrink_to_hi()),
1025        SourceInfo::outermost(body_span.shrink_to_hi()),
1026    ]);
1027
1028    // Build the coroutine variant field list.
1029    // Create a map from local indices to coroutine struct indices.
1030    let mut variant_fields: IndexVec<VariantIdx, _> = IndexVec::from_elem_n(
1031        IndexVec::new(),
1032        CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
1033    );
1034    let mut remap = IndexVec::from_elem_n(None, saved_locals.domain_size());
1035    for (live_locals, &source_info_at_suspension_point, (variant_index, fields)) in izip!(
1036        &live_locals_at_suspension_points,
1037        &source_info_at_suspension_points,
1038        variant_fields.iter_enumerated_mut().skip(CoroutineArgs::RESERVED_VARIANTS)
1039    ) {
1040        *fields = live_locals.iter().collect();
1041        for (idx, &saved_local) in fields.iter_enumerated() {
1042            // Note that if a field is included in multiple variants, we will
1043            // just use the first one here. That's fine; fields do not move
1044            // around inside coroutines, so it doesn't matter which variant
1045            // index we access them by.
1046            remap[locals[saved_local]] = Some((tys[saved_local].ty, variant_index, idx));
1047        }
1048        variant_source_info.push(source_info_at_suspension_point);
1049    }
1050    debug!(?variant_fields);
1051    debug!(?storage_conflicts);
1052
1053    let mut field_names = IndexVec::from_elem(None, &tys);
1054    for var in &body.var_debug_info {
1055        let VarDebugInfoContents::Place(place) = &var.value else { continue };
1056        let Some(local) = place.as_local() else { continue };
1057        let Some(&Some((_, variant, field))) = remap.get(local) else {
1058            continue;
1059        };
1060
1061        let saved_local = variant_fields[variant][field];
1062        field_names.get_or_insert_with(saved_local, || var.name);
1063    }
1064
1065    let layout = CoroutineLayout {
1066        field_tys: tys,
1067        field_names,
1068        variant_fields,
1069        variant_source_info,
1070        storage_conflicts,
1071    };
1072    debug!(?remap);
1073    debug!(?layout);
1074    debug!(?storage_liveness);
1075
1076    (remap, layout, storage_liveness)
1077}
1078
1079/// Replaces the entry point of `body` with a block that switches on the coroutine discriminant and
1080/// dispatches to blocks according to `cases`.
1081///
1082/// After this function, the former entry point of the function will be bb1.
1083fn insert_switch<'tcx>(
1084    body: &mut Body<'tcx>,
1085    cases: Vec<(usize, BasicBlock)>,
1086    transform: &TransformVisitor<'tcx>,
1087    default_block: BasicBlock,
1088) {
1089    let (assign, discr) = transform.get_discr(body);
1090    let switch_targets =
1091        SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
1092    let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
1093
1094    let source_info = SourceInfo::outermost(body.span);
1095    body.basic_blocks_mut().raw.insert(
1096        0,
1097        BasicBlockData::new_stmts(
1098            vec![assign],
1099            Some(Terminator { source_info, kind: switch }),
1100            false,
1101        ),
1102    );
1103
1104    for b in body.basic_blocks_mut().iter_mut() {
1105        b.terminator_mut().successors_mut(|target| *target += 1);
1106    }
1107}
1108
1109fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
1110    let source_info = SourceInfo::outermost(body.span);
1111    body.basic_blocks_mut().push(BasicBlockData::new(Some(Terminator { source_info, kind }), false))
1112}
1113
1114fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
1115    // Poll::Ready(())
1116    let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
1117    let args = tcx.mk_args(&[tcx.types.unit.into()]);
1118    let val = Operand::Constant(Box::new(ConstOperand {
1119        span: source_info.span,
1120        user_ty: None,
1121        const_: Const::zero_sized(tcx.types.unit),
1122    }));
1123    let ready_val = Rvalue::Aggregate(
1124        Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
1125        indexvec![val],
1126    );
1127    Statement::new(source_info, StatementKind::Assign(Box::new((Place::return_place(), ready_val))))
1128}
1129
1130fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
1131    let source_info = SourceInfo::outermost(body.span);
1132    body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1133        [return_poll_ready_assign(tcx, source_info)].to_vec(),
1134        Some(Terminator { source_info, kind: TerminatorKind::Return }),
1135        false,
1136    ))
1137}
1138
1139fn insert_panic_block<'tcx>(
1140    tcx: TyCtxt<'tcx>,
1141    body: &mut Body<'tcx>,
1142    message: AssertMessage<'tcx>,
1143) -> BasicBlock {
1144    let assert_block = body.basic_blocks.next_index();
1145    let kind = TerminatorKind::Assert {
1146        cond: Operand::Constant(Box::new(ConstOperand {
1147            span: body.span,
1148            user_ty: None,
1149            const_: Const::from_bool(tcx, false),
1150        })),
1151        expected: true,
1152        msg: Box::new(message),
1153        target: assert_block,
1154        unwind: UnwindAction::Continue,
1155    };
1156
1157    insert_term_block(body, kind)
1158}
1159
1160fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1161    // Returning from a function with an uninhabited return type is undefined behavior.
1162    if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
1163        return false;
1164    }
1165
1166    // If there's a return terminator the function may return.
1167    body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
1168    // Otherwise the function can't return.
1169}
1170
1171fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1172    // Nothing can unwind when landing pads are off.
1173    if !tcx.sess.panic_strategy().unwinds() {
1174        return false;
1175    }
1176
1177    // Unwinds can only start at certain terminators.
1178    for block in body.basic_blocks.iter() {
1179        match block.terminator().kind {
1180            // These never unwind.
1181            TerminatorKind::Goto { .. }
1182            | TerminatorKind::SwitchInt { .. }
1183            | TerminatorKind::UnwindTerminate(_)
1184            | TerminatorKind::Return
1185            | TerminatorKind::Unreachable
1186            | TerminatorKind::CoroutineDrop
1187            | TerminatorKind::FalseEdge { .. }
1188            | TerminatorKind::FalseUnwind { .. } => {}
1189
1190            // Resume will *continue* unwinding, but if there's no other unwinding terminator it
1191            // will never be reached.
1192            TerminatorKind::UnwindResume => {}
1193
1194            TerminatorKind::Yield { .. } => {
1195                unreachable!("`can_unwind` called before coroutine transform")
1196            }
1197
1198            // These may unwind.
1199            TerminatorKind::Drop { .. }
1200            | TerminatorKind::Call { .. }
1201            | TerminatorKind::InlineAsm { .. }
1202            | TerminatorKind::Assert { .. } => return true,
1203
1204            TerminatorKind::TailCall { .. } => {
1205                unreachable!("tail calls can't be present in generators")
1206            }
1207        }
1208    }
1209
1210    // If we didn't find an unwinding terminator, the function cannot unwind.
1211    false
1212}
1213
1214// Poison the coroutine when it unwinds
1215fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
1216    transform: &TransformVisitor<'tcx>,
1217    body: &mut Body<'tcx>,
1218) {
1219    let source_info = SourceInfo::outermost(body.span);
1220    let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1221        vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)],
1222        Some(Terminator { source_info, kind: TerminatorKind::UnwindResume }),
1223        true,
1224    ));
1225
1226    for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1227        let source_info = block.terminator().source_info;
1228
1229        if let TerminatorKind::UnwindResume = block.terminator().kind {
1230            // An existing `Resume` terminator is redirected to jump to our dedicated
1231            // "poisoning block" above.
1232            if idx != poison_block {
1233                *block.terminator_mut() =
1234                    Terminator { source_info, kind: TerminatorKind::Goto { target: poison_block } };
1235            }
1236        } else if !block.is_cleanup
1237            // Any terminators that *can* unwind but don't have an unwind target set are also
1238            // pointed at our poisoning block (unless they're part of the cleanup path).
1239            && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
1240        {
1241            *unwind = UnwindAction::Cleanup(poison_block);
1242        }
1243    }
1244}
1245
1246#[tracing::instrument(level = "trace", skip(tcx, transform, body))]
1247fn create_coroutine_resume_function<'tcx>(
1248    tcx: TyCtxt<'tcx>,
1249    transform: TransformVisitor<'tcx>,
1250    body: &mut Body<'tcx>,
1251    can_return: bool,
1252    can_unwind: bool,
1253) {
1254    // Poison the coroutine when it unwinds
1255    if can_unwind {
1256        generate_poison_block_and_redirect_unwinds_there(&transform, body);
1257    }
1258
1259    let mut cases = create_cases(body, &transform, Operation::Resume);
1260
1261    use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1262
1263    // Jump to the entry point on the unresumed
1264    cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
1265
1266    // Panic when resumed on the returned or poisoned state
1267    if can_unwind {
1268        cases.insert(
1269            1,
1270            (
1271                CoroutineArgs::POISONED,
1272                insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
1273            ),
1274        );
1275    }
1276
1277    if can_return {
1278        let block = match transform.coroutine_kind {
1279            CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
1280            | CoroutineKind::Coroutine(_) => {
1281                // For `async_drop_in_place<T>::{closure}` we just keep return Poll::Ready,
1282                // because async drop of such coroutine keeps polling original coroutine
1283                if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
1284                    insert_poll_ready_block(tcx, body)
1285                } else {
1286                    insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
1287                }
1288            }
1289            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
1290            | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1291                transform.insert_none_ret_block(body)
1292            }
1293        };
1294        cases.insert(1, (CoroutineArgs::RETURNED, block));
1295    }
1296
1297    let default_block = insert_term_block(body, TerminatorKind::Unreachable);
1298    insert_switch(body, cases, &transform, default_block);
1299
1300    match transform.coroutine_kind {
1301        CoroutineKind::Coroutine(_)
1302        | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
1303        {
1304            make_coroutine_state_argument_pinned(tcx, body);
1305        }
1306        // Iterator::next doesn't accept a pinned argument,
1307        // unlike for all other coroutine kinds.
1308        CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1309            make_coroutine_state_argument_indirect(tcx, body);
1310        }
1311    }
1312
1313    // Make sure we remove dead blocks to remove
1314    // unrelated code from the drop part of the function
1315    simplify::remove_dead_blocks(body);
1316
1317    pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
1318
1319    if let Some(dumper) = MirDumper::new(tcx, "coroutine_resume", body) {
1320        dumper.dump_mir(body);
1321    }
1322}
1323
1324/// An operation that can be performed on a coroutine.
1325#[derive(PartialEq, Copy, Clone, Debug)]
1326enum Operation {
1327    Resume,
1328    Drop,
1329}
1330
1331impl Operation {
1332    fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1333        match self {
1334            Operation::Resume => Some(point.resume),
1335            Operation::Drop => point.drop,
1336        }
1337    }
1338}
1339
1340#[tracing::instrument(level = "trace", skip(transform, body))]
1341fn create_cases<'tcx>(
1342    body: &mut Body<'tcx>,
1343    transform: &TransformVisitor<'tcx>,
1344    operation: Operation,
1345) -> Vec<(usize, BasicBlock)> {
1346    let source_info = SourceInfo::outermost(body.span);
1347
1348    transform
1349        .suspension_points
1350        .iter()
1351        .filter_map(|point| {
1352            // Find the target for this suspension point, if applicable
1353            operation.target_block(point).map(|target| {
1354                let mut statements = Vec::new();
1355
1356                // Create StorageLive instructions for locals with live storage
1357                for l in body.local_decls.indices() {
1358                    let needs_storage_live = point.storage_liveness.contains(l)
1359                        && !transform.remap.contains(l)
1360                        && !transform.always_live_locals.contains(l);
1361                    if needs_storage_live {
1362                        statements.push(Statement::new(source_info, StatementKind::StorageLive(l)));
1363                    }
1364                }
1365
1366                if operation == Operation::Resume && point.resume_arg != CTX_ARG.into() {
1367                    // Move the resume argument to the destination place of the `Yield` terminator
1368                    statements.push(Statement::new(
1369                        source_info,
1370                        StatementKind::Assign(Box::new((
1371                            point.resume_arg,
1372                            Rvalue::Use(Operand::Move(CTX_ARG.into())),
1373                        ))),
1374                    ));
1375                }
1376
1377                // Then jump to the real target
1378                let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1379                    statements,
1380                    Some(Terminator { source_info, kind: TerminatorKind::Goto { target } }),
1381                    false,
1382                ));
1383
1384                (point.state, block)
1385            })
1386        })
1387        .collect()
1388}
1389
1390#[instrument(level = "debug", skip(tcx), ret)]
1391pub(crate) fn mir_coroutine_witnesses<'tcx>(
1392    tcx: TyCtxt<'tcx>,
1393    def_id: LocalDefId,
1394) -> Option<CoroutineLayout<'tcx>> {
1395    let (body, _) = tcx.mir_promoted(def_id);
1396    let body = body.borrow();
1397    let body = &*body;
1398
1399    // The first argument is the coroutine type passed by value
1400    let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
1401
1402    let movable = match *coroutine_ty.kind() {
1403        ty::Coroutine(def_id, _) => tcx.coroutine_movability(def_id) == hir::Movability::Movable,
1404        ty::Error(_) => return None,
1405        _ => span_bug!(body.span, "unexpected coroutine type {}", coroutine_ty),
1406    };
1407
1408    // The witness simply contains all locals live across suspend points.
1409
1410    let always_live_locals = always_storage_live_locals(body);
1411    let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1412
1413    // Extract locals which are live across suspension point into `layout`
1414    // `remap` gives a mapping from local indices onto coroutine struct indices
1415    // `storage_liveness` tells us which locals have live storage at suspension points
1416    let (_, coroutine_layout, _) = compute_layout(liveness_info, body);
1417
1418    check_suspend_tys(tcx, &coroutine_layout, body);
1419    check_field_tys_sized(tcx, &coroutine_layout, def_id);
1420
1421    Some(coroutine_layout)
1422}
1423
1424fn check_field_tys_sized<'tcx>(
1425    tcx: TyCtxt<'tcx>,
1426    coroutine_layout: &CoroutineLayout<'tcx>,
1427    def_id: LocalDefId,
1428) {
1429    // No need to check if unsized_fn_params is disabled,
1430    // since we will error during typeck.
1431    if !tcx.features().unsized_fn_params() {
1432        return;
1433    }
1434
1435    // FIXME(#132279): @lcnr believes that we may want to support coroutines
1436    // whose `Sized`-ness relies on the hidden types of opaques defined by the
1437    // parent function. In this case we'd have to be able to reveal only these
1438    // opaques here.
1439    let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
1440    let param_env = tcx.param_env(def_id);
1441
1442    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1443    for field_ty in &coroutine_layout.field_tys {
1444        ocx.register_bound(
1445            ObligationCause::new(
1446                field_ty.source_info.span,
1447                def_id,
1448                ObligationCauseCode::SizedCoroutineInterior(def_id),
1449            ),
1450            param_env,
1451            field_ty.ty,
1452            tcx.require_lang_item(hir::LangItem::Sized, field_ty.source_info.span),
1453        );
1454    }
1455
1456    let errors = ocx.evaluate_obligations_error_on_ambiguity();
1457    debug!(?errors);
1458    if !errors.is_empty() {
1459        infcx.err_ctxt().report_fulfillment_errors(errors);
1460    }
1461}
1462
1463impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1464    #[instrument(level = "debug", skip(self, tcx, body), ret)]
1465    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1466        debug!(def_id = ?body.source.def_id());
1467
1468        let Some(old_yield_ty) = body.yield_ty() else {
1469            // This only applies to coroutines
1470            return;
1471        };
1472        tracing::trace!(def_id = ?body.source.def_id());
1473
1474        let old_ret_ty = body.return_ty();
1475
1476        assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1477
1478        if let Some(dumper) = MirDumper::new(tcx, "coroutine_before", body) {
1479            dumper.dump_mir(body);
1480        }
1481
1482        // The first argument is the coroutine type passed by value
1483        let coroutine_ty = body.local_decls.raw[1].ty;
1484        let coroutine_kind = body.coroutine_kind().unwrap();
1485
1486        // Get the discriminant type and args which typeck computed
1487        let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1488            tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1489        };
1490        let discr_ty = args.as_coroutine().discr_ty(tcx);
1491
1492        let new_ret_ty = match coroutine_kind {
1493            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1494                // Compute Poll<return_ty>
1495                let poll_did = tcx.require_lang_item(LangItem::Poll, body.span);
1496                let poll_adt_ref = tcx.adt_def(poll_did);
1497                let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1498                Ty::new_adt(tcx, poll_adt_ref, poll_args)
1499            }
1500            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1501                // Compute Option<yield_ty>
1502                let option_did = tcx.require_lang_item(LangItem::Option, body.span);
1503                let option_adt_ref = tcx.adt_def(option_did);
1504                let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1505                Ty::new_adt(tcx, option_adt_ref, option_args)
1506            }
1507            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1508                // The yield ty is already `Poll<Option<yield_ty>>`
1509                old_yield_ty
1510            }
1511            CoroutineKind::Coroutine(_) => {
1512                // Compute CoroutineState<yield_ty, return_ty>
1513                let state_did = tcx.require_lang_item(LangItem::CoroutineState, body.span);
1514                let state_adt_ref = tcx.adt_def(state_did);
1515                let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1516                Ty::new_adt(tcx, state_adt_ref, state_args)
1517            }
1518        };
1519
1520        // We need to insert clean drop for unresumed state and perform drop elaboration
1521        // (finally in open_drop_for_tuple) before async drop expansion.
1522        // Async drops, produced by this drop elaboration, will be expanded,
1523        // and corresponding futures kept in layout.
1524        let has_async_drops = matches!(
1525            coroutine_kind,
1526            CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1527        ) && has_expandable_async_drops(tcx, body, coroutine_ty);
1528
1529        // Replace all occurrences of `ResumeTy` with `&mut Context<'_>` within async bodies.
1530        if matches!(
1531            coroutine_kind,
1532            CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1533        ) {
1534            let context_mut_ref = transform_async_context(tcx, body);
1535            expand_async_drops(tcx, body, context_mut_ref, coroutine_kind, coroutine_ty);
1536
1537            if let Some(dumper) = MirDumper::new(tcx, "coroutine_async_drop_expand", body) {
1538                dumper.dump_mir(body);
1539            }
1540        } else {
1541            cleanup_async_drops(body);
1542        }
1543
1544        let always_live_locals = always_storage_live_locals(body);
1545        let movable = coroutine_kind.movability() == hir::Movability::Movable;
1546        let liveness_info =
1547            locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1548
1549        if tcx.sess.opts.unstable_opts.validate_mir {
1550            let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1551                assigned_local: None,
1552                saved_locals: &liveness_info.saved_locals,
1553                storage_conflicts: &liveness_info.storage_conflicts,
1554            };
1555
1556            vis.visit_body(body);
1557        }
1558
1559        // Extract locals which are live across suspension point into `layout`
1560        // `remap` gives a mapping from local indices onto coroutine struct indices
1561        // `storage_liveness` tells us which locals have live storage at suspension points
1562        let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1563
1564        let can_return = can_return(tcx, body, body.typing_env(tcx));
1565
1566        // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1567        // RETURN_PLACE then is a fresh unused local with type ret_ty.
1568        let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1569        tracing::trace!(?new_ret_local);
1570
1571        // Run the transformation which converts Places from Local to coroutine struct
1572        // accesses for locals in `remap`.
1573        // It also rewrites `return x` and `yield y` as writing a new coroutine state and returning
1574        // either `CoroutineState::Complete(x)` and `CoroutineState::Yielded(y)`,
1575        // or `Poll::Ready(x)` and `Poll::Pending` respectively depending on the coroutine kind.
1576        let mut transform = TransformVisitor {
1577            tcx,
1578            coroutine_kind,
1579            remap,
1580            storage_liveness,
1581            always_live_locals,
1582            suspension_points: Vec::new(),
1583            discr_ty,
1584            new_ret_local,
1585            old_ret_ty,
1586            old_yield_ty,
1587        };
1588        transform.visit_body(body);
1589
1590        // Swap the actual `RETURN_PLACE` and the provisional `new_ret_local`.
1591        transform.replace_local(RETURN_PLACE, new_ret_local, body);
1592
1593        // MIR parameters are not explicitly assigned-to when entering the MIR body.
1594        // If we want to save their values inside the coroutine state, we need to do so explicitly.
1595        let source_info = SourceInfo::outermost(body.span);
1596        let args_iter = body.args_iter();
1597        body.basic_blocks.as_mut()[START_BLOCK].statements.splice(
1598            0..0,
1599            args_iter.filter_map(|local| {
1600                let (ty, variant_index, idx) = transform.remap[local]?;
1601                let lhs = transform.make_field(variant_index, idx, ty);
1602                let rhs = Rvalue::Use(Operand::Move(local.into()));
1603                let assign = StatementKind::Assign(Box::new((lhs, rhs)));
1604                Some(Statement::new(source_info, assign))
1605            }),
1606        );
1607
1608        // Update our MIR struct to reflect the changes we've made
1609        body.arg_count = 2; // self, resume arg
1610        body.spread_arg = None;
1611
1612        // Remove the context argument within generator bodies.
1613        if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1614            transform_gen_context(body);
1615        }
1616
1617        // The original arguments to the function are no longer arguments, mark them as such.
1618        // Otherwise they'll conflict with our new arguments, which although they don't have
1619        // argument_index set, will get emitted as unnamed arguments.
1620        for var in &mut body.var_debug_info {
1621            var.argument_index = None;
1622        }
1623
1624        body.coroutine.as_mut().unwrap().yield_ty = None;
1625        body.coroutine.as_mut().unwrap().resume_ty = None;
1626        body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1627
1628        // FIXME: Drops, produced by insert_clean_drop + elaborate_coroutine_drops,
1629        // are currently sync only. To allow async for them, we need to move those calls
1630        // before expand_async_drops, and fix the related problems.
1631        //
1632        // Insert `drop(coroutine_struct)` which is used to drop upvars for coroutines in
1633        // the unresumed state.
1634        // This is expanded to a drop ladder in `elaborate_coroutine_drops`.
1635        let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1636
1637        if let Some(dumper) = MirDumper::new(tcx, "coroutine_pre-elab", body) {
1638            dumper.dump_mir(body);
1639        }
1640
1641        // Expand `drop(coroutine_struct)` to a drop ladder which destroys upvars.
1642        // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1643        // However we need to also elaborate the code generated by `insert_clean_drop`.
1644        elaborate_coroutine_drops(tcx, body);
1645
1646        if let Some(dumper) = MirDumper::new(tcx, "coroutine_post-transform", body) {
1647            dumper.dump_mir(body);
1648        }
1649
1650        let can_unwind = can_unwind(tcx, body);
1651
1652        // Create a copy of our MIR and use it to create the drop shim for the coroutine
1653        if has_async_drops {
1654            // If coroutine has async drops, generating async drop shim
1655            let mut drop_shim =
1656                create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1657            // Run derefer to fix Derefs that are not in the first place
1658            deref_finder(tcx, &mut drop_shim, false);
1659            body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1660        } else {
1661            // If coroutine has no async drops, generating sync drop shim
1662            let mut drop_shim =
1663                create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1664            // Run derefer to fix Derefs that are not in the first place
1665            deref_finder(tcx, &mut drop_shim, false);
1666            body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1667
1668            // For coroutine with sync drop, generating async proxy for `future_drop_poll` call
1669            let mut proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body);
1670            deref_finder(tcx, &mut proxy_shim, false);
1671            body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1672        }
1673
1674        // Create the Coroutine::resume / Future::poll function
1675        create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1676
1677        // Run derefer to fix Derefs that are not in the first place
1678        deref_finder(tcx, body, false);
1679    }
1680
1681    fn is_required(&self) -> bool {
1682        true
1683    }
1684}
1685
1686/// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1687/// in the coroutine state machine but whose storage is not marked as conflicting
1688///
1689/// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1690///
1691/// This condition would arise when the assignment is the last use of `_5` but the initial
1692/// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1693/// conflicting. Non-conflicting coroutine saved locals may be stored at the same location within
1694/// the coroutine state machine, which would result in ill-formed MIR: the left-hand and right-hand
1695/// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1696///
1697/// [#73137]: https://github.com/rust-lang/rust/issues/73137
1698struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1699    saved_locals: &'a CoroutineSavedLocals,
1700    storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1701    assigned_local: Option<CoroutineSavedLocal>,
1702}
1703
1704impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1705    fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1706        if place.is_indirect() {
1707            return None;
1708        }
1709
1710        self.saved_locals.get(place.local)
1711    }
1712
1713    fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1714        if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1715            assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1716
1717            self.assigned_local = Some(assigned_local);
1718            f(self);
1719            self.assigned_local = None;
1720        }
1721    }
1722}
1723
1724impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1725    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1726        let Some(lhs) = self.assigned_local else {
1727            // This visitor only invokes `visit_place` for the right-hand side of an assignment
1728            // and only after setting `self.assigned_local`. However, the default impl of
1729            // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1730            // with debuginfo. Ignore them here.
1731            assert!(!context.is_use());
1732            return;
1733        };
1734
1735        let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1736
1737        if !self.storage_conflicts.contains(lhs, rhs) {
1738            bug!(
1739                "Assignment between coroutine saved locals whose storage is not \
1740                    marked as conflicting: {:?}: {:?} = {:?}",
1741                location,
1742                lhs,
1743                rhs,
1744            );
1745        }
1746    }
1747
1748    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1749        match &statement.kind {
1750            StatementKind::Assign(box (lhs, rhs)) => {
1751                self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1752            }
1753
1754            StatementKind::FakeRead(..)
1755            | StatementKind::SetDiscriminant { .. }
1756            | StatementKind::StorageLive(_)
1757            | StatementKind::StorageDead(_)
1758            | StatementKind::Retag(..)
1759            | StatementKind::AscribeUserType(..)
1760            | StatementKind::PlaceMention(..)
1761            | StatementKind::Coverage(..)
1762            | StatementKind::Intrinsic(..)
1763            | StatementKind::ConstEvalCounter
1764            | StatementKind::BackwardIncompatibleDropHint { .. }
1765            | StatementKind::Nop => {}
1766        }
1767    }
1768
1769    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1770        // Checking for aliasing in terminators is probably overkill, but until we have actual
1771        // semantics, we should be conservative here.
1772        match &terminator.kind {
1773            TerminatorKind::Call {
1774                func,
1775                args,
1776                destination,
1777                target: Some(_),
1778                unwind: _,
1779                call_source: _,
1780                fn_span: _,
1781            } => {
1782                self.check_assigned_place(*destination, |this| {
1783                    this.visit_operand(func, location);
1784                    for arg in args {
1785                        this.visit_operand(&arg.node, location);
1786                    }
1787                });
1788            }
1789
1790            TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1791                self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1792            }
1793
1794            // FIXME: Does `asm!` have any aliasing requirements?
1795            TerminatorKind::InlineAsm { .. } => {}
1796
1797            TerminatorKind::Call { .. }
1798            | TerminatorKind::Goto { .. }
1799            | TerminatorKind::SwitchInt { .. }
1800            | TerminatorKind::UnwindResume
1801            | TerminatorKind::UnwindTerminate(_)
1802            | TerminatorKind::Return
1803            | TerminatorKind::TailCall { .. }
1804            | TerminatorKind::Unreachable
1805            | TerminatorKind::Drop { .. }
1806            | TerminatorKind::Assert { .. }
1807            | TerminatorKind::CoroutineDrop
1808            | TerminatorKind::FalseEdge { .. }
1809            | TerminatorKind::FalseUnwind { .. } => {}
1810        }
1811    }
1812}
1813
1814fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &CoroutineLayout<'tcx>, body: &Body<'tcx>) {
1815    let mut linted_tys = FxHashSet::default();
1816
1817    for (variant, yield_source_info) in
1818        layout.variant_fields.iter().zip(&layout.variant_source_info)
1819    {
1820        debug!(?variant);
1821        for &local in variant {
1822            let decl = &layout.field_tys[local];
1823            debug!(?decl);
1824
1825            if !decl.ignore_for_traits && linted_tys.insert(decl.ty) {
1826                let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else {
1827                    continue;
1828                };
1829
1830                check_must_not_suspend_ty(
1831                    tcx,
1832                    decl.ty,
1833                    hir_id,
1834                    SuspendCheckData {
1835                        source_span: decl.source_info.span,
1836                        yield_span: yield_source_info.span,
1837                        plural_len: 1,
1838                        ..Default::default()
1839                    },
1840                );
1841            }
1842        }
1843    }
1844}
1845
1846#[derive(Default)]
1847struct SuspendCheckData<'a> {
1848    source_span: Span,
1849    yield_span: Span,
1850    descr_pre: &'a str,
1851    descr_post: &'a str,
1852    plural_len: usize,
1853}
1854
1855// Returns whether it emitted a diagnostic or not
1856// Note that this fn and the proceeding one are based on the code
1857// for creating must_use diagnostics
1858//
1859// Note that this technique was chosen over things like a `Suspend` marker trait
1860// as it is simpler and has precedent in the compiler
1861fn check_must_not_suspend_ty<'tcx>(
1862    tcx: TyCtxt<'tcx>,
1863    ty: Ty<'tcx>,
1864    hir_id: hir::HirId,
1865    data: SuspendCheckData<'_>,
1866) -> bool {
1867    if ty.is_unit() {
1868        return false;
1869    }
1870
1871    let plural_suffix = pluralize!(data.plural_len);
1872
1873    debug!("Checking must_not_suspend for {}", ty);
1874
1875    match *ty.kind() {
1876        ty::Adt(_, args) if ty.is_box() => {
1877            let boxed_ty = args.type_at(0);
1878            let allocator_ty = args.type_at(1);
1879            check_must_not_suspend_ty(
1880                tcx,
1881                boxed_ty,
1882                hir_id,
1883                SuspendCheckData { descr_pre: &format!("{}boxed ", data.descr_pre), ..data },
1884            ) || check_must_not_suspend_ty(
1885                tcx,
1886                allocator_ty,
1887                hir_id,
1888                SuspendCheckData { descr_pre: &format!("{}allocator ", data.descr_pre), ..data },
1889            )
1890        }
1891        // FIXME(sized_hierarchy): This should be replaced with a requirement that types in
1892        // coroutines implement `const Sized`. Scalable vectors are temporarily `Sized` while
1893        // `feature(sized_hierarchy)` is not fully implemented, but in practice are
1894        // non-`const Sized` and so do not have a known size at compilation time. Layout computation
1895        // for a coroutine containing scalable vectors would be incorrect.
1896        ty::Adt(def, _) if def.repr().scalable() => {
1897            tcx.dcx()
1898                .span_err(data.source_span, "scalable vectors cannot be held over await points");
1899            true
1900        }
1901        ty::Adt(def, _) => check_must_not_suspend_def(tcx, def.did(), hir_id, data),
1902        // FIXME: support adding the attribute to TAITs
1903        ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1904            let mut has_emitted = false;
1905            for &(predicate, _) in tcx.explicit_item_bounds(def).skip_binder() {
1906                // We only look at the `DefId`, so it is safe to skip the binder here.
1907                if let ty::ClauseKind::Trait(ref poly_trait_predicate) =
1908                    predicate.kind().skip_binder()
1909                {
1910                    let def_id = poly_trait_predicate.trait_ref.def_id;
1911                    let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix);
1912                    if check_must_not_suspend_def(
1913                        tcx,
1914                        def_id,
1915                        hir_id,
1916                        SuspendCheckData { descr_pre, ..data },
1917                    ) {
1918                        has_emitted = true;
1919                        break;
1920                    }
1921                }
1922            }
1923            has_emitted
1924        }
1925        ty::Dynamic(binder, _) => {
1926            let mut has_emitted = false;
1927            for predicate in binder.iter() {
1928                if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
1929                    let def_id = trait_ref.def_id;
1930                    let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post);
1931                    if check_must_not_suspend_def(
1932                        tcx,
1933                        def_id,
1934                        hir_id,
1935                        SuspendCheckData { descr_post, ..data },
1936                    ) {
1937                        has_emitted = true;
1938                        break;
1939                    }
1940                }
1941            }
1942            has_emitted
1943        }
1944        ty::Tuple(fields) => {
1945            let mut has_emitted = false;
1946            for (i, ty) in fields.iter().enumerate() {
1947                let descr_post = &format!(" in tuple element {i}");
1948                if check_must_not_suspend_ty(
1949                    tcx,
1950                    ty,
1951                    hir_id,
1952                    SuspendCheckData { descr_post, ..data },
1953                ) {
1954                    has_emitted = true;
1955                }
1956            }
1957            has_emitted
1958        }
1959        ty::Array(ty, len) => {
1960            let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
1961            check_must_not_suspend_ty(
1962                tcx,
1963                ty,
1964                hir_id,
1965                SuspendCheckData {
1966                    descr_pre,
1967                    // FIXME(must_not_suspend): This is wrong. We should handle printing unevaluated consts.
1968                    plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1,
1969                    ..data
1970                },
1971            )
1972        }
1973        // If drop tracking is enabled, we want to look through references, since the referent
1974        // may not be considered live across the await point.
1975        ty::Ref(_region, ty, _mutability) => {
1976            let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix);
1977            check_must_not_suspend_ty(tcx, ty, hir_id, SuspendCheckData { descr_pre, ..data })
1978        }
1979        _ => false,
1980    }
1981}
1982
1983fn check_must_not_suspend_def(
1984    tcx: TyCtxt<'_>,
1985    def_id: DefId,
1986    hir_id: hir::HirId,
1987    data: SuspendCheckData<'_>,
1988) -> bool {
1989    if let Some(reason_str) = find_attr!(tcx, def_id, MustNotSupend {reason} => reason) {
1990        let reason =
1991            reason_str.map(|s| errors::MustNotSuspendReason { span: data.source_span, reason: s });
1992        tcx.emit_node_span_lint(
1993            rustc_session::lint::builtin::MUST_NOT_SUSPEND,
1994            hir_id,
1995            data.source_span,
1996            errors::MustNotSupend {
1997                tcx,
1998                yield_sp: data.yield_span,
1999                reason,
2000                src_sp: data.source_span,
2001                pre: data.descr_pre,
2002                def_id,
2003                post: data.descr_post,
2004            },
2005        );
2006
2007        true
2008    } else {
2009        false
2010    }
2011}