Skip to main content

rustc_mir_transform/coroutine/
layout.rs

1//! Coroutine `StateTransform` inverts control flow in a coroutine from a function with yield
2//! points to a state machine. Each yield point corresponds to a state variant, and each variant
3//! stores the locals that are needed to continue the coroutine.
4//!
5//! The state transform creates a `poll` method such that calling the coroutine `f()` is equivalent
6//! to:
7//! ```ignore (example)
8//! fn initial_mir(state: CoroutineState, mut resume_arg: ResumeTy) {
9//!     // Repeatedly poll the state machine.
10//!     loop {
11//!         match final_mir(&mut state, resume_arg) {
12//!             CoroutineState::Yielded(yield_value) => resume_arg = yield yield_value,
13//!             CoroutineState::Complete(return_value) => return return_value,
14//!         }
15//!     }
16//! }
17//! ```
18//!
19//! This file compute for each yield point the set of locals that need to be saved in the coroutine
20//! state. This is also used for borrowck to compute the set of types held inside that state, which
21//! determine trait and region predicates that hold for this state.
22
23use std::ops;
24
25use itertools::izip;
26use rustc_abi::{FieldIdx, VariantIdx};
27use rustc_data_structures::fx::FxHashSet;
28use rustc_errors::pluralize;
29use rustc_hir::attrs::lang_items::LangItem;
30use rustc_hir::{self as hir, find_attr};
31use rustc_index::bit_set::{BitMatrix, DenseBitSet};
32use rustc_index::{Idx, IndexVec};
33use rustc_infer::traits::TraitErrors;
34use rustc_middle::mir::*;
35use rustc_middle::span_bug;
36use rustc_middle::ty::{self, CoroutineArgs, CoroutineArgsExt, Ty, TyCtxt, TypingMode};
37use rustc_mir_dataflow::impls::{
38    MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
39    always_storage_live_locals,
40};
41use rustc_mir_dataflow::{Analysis, Results, ResultsCursor, ResultsVisitor, visit_results};
42use rustc_span::Span;
43use rustc_span::def_id::{DefId, LocalDefId};
44use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
45use rustc_trait_selection::infer::TyCtxtInferExt as _;
46use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt};
47use tracing::{debug, instrument};
48
49use crate::diagnostics::{MustNotSupend, MustNotSuspendReason};
50
51const SELF_ARG: Local = Local::arg(0);
52
53pub(super) struct LivenessInfo {
54    /// Which locals are live across any suspension point.
55    pub(super) saved_locals: CoroutineSavedLocals,
56
57    /// The set of saved locals live at each suspension point.
58    live_locals_at_suspension_points: Vec<DenseBitSet<CoroutineSavedLocal>>,
59
60    /// Parallel vec to the above with SourceInfo for each yield terminator.
61    source_info_at_suspension_points: Vec<SourceInfo>,
62
63    /// For every saved local, the set of other saved locals that are
64    /// storage-live at the same time as this local. We cannot overlap locals in
65    /// the layout which have conflicting storage.
66    pub(super) storage_conflicts: BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
67
68    /// For every suspending block, the locals which are storage-live across
69    /// that suspension point.
70    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
71}
72
73/// Computes which locals have to be stored in the state-machine for the
74/// given coroutine.
75///
76/// The basic idea is as follows:
77/// - a local is live until we encounter a `StorageDead` statement. In
78///   case none exist, the local is considered to be always live.
79/// - a local has to be stored if it is either directly used after the
80///   the suspend point, or if it is live and has been previously borrowed.
81#[tracing::instrument(level = "trace", skip(tcx, body))]
82pub(super) fn locals_live_across_suspend_points<'tcx>(
83    tcx: TyCtxt<'tcx>,
84    body: &Body<'tcx>,
85    always_live_locals: &DenseBitSet<Local>,
86    movable: bool,
87) -> LivenessInfo {
88    // Calculate when MIR locals have live storage. This gives us an upper bound of their
89    // lifetimes.
90    let mut storage_live = MaybeStorageLive::new(std::borrow::Cow::Borrowed(always_live_locals))
91        .iterate_to_fixpoint(tcx, body, None)
92        .into_results_cursor(body);
93
94    // Calculate the MIR locals that have been previously borrowed (even if they are still active).
95    let borrowed_locals = MaybeBorrowedLocals.iterate_to_fixpoint(tcx, body, Some("coroutine"));
96
97    // Calculate the MIR locals that we need to keep storage around for.
98    let requires_storage =
99        MaybeRequiresStorage::new(body, &borrowed_locals).iterate_to_fixpoint(tcx, body, None);
100    let mut requires_storage_cursor = ResultsCursor::new_borrowing(body, &requires_storage);
101
102    // Calculate the liveness of MIR locals ignoring borrows.
103    let mut liveness =
104        MaybeLiveLocals.iterate_to_fixpoint(tcx, body, Some("coroutine")).into_results_cursor(body);
105
106    let mut storage_liveness_map = IndexVec::from_elem(None, &body.basic_blocks);
107    let mut live_locals_at_suspension_points = Vec::new();
108    let mut source_info_at_suspension_points = Vec::new();
109    let mut live_locals_at_any_suspension_point = DenseBitSet::new_empty(body.local_decls.len());
110    let mut borrowed_locals_cursor = ResultsCursor::new_owning(body, borrowed_locals);
111
112    for (block, data) in body.basic_blocks.iter_enumerated() {
113        let TerminatorKind::Yield { .. } = data.terminator().kind else { continue };
114
115        let loc = Location { block, statement_index: data.statements.len() };
116
117        liveness.seek_to_block_end(block);
118        let mut live_locals = liveness.get().clone();
119
120        if !movable {
121            // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
122            // This is correct for movable coroutines since borrows cannot live across
123            // suspension points. However for immovable coroutines we need to account for
124            // borrows, so we conservatively assume that all borrowed locals are live until
125            // we find a StorageDead statement referencing the locals.
126            // To do this we just union our `liveness` result with `borrowed_locals`, which
127            // contains all the locals which has been borrowed before this suspension point.
128            // If a borrow is converted to a raw reference, we must also assume that it lives
129            // forever. Note that the final liveness is still bounded by the storage liveness
130            // of the local, which happens using the `intersect` operation below.
131            borrowed_locals_cursor.seek_before_primary_effect(loc);
132            live_locals.union(borrowed_locals_cursor.get());
133        }
134
135        // Store the storage liveness for later use so we can restore the state
136        // after a suspension point
137        storage_live.seek_before_primary_effect(loc);
138        storage_liveness_map[block] = Some(storage_live.get().clone());
139
140        // Locals live are live at this point only if they are used across
141        // suspension points (the `liveness` variable)
142        // and their storage is required (the `storage_required` variable)
143        requires_storage_cursor.seek_before_primary_effect(loc);
144        live_locals.intersect(requires_storage_cursor.get());
145
146        // The coroutine argument is ignored.
147        live_locals.remove(SELF_ARG);
148
149        debug!(?loc, ?live_locals);
150
151        // Add the locals live at this suspension point to the set of locals which live across
152        // any suspension points
153        live_locals_at_any_suspension_point.union(&live_locals);
154
155        live_locals_at_suspension_points.push(live_locals);
156        source_info_at_suspension_points.push(data.terminator().source_info);
157    }
158
159    debug!(?live_locals_at_any_suspension_point);
160    let saved_locals = CoroutineSavedLocals(live_locals_at_any_suspension_point);
161
162    // Renumber our liveness_map bitsets to include only the locals we are
163    // saving.
164    let live_locals_at_suspension_points = live_locals_at_suspension_points
165        .iter()
166        .map(|live_here| saved_locals.renumber_bitset(live_here))
167        .collect();
168
169    let storage_conflicts = compute_storage_conflicts(
170        body,
171        &saved_locals,
172        always_live_locals.clone(),
173        &requires_storage,
174    );
175
176    LivenessInfo {
177        saved_locals,
178        live_locals_at_suspension_points,
179        source_info_at_suspension_points,
180        storage_conflicts,
181        storage_liveness: storage_liveness_map,
182    }
183}
184
185/// The set of `Local`s that must be saved across yield points.
186///
187/// `CoroutineSavedLocal` is indexed in terms of the elements in this set;
188/// i.e. `CoroutineSavedLocal::new(1)` corresponds to the second local
189/// included in this set.
190pub(super) struct CoroutineSavedLocals(DenseBitSet<Local>);
191
192impl CoroutineSavedLocals {
193    /// Returns an iterator over each `CoroutineSavedLocal` along with the `Local` it corresponds
194    /// to.
195    fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (CoroutineSavedLocal, Local)> {
196        self.iter().enumerate().map(|(i, l)| (CoroutineSavedLocal::from(i), l))
197    }
198
199    /// Transforms a `DenseBitSet<Local>` that contains only locals saved across yield points to the
200    /// equivalent `DenseBitSet<CoroutineSavedLocal>`.
201    fn renumber_bitset(&self, input: &DenseBitSet<Local>) -> DenseBitSet<CoroutineSavedLocal> {
202        assert!(self.superset(input), "{:?} not a superset of {:?}", self.0, input);
203        let mut out = DenseBitSet::new_empty(self.count());
204        for (saved_local, local) in self.iter_enumerated() {
205            if input.contains(local) {
206                out.insert(saved_local);
207            }
208        }
209        out
210    }
211
212    pub(super) fn get(&self, local: Local) -> Option<CoroutineSavedLocal> {
213        if !self.contains(local) {
214            return None;
215        }
216
217        let idx = self.iter().take_while(|&l| l < local).count();
218        Some(CoroutineSavedLocal::new(idx))
219    }
220}
221
222impl ops::Deref for CoroutineSavedLocals {
223    type Target = DenseBitSet<Local>;
224
225    fn deref(&self) -> &Self::Target {
226        &self.0
227    }
228}
229
230/// For every saved local, looks for which locals are StorageLive at the same
231/// time. Generates a bitset for every local of all the other locals that may be
232/// StorageLive simultaneously with that local. This is used in the layout
233/// computation; see `CoroutineLayout` for more.
234fn compute_storage_conflicts<'mir, 'tcx>(
235    body: &'mir Body<'tcx>,
236    saved_locals: &'mir CoroutineSavedLocals,
237    always_live_locals: DenseBitSet<Local>,
238    results: &Results<'tcx, MaybeRequiresStorage>,
239) -> BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal> {
240    assert_eq!(body.local_decls.len(), saved_locals.domain_size());
241
242    debug!("compute_storage_conflicts({:?})", body.span);
243    debug!("always_live = {:?}", always_live_locals);
244
245    // Locals that are always live or ones that need to be stored across
246    // suspension points are not eligible for overlap.
247    let mut ineligible_locals = always_live_locals;
248    ineligible_locals.intersect(&**saved_locals);
249
250    // Compute the storage conflicts for all eligible locals.
251    let mut visitor = StorageConflictVisitor {
252        saved_locals,
253        local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
254        eligible_storage_live: DenseBitSet::new_empty(body.local_decls.len()),
255    };
256
257    // Filter out:
258    // - unreachable blocks;
259    // - reachable blocks that end in `Unreachable`, because they never complete execution and
260    //   conflicts within them are spurious.
261    let blocks = traversal::reachable(body).filter_map(|(bb, data)| {
262        (!matches!(data.terminator().kind, TerminatorKind::Unreachable)).then_some(bb)
263    });
264    visit_results(body, blocks, results, &mut visitor);
265
266    let local_conflicts = visitor.local_conflicts;
267
268    // Compress the matrix using only stored locals (Local -> CoroutineSavedLocal).
269    //
270    // NOTE: Today we store a full conflict bitset for every local. Technically
271    // this is twice as many bits as we need, since the relation is symmetric.
272    // However, in practice these bitsets are not usually large. The layout code
273    // also needs to keep track of how many conflicts each local has, so it's
274    // simpler to keep it this way for now.
275    let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
276    for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
277        if ineligible_locals.contains(local_a) {
278            // Conflicts with everything.
279            storage_conflicts.insert_all_into_row(saved_local_a);
280        } else {
281            // Keep overlap information only for stored locals.
282            for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
283                if local_conflicts.contains(local_a, local_b) {
284                    storage_conflicts.insert(saved_local_a, saved_local_b);
285                }
286            }
287        }
288    }
289    storage_conflicts
290}
291
292struct StorageConflictVisitor<'a> {
293    saved_locals: &'a CoroutineSavedLocals,
294    // FIXME(tmandry): Consider using sparse bitsets here once we have good
295    // benchmarks for coroutines.
296    local_conflicts: BitMatrix<Local, Local>,
297    // We keep this bitset as a buffer to avoid reallocating memory.
298    eligible_storage_live: DenseBitSet<Local>,
299}
300
301impl<'a, 'tcx> ResultsVisitor<'tcx, MaybeRequiresStorage> for StorageConflictVisitor<'a> {
302    fn visit_after_early_statement_effect(
303        &mut self,
304        _analysis: &MaybeRequiresStorage,
305        state: &DenseBitSet<Local>,
306        _statement: &Statement<'tcx>,
307        _loc: Location,
308    ) {
309        self.apply_state(state);
310    }
311
312    fn visit_after_early_terminator_effect(
313        &mut self,
314        _analysis: &MaybeRequiresStorage,
315        state: &DenseBitSet<Local>,
316        _terminator: &Terminator<'tcx>,
317        _loc: Location,
318    ) {
319        self.apply_state(state);
320    }
321}
322
323impl StorageConflictVisitor<'_> {
324    fn apply_state(&mut self, state: &DenseBitSet<Local>) {
325        self.eligible_storage_live.clone_from(state);
326        self.eligible_storage_live.intersect(&**self.saved_locals);
327
328        for local in self.eligible_storage_live.iter() {
329            self.local_conflicts.union_row_with(&self.eligible_storage_live, local);
330        }
331    }
332}
333
334#[tracing::instrument(level = "trace", skip(liveness, body))]
335pub(super) fn compute_layout<'tcx>(
336    liveness: LivenessInfo,
337    body: &Body<'tcx>,
338) -> (
339    IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
340    CoroutineLayout<'tcx>,
341    IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
342) {
343    let LivenessInfo {
344        saved_locals,
345        live_locals_at_suspension_points,
346        source_info_at_suspension_points,
347        storage_conflicts,
348        storage_liveness,
349    } = liveness;
350
351    // Gather live local types.
352    let mut tys: IndexVec<CoroutineSavedLocal, CoroutineSavedTy<'_>> = saved_locals
353        .iter_enumerated()
354        .map(|(saved_local, local)| {
355            debug!("coroutine saved local {:?} => {:?}", saved_local, local);
356
357            let decl = &body.local_decls[local];
358
359            // Do not `unwrap_crate_local` here, as post-borrowck cleanup may have already cleared
360            // the information. This is alright, since `ignore_for_traits` is only relevant when
361            // this code runs on pre-cleanup MIR, and `ignore_for_traits = false` is the safer
362            // default.
363            let ignore_for_traits = match decl.local_info {
364                // Do not include raw pointers created from accessing `static` items, as those could
365                // well be re-created by another access to the same static.
366                ClearCrossCrate::Set(LocalInfo::StaticRef { is_thread_local, .. }) => {
367                    !is_thread_local
368                }
369                // Fake borrows are only read by fake reads, so do not have any reality in
370                // post-analysis MIR.
371                ClearCrossCrate::Set(LocalInfo::FakeBorrow) => true,
372                _ => false,
373            };
374
375            CoroutineSavedTy {
376                ty: decl.ty,
377                source_info: decl.source_info,
378                ignore_for_traits,
379                // Will be set later when walking debuginfo.
380                debuginfo_name: None,
381            }
382        })
383        .collect();
384
385    // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
386    // In debuginfo, these will correspond to the beginning (UNRESUMED) or end
387    // (RETURNED, POISONED) of the function.
388    let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
389    let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = IndexVec::with_capacity(
390        CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
391    );
392    variant_source_info.extend([
393        SourceInfo::outermost(body_span.shrink_to_lo()),
394        SourceInfo::outermost(body_span.shrink_to_hi()),
395        SourceInfo::outermost(body_span.shrink_to_hi()),
396    ]);
397
398    // Simple map from new to old indices to avoid repeatedly counting bits.
399    let reverse_local_map: IndexVec<CoroutineSavedLocal, Local> = saved_locals.iter().collect();
400
401    // Build the coroutine variant field list.
402    // Create a map from local indices to coroutine struct indices.
403    let mut variant_fields: IndexVec<VariantIdx, _> = IndexVec::from_elem_n(
404        IndexVec::new(),
405        CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
406    );
407    let mut remap = IndexVec::from_elem_n(None, saved_locals.domain_size());
408    for (live_locals, &source_info_at_suspension_point, (variant_index, fields)) in izip!(
409        &live_locals_at_suspension_points,
410        &source_info_at_suspension_points,
411        variant_fields.iter_enumerated_mut().skip(CoroutineArgs::RESERVED_VARIANTS)
412    ) {
413        *fields = live_locals.iter().collect();
414        for (idx, &saved_local) in fields.iter_enumerated() {
415            // Note that if a field is included in multiple variants, we will
416            // just use the first one here. That's fine; fields do not move
417            // around inside coroutines, so it doesn't matter which variant
418            // index we access them by.
419            remap[reverse_local_map[saved_local]] = Some((tys[saved_local].ty, variant_index, idx));
420        }
421        variant_source_info.push(source_info_at_suspension_point);
422    }
423    debug!(?variant_fields);
424    debug!(?storage_conflicts);
425
426    for var in &body.var_debug_info {
427        let VarDebugInfoContents::Place(place) = &var.value else { continue };
428        let Some(local) = place.as_local() else { continue };
429        let Some(&Some((_, variant, field))) = remap.get(local) else {
430            continue;
431        };
432
433        let saved_local: CoroutineSavedLocal = variant_fields[variant][field];
434        tys[saved_local].debuginfo_name.get_or_insert(var.name);
435    }
436
437    let layout =
438        CoroutineLayout { field_tys: tys, variant_fields, variant_source_info, storage_conflicts };
439    debug!(?remap);
440    debug!(?layout);
441    debug!(?storage_liveness);
442
443    (remap, layout, storage_liveness)
444}
445
446#[instrument(level = "debug", skip(tcx), ret)]
447pub(crate) fn mir_coroutine_witnesses<'tcx>(
448    tcx: TyCtxt<'tcx>,
449    def_id: LocalDefId,
450) -> Option<CoroutineLayout<'tcx>> {
451    let (body, _) = tcx.mir_promoted(def_id);
452    let body = body.borrow();
453    let body = &*body;
454
455    // The first argument is the coroutine type passed by value
456    let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
457
458    let movable = match *coroutine_ty.kind() {
459        ty::Coroutine(def_id, _) => tcx.coroutine_movability(def_id) == hir::Movability::Movable,
460        ty::Error(_) => return None,
461        _ => span_bug!(body.span, "unexpected coroutine type {}", coroutine_ty),
462    };
463
464    // The witness simply contains all locals live across suspend points.
465
466    let always_live_locals = always_storage_live_locals(body);
467    let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
468
469    // Extract locals which are live across suspension point into `layout`
470    // `remap` gives a mapping from local indices onto coroutine struct indices
471    // `storage_liveness` tells us which locals have live storage at suspension points
472    let (_, coroutine_layout, _) = compute_layout(liveness_info, body);
473
474    check_suspend_tys(tcx, &coroutine_layout, body);
475    check_field_tys_sized(tcx, &coroutine_layout, def_id);
476
477    Some(coroutine_layout)
478}
479
480fn check_field_tys_sized<'tcx>(
481    tcx: TyCtxt<'tcx>,
482    coroutine_layout: &CoroutineLayout<'tcx>,
483    def_id: LocalDefId,
484) {
485    // No need to check if unsized_fn_params is disabled,
486    // since we will error during typeck.
487    if !tcx.features().unsized_fn_params() {
488        return;
489    }
490
491    // FIXME(#132279): @lcnr believes that we may want to support coroutines
492    // whose `Sized`-ness relies on the hidden types of opaques defined by the
493    // parent function. In this case we'd have to be able to reveal only these
494    // opaques here.
495    let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
496    let param_env = tcx.param_env(def_id);
497
498    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
499    for field_ty in &coroutine_layout.field_tys {
500        ocx.register_bound(
501            ObligationCause::new(
502                field_ty.source_info.span,
503                def_id,
504                ObligationCauseCode::SizedCoroutineInterior(def_id),
505            ),
506            param_env,
507            field_ty.ty,
508            tcx.require_lang_item(LangItem::Sized, field_ty.source_info.span),
509        );
510    }
511
512    let errors = ocx.evaluate_obligations_error_on_ambiguity();
513    debug!(?errors);
514    if let TraitErrors::HasErrors(errors) = errors {
515        infcx.err_ctxt().report_fulfillment_errors(errors);
516    }
517}
518
519fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &CoroutineLayout<'tcx>, body: &Body<'tcx>) {
520    let mut linted_tys = FxHashSet::default();
521
522    for (variant, yield_source_info) in
523        layout.variant_fields.iter().zip(&layout.variant_source_info)
524    {
525        debug!(?variant);
526        for &local in variant {
527            let decl = &layout.field_tys[local];
528            debug!(?decl);
529
530            if !decl.ignore_for_traits && linted_tys.insert(decl.ty) {
531                let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else {
532                    continue;
533                };
534
535                check_must_not_suspend_ty(
536                    tcx,
537                    decl.ty,
538                    hir_id,
539                    SuspendCheckData {
540                        source_span: decl.source_info.span,
541                        yield_span: yield_source_info.span,
542                        plural_len: 1,
543                        ..Default::default()
544                    },
545                );
546            }
547        }
548    }
549}
550
551#[derive(Default)]
552struct SuspendCheckData<'a> {
553    source_span: Span,
554    yield_span: Span,
555    descr_pre: &'a str,
556    descr_post: &'a str,
557    plural_len: usize,
558}
559
560// Returns whether it emitted a diagnostic or not
561// Note that this fn and the proceeding one are based on the code
562// for creating must_use diagnostics
563//
564// Note that this technique was chosen over things like a `Suspend` marker trait
565// as it is simpler and has precedent in the compiler
566fn check_must_not_suspend_ty<'tcx>(
567    tcx: TyCtxt<'tcx>,
568    ty: Ty<'tcx>,
569    hir_id: hir::HirId,
570    data: SuspendCheckData<'_>,
571) -> bool {
572    if ty.is_unit() {
573        return false;
574    }
575
576    let plural_suffix = pluralize!(data.plural_len);
577
578    debug!("Checking must_not_suspend for {}", ty);
579
580    match *ty.kind() {
581        ty::Adt(_, args) if ty.is_box() => {
582            let boxed_ty = args.type_at(0);
583            let allocator_ty = args.type_at(1);
584            check_must_not_suspend_ty(
585                tcx,
586                boxed_ty,
587                hir_id,
588                SuspendCheckData { descr_pre: &format!("{}boxed ", data.descr_pre), ..data },
589            ) || check_must_not_suspend_ty(
590                tcx,
591                allocator_ty,
592                hir_id,
593                SuspendCheckData { descr_pre: &format!("{}allocator ", data.descr_pre), ..data },
594            )
595        }
596        // FIXME(sized_hierarchy): This should be replaced with a requirement that types in
597        // coroutines implement `const Sized`. Scalable vectors are temporarily `Sized` while
598        // `feature(sized_hierarchy)` is not fully implemented, but in practice are
599        // non-`const Sized` and so do not have a known size at compilation time. Layout computation
600        // for a coroutine containing scalable vectors would be incorrect.
601        ty::Adt(def, _) if def.repr().scalable() => {
602            tcx.dcx()
603                .span_err(data.source_span, "scalable vectors cannot be held over await points");
604            true
605        }
606        ty::Adt(def, _) => check_must_not_suspend_def(tcx, def.did(), hir_id, data),
607        // FIXME: support adding the attribute to TAITs
608        ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: def }, .. }) => {
609            let mut has_emitted = false;
610            for &(predicate, _) in tcx.explicit_item_bounds(def).skip_binder() {
611                // We only look at the `DefId`, so it is safe to skip the binder here.
612                if let ty::ClauseKind::Trait(ref poly_trait_predicate) =
613                    predicate.kind().skip_binder()
614                {
615                    let def_id = poly_trait_predicate.trait_ref.def_id;
616                    let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix);
617                    if check_must_not_suspend_def(
618                        tcx,
619                        def_id,
620                        hir_id,
621                        SuspendCheckData { descr_pre, ..data },
622                    ) {
623                        has_emitted = true;
624                        break;
625                    }
626                }
627            }
628            has_emitted
629        }
630        ty::Dynamic(binder, _) => {
631            let mut has_emitted = false;
632            for predicate in binder.iter() {
633                if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
634                    let def_id = trait_ref.def_id;
635                    let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post);
636                    if check_must_not_suspend_def(
637                        tcx,
638                        def_id,
639                        hir_id,
640                        SuspendCheckData { descr_post, ..data },
641                    ) {
642                        has_emitted = true;
643                        break;
644                    }
645                }
646            }
647            has_emitted
648        }
649        ty::Tuple(fields) => {
650            let mut has_emitted = false;
651            for (i, ty) in fields.iter().enumerate() {
652                let descr_post = &format!(" in tuple element {i}");
653                if check_must_not_suspend_ty(
654                    tcx,
655                    ty,
656                    hir_id,
657                    SuspendCheckData { descr_post, ..data },
658                ) {
659                    has_emitted = true;
660                }
661            }
662            has_emitted
663        }
664        ty::Array(ty, len) => {
665            let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
666            check_must_not_suspend_ty(
667                tcx,
668                ty,
669                hir_id,
670                SuspendCheckData {
671                    descr_pre,
672                    // FIXME(must_not_suspend): This is wrong. We should handle printing unevaluated consts.
673                    plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1,
674                    ..data
675                },
676            )
677        }
678        // If drop tracking is enabled, we want to look through references, since the referent
679        // may not be considered live across the await point.
680        ty::Ref(_region, ty, _mutability) => {
681            let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix);
682            check_must_not_suspend_ty(tcx, ty, hir_id, SuspendCheckData { descr_pre, ..data })
683        }
684        _ => false,
685    }
686}
687
688fn check_must_not_suspend_def(
689    tcx: TyCtxt<'_>,
690    def_id: DefId,
691    hir_id: hir::HirId,
692    data: SuspendCheckData<'_>,
693) -> bool {
694    if let Some(reason_str) = find_attr!(tcx, def_id, MustNotSupend {reason} => reason) {
695        let reason = reason_str.map(|s| MustNotSuspendReason { span: data.source_span, reason: s });
696        tcx.emit_node_span_lint(
697            rustc_session::lint::builtin::MUST_NOT_SUSPEND,
698            hir_id,
699            data.source_span,
700            MustNotSupend {
701                tcx,
702                yield_sp: data.yield_span,
703                reason,
704                src_sp: data.source_span,
705                pre: data.descr_pre,
706                def_id,
707                post: data.descr_post,
708            },
709        );
710
711        true
712    } else {
713        false
714    }
715}