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