Skip to main content

rustc_abi/layout/
coroutine.rs

1//! Coroutine layout logic.
2//!
3//! When laying out coroutines, we divide our saved local fields into two
4//! categories: overlap-eligible and overlap-ineligible.
5//!
6//! Those fields which are ineligible for overlap go in a "prefix" at the
7//! beginning of the layout, and always have space reserved for them.
8//!
9//! Overlap-eligible fields are only assigned to one variant, so we lay
10//! those fields out for each variant and put them right after the
11//! prefix.
12//!
13//! Finally, in the layout details, we point to the fields from the
14//! variants they are assigned to. It is possible for some fields to be
15//! included in multiple variants. No field ever "moves around" in the
16//! layout; its offset is always the same.
17//!
18//! Also included in the layout are the upvars and the discriminant.
19//! These are included as fields on the "outer" layout; they are not part
20//! of any variant.
21
22use std::iter;
23
24use rustc_index::bit_set::{BitMatrix, DenseBitSet};
25use rustc_index::{Idx, IndexSlice, IndexVec};
26use tracing::{debug, trace};
27
28use crate::{
29    BackendRepr, FieldsShape, HasDataLayout, Integer, LayoutData, Primitive, ReprOptions, Scalar,
30    StructKind, TagEncoding, VariantLayout, Variants, WrappingRange,
31};
32
33/// Overlap eligibility and variant assignment for each CoroutineSavedLocal.
34#[derive(#[automatically_derived]
impl<VariantIdx: ::core::clone::Clone, FieldIdx: ::core::clone::Clone>
    ::core::clone::Clone for SavedLocalEligibility<VariantIdx, FieldIdx> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Unassigned => Self::Unassigned,
            Self::Assigned(__self_0) =>
                Self::Assigned(::core::clone::Clone::clone(__self_0)),
            Self::Ineligible(__self_0) =>
                Self::Ineligible(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl<VariantIdx: ::core::fmt::Debug, FieldIdx: ::core::fmt::Debug>
    ::core::fmt::Debug for SavedLocalEligibility<VariantIdx, FieldIdx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Unassigned =>
                ::core::fmt::Formatter::write_str(f, "Unassigned"),
            Self::Assigned(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Assigned", &__self_0),
            Self::Ineligible(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Ineligible", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<VariantIdx: ::core::cmp::PartialEq, FieldIdx: ::core::cmp::PartialEq>
    ::core::marker::StructuralPartialEq for
    SavedLocalEligibility<VariantIdx, FieldIdx> {
}
#[automatically_derived]
impl<VariantIdx: ::core::cmp::PartialEq, FieldIdx: ::core::cmp::PartialEq>
    ::core::cmp::PartialEq for SavedLocalEligibility<VariantIdx, FieldIdx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Assigned(__self_0), Self::Assigned(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Ineligible(__self_0), Self::Ineligible(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
35enum SavedLocalEligibility<VariantIdx, FieldIdx> {
36    Unassigned,
37    Assigned(VariantIdx),
38    Ineligible(Option<FieldIdx>),
39}
40
41/// Compute the eligibility and assignment of each local.
42fn coroutine_saved_local_eligibility<VariantIdx: Idx, FieldIdx: Idx, LocalIdx: Idx>(
43    nb_locals: usize,
44    variant_fields: &IndexSlice<VariantIdx, IndexVec<FieldIdx, LocalIdx>>,
45    storage_conflicts: &BitMatrix<LocalIdx, LocalIdx>,
46) -> (DenseBitSet<LocalIdx>, IndexVec<LocalIdx, SavedLocalEligibility<VariantIdx, FieldIdx>>) {
47    use SavedLocalEligibility::*;
48
49    let mut assignments: IndexVec<LocalIdx, _> = IndexVec::from_elem_n(Unassigned, nb_locals);
50
51    // The saved locals not eligible for overlap. These will get
52    // "promoted" to the prefix of our coroutine.
53    let mut ineligible_locals = DenseBitSet::new_empty(nb_locals);
54
55    // Figure out which of our saved locals are fields in only
56    // one variant. The rest are deemed ineligible for overlap.
57    for (variant_index, fields) in variant_fields.iter_enumerated() {
58        for local in fields {
59            match assignments[*local] {
60                Unassigned => {
61                    assignments[*local] = Assigned(variant_index);
62                }
63                Assigned(idx) => {
64                    // We've already seen this local at another suspension
65                    // point, so it is no longer a candidate.
66                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout/coroutine.rs:66",
                        "rustc_abi::layout::coroutine", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout/coroutine.rs"),
                        ::tracing_core::__macro_support::Option::Some(66u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout::coroutine"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("removing local {0:?} in >1 variant ({1:?}, {2:?})",
                                                    local, variant_index, idx) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(
67                        "removing local {:?} in >1 variant ({:?}, {:?})",
68                        local, variant_index, idx
69                    );
70                    ineligible_locals.insert(*local);
71                    assignments[*local] = Ineligible(None);
72                }
73                Ineligible(_) => {}
74            }
75        }
76    }
77
78    // Next, check every pair of eligible locals to see if they
79    // conflict.
80    for local_a in storage_conflicts.rows() {
81        let conflicts_a = storage_conflicts.count(local_a);
82        if ineligible_locals.contains(local_a) {
83            continue;
84        }
85
86        for local_b in storage_conflicts.iter(local_a) {
87            // local_a and local_b are storage live at the same time, therefore they
88            // cannot overlap in the coroutine layout. The only way to guarantee
89            // this is if they are in the same variant, or one is ineligible
90            // (which means it is stored in every variant).
91            if ineligible_locals.contains(local_b) || assignments[local_a] == assignments[local_b] {
92                continue;
93            }
94
95            // If they conflict, we will choose one to make ineligible.
96            // This is not always optimal; it's just a greedy heuristic that
97            // seems to produce good results most of the time.
98            let conflicts_b = storage_conflicts.count(local_b);
99            let (remove, other) =
100                if conflicts_a > conflicts_b { (local_a, local_b) } else { (local_b, local_a) };
101            ineligible_locals.insert(remove);
102            assignments[remove] = Ineligible(None);
103            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout/coroutine.rs:103",
                        "rustc_abi::layout::coroutine", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout/coroutine.rs"),
                        ::tracing_core::__macro_support::Option::Some(103u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout::coroutine"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("removing local {0:?} due to conflict with {1:?}",
                                                    remove, other) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("removing local {:?} due to conflict with {:?}", remove, other);
104        }
105    }
106
107    // Count the number of variants in use. If only one of them, then it is
108    // impossible to overlap any locals in our layout. In this case it's
109    // always better to make the remaining locals ineligible, so we can
110    // lay them out with the other locals in the prefix and eliminate
111    // unnecessary padding bytes.
112    {
113        let mut used_variants = DenseBitSet::new_empty(variant_fields.len());
114        for assignment in &assignments {
115            if let Assigned(idx) = assignment {
116                used_variants.insert(*idx);
117            }
118        }
119        if used_variants.count() < 2 {
120            for assignment in assignments.iter_mut() {
121                *assignment = Ineligible(None);
122            }
123            ineligible_locals.insert_all();
124        }
125    }
126
127    // Write down the order of our locals that will be promoted to the prefix.
128    {
129        for (idx, local) in ineligible_locals.iter().enumerate() {
130            assignments[local] = Ineligible(Some(FieldIdx::new(idx)));
131        }
132    }
133    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout/coroutine.rs:133",
                        "rustc_abi::layout::coroutine", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout/coroutine.rs"),
                        ::tracing_core::__macro_support::Option::Some(133u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout::coroutine"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coroutine saved local assignments: {0:?}",
                                                    assignments) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("coroutine saved local assignments: {:?}", assignments);
134
135    (ineligible_locals, assignments)
136}
137
138/// Compute the full coroutine layout.
139pub(super) fn layout<'a, F, VariantIdx, FieldIdx, LocalIdx>(
140    calc: &super::LayoutCalculator<impl HasDataLayout>,
141    local_layouts: &IndexSlice<LocalIdx, F>,
142    mut prefix_layouts: IndexVec<FieldIdx, F>,
143    variant_fields: &IndexSlice<VariantIdx, IndexVec<FieldIdx, LocalIdx>>,
144    storage_conflicts: &BitMatrix<LocalIdx, LocalIdx>,
145    tag_to_layout: impl Fn(Scalar) -> F,
146) -> super::LayoutCalculatorResult<FieldIdx, VariantIdx, F>
147where
148    F: core::ops::Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + core::fmt::Debug + Copy,
149    VariantIdx: Idx,
150    FieldIdx: Idx,
151    LocalIdx: Idx,
152{
153    use SavedLocalEligibility::*;
154
155    let (ineligible_locals, assignments) =
156        coroutine_saved_local_eligibility(local_layouts.len(), variant_fields, storage_conflicts);
157
158    // Build a prefix layout, including "promoting" all ineligible
159    // locals as part of the prefix. We compute the layout of all of
160    // these fields at once to get optimal packing.
161    let tag_index = prefix_layouts.next_index();
162
163    // `variant_fields` already accounts for the reserved variants, so no need to add them.
164    let max_discr = (variant_fields.len() - 1) as u128;
165    let discr_int = Integer::fit_unsigned(max_discr);
166    let tag = Scalar::Initialized {
167        value: Primitive::Int(discr_int, /* signed = */ false),
168        valid_range: WrappingRange { start: 0, end: max_discr },
169    };
170
171    let promoted_layouts = ineligible_locals.iter().map(|local| local_layouts[local]);
172    prefix_layouts.push(tag_to_layout(tag));
173    prefix_layouts.extend(promoted_layouts);
174    let prefix = calc.layout_of_univariant(
175        &prefix_layouts,
176        &ReprOptions::default(),
177        StructKind::AlwaysSized,
178    )?;
179
180    let (prefix_size, prefix_align) = (prefix.size, prefix.align);
181
182    // Split the prefix layout into the "outer" fields (upvars and
183    // discriminant) and the "promoted" fields. Promoted fields will
184    // get included in each variant that requested them in
185    // CoroutineLayout.
186    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout/coroutine.rs:186",
                        "rustc_abi::layout::coroutine", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_abi/src/layout/coroutine.rs"),
                        ::tracing_core::__macro_support::Option::Some(186u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_abi::layout::coroutine"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("prefix = {0:#?}",
                                                    prefix) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("prefix = {:#?}", prefix);
187    let (outer_fields, promoted_offsets, promoted_memory_index) = match prefix.fields {
188        FieldsShape::Arbitrary { mut offsets, in_memory_order } => {
189            // "a" (`0..b_start`) and "b" (`b_start..`) correspond to
190            // "outer" and "promoted" fields respectively.
191            let b_start = tag_index.plus(1);
192            let offsets_b = IndexVec::from_raw(offsets.raw.split_off(b_start.index()));
193            let offsets_a = offsets;
194
195            // Disentangle the "a" and "b" components of `in_memory_order`
196            // by preserving the order but keeping only one disjoint "half" each.
197            // FIXME(eddyb) build a better abstraction for permutations, if possible.
198            let mut in_memory_order_a = IndexVec::<u32, FieldIdx>::new();
199            let mut in_memory_order_b = IndexVec::<u32, FieldIdx>::new();
200            for i in in_memory_order {
201                if let Some(j) = i.index().checked_sub(b_start.index()) {
202                    in_memory_order_b.push(FieldIdx::new(j));
203                } else {
204                    in_memory_order_a.push(i);
205                }
206            }
207
208            let outer_fields =
209                FieldsShape::Arbitrary { offsets: offsets_a, in_memory_order: in_memory_order_a };
210            (outer_fields, offsets_b, in_memory_order_b.invert_bijective_mapping())
211        }
212        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
213    };
214
215    let mut size = prefix.size;
216    let mut align = prefix.align;
217    let variants = variant_fields
218        .iter_enumerated()
219        .map(|(index, variant_fields)| {
220            // Only include overlap-eligible fields when we compute our variant layout.
221            let variant_only_tys = variant_fields
222                .iter()
223                .filter(|local| match assignments[**local] {
224                    Unassigned => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
225                    Assigned(v) if v == index => true,
226                    Assigned(_) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("assignment does not match variant")));
}unreachable!("assignment does not match variant"),
227                    Ineligible(_) => false,
228                })
229                .map(|local| local_layouts[*local]);
230
231            let mut variant = calc.layout_of_univariant(
232                &variant_only_tys.collect::<IndexVec<_, _>>(),
233                &ReprOptions::default(),
234                StructKind::Prefixed(prefix_size, prefix_align.abi),
235            )?;
236
237            let FieldsShape::Arbitrary { offsets, in_memory_order } = variant.fields else {
238                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
239            };
240
241            // Now, stitch the promoted and variant-only fields back together in
242            // the order they are mentioned by our CoroutineLayout.
243            // Because we only use some subset (that can differ between variants)
244            // of the promoted fields, we can't just pick those elements of the
245            // `promoted_memory_index` (as we'd end up with gaps).
246            // So instead, we build an "inverse memory_index", as if all of the
247            // promoted fields were being used, but leave the elements not in the
248            // subset as `invalid_field_idx`, which we can filter out later to
249            // obtain a valid (bijective) mapping.
250            let memory_index = in_memory_order.invert_bijective_mapping();
251            let invalid_field_idx = promoted_memory_index.len() + memory_index.len();
252            let mut combined_in_memory_order =
253                IndexVec::from_elem_n(FieldIdx::new(invalid_field_idx), invalid_field_idx);
254
255            let mut offsets_and_memory_index = iter::zip(offsets, memory_index);
256            let combined_offsets = variant_fields
257                .iter_enumerated()
258                .map(|(i, local)| {
259                    let (offset, memory_index) = match assignments[*local] {
260                        Unassigned => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
261                        Assigned(_) => {
262                            let (offset, memory_index) = offsets_and_memory_index.next().unwrap();
263                            (offset, promoted_memory_index.len() as u32 + memory_index)
264                        }
265                        Ineligible(field_idx) => {
266                            let field_idx = field_idx.unwrap();
267                            (promoted_offsets[field_idx], promoted_memory_index[field_idx])
268                        }
269                    };
270                    combined_in_memory_order[memory_index] = i;
271                    offset
272                })
273                .collect();
274
275            // Remove the unused slots to obtain the combined `in_memory_order`
276            // (also see previous comment).
277            combined_in_memory_order.raw.retain(|&i| i.index() != invalid_field_idx);
278
279            variant.fields = FieldsShape::Arbitrary {
280                offsets: combined_offsets,
281                in_memory_order: combined_in_memory_order,
282            };
283
284            size = size.max(variant.size);
285            align = align.max(variant.align);
286            Ok(VariantLayout::from_layout(variant))
287        })
288        .collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
289
290    size = size.align_to(align.abi);
291
292    let uninhabited = prefix.uninhabited || variants.iter().all(|v| v.is_uninhabited());
293    let abi = BackendRepr::Memory { sized: true };
294
295    Ok(LayoutData {
296        variants: Variants::Multiple {
297            tag,
298            tag_encoding: TagEncoding::Direct,
299            tag_field: tag_index,
300            variants,
301        },
302        fields: outer_fields,
303        backend_repr: abi,
304        // Suppress niches inside coroutines. If the niche is inside a field that is aliased (due to
305        // self-referentiality), getting the discriminant can cause aliasing violations.
306        // `UnsafeCell` blocks niches for the same reason, but we don't yet have `UnsafePinned` that
307        // would do the same for us here.
308        // See <https://github.com/rust-lang/rust/issues/63818>, <https://github.com/rust-lang/miri/issues/3780>.
309        // FIXME: Remove when <https://github.com/rust-lang/rust/issues/125735> is implemented and aliased coroutine fields are wrapped in `UnsafePinned`.
310        largest_niche: None,
311        uninhabited,
312        size,
313        align,
314        max_repr_align: None,
315        unadjusted_abi_align: align.abi,
316        randomization_seed: Default::default(),
317    })
318}