1use std::fmt;
2use std::ops::{Deref, Range};
34use rustc_data_structures::intern::Interned;
5use rustc_data_structures::range_set::RangeSet;
6use rustc_macros::StableHash;
78use crate::layout::{FieldIdx, VariantIdx};
9use crate::{
10Align, BackendRepr, FieldsShape, Float, HasDataLayout, Integer, LayoutData, Niche, Numeric,
11PointeeInfo, Primitive, Size, Variants,
12};
1314// Explicitly import `Float` to avoid ambiguity with `Primitive::Float`.
1516#[derive(#[automatically_derived]impl<'a> ::core::marker::Copy for Layout<'a> { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'a>
::core::clone::TrivialClone for Layout<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for Layout<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _:
::core::clone::AssertParamIsClone<Interned<'a,
LayoutData<FieldIdx, VariantIdx>>>;
*self
}
}Clone, #[automatically_derived]impl<'a> ::core::marker::StructuralPartialEq for
Layout<'a> {
}
#[automatically_derived]impl<'a> ::core::cmp::PartialEq for Layout<'a> {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]impl<'a> ::core::cmp::Eq for Layout<'a> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _:
::core::cmp::AssertParamIsEq<Interned<'a,
LayoutData<FieldIdx, VariantIdx>>>;
}
}Eq, #[automatically_derived]impl<'a> ::core::hash::Hash for Layout<'a> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, const _: () =
{
impl<'a> ::rustc_data_structures::stable_hash::StableHash for
Layout<'a> {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
Layout(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
17#[cfg_attr(bootstrap, rustc_pass_by_value)]
18#[cfg_attr(not(bootstrap), lint::pass_by_value)]
19pub struct Layout<'a>(pub Interned<'a, LayoutData<FieldIdx, VariantIdx>>);
2021impl<'a> fmt::Debugfor Layout<'a> {
22fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23// See comment on `<LayoutData as Debug>::fmt` above.
24self.0.0.fmt(f)
25 }
26}
2728impl<'a> Dereffor Layout<'a> {
29type Target = &'a LayoutData<FieldIdx, VariantIdx>;
30fn deref(&self) -> &&'a LayoutData<FieldIdx, VariantIdx> {
31&self.0.0
32}
33}
3435impl<'a> Layout<'a> {
36pub fn fields(self) -> &'a FieldsShape<FieldIdx> {
37&self.0.0.fields
38 }
3940pub fn variants(self) -> &'a Variants<FieldIdx, VariantIdx> {
41&self.0.0.variants
42 }
4344pub fn backend_repr(self) -> BackendRepr {
45self.0.0.backend_repr
46 }
4748pub fn largest_niche(self) -> Option<Niche> {
49self.0.0.largest_niche
50 }
5152pub fn align(self) -> Align {
53self.0.0.align
54 }
5556pub fn size(self) -> Size {
57self.0.0.size
58 }
5960pub fn max_repr_align(self) -> Option<Align> {
61self.0.0.max_repr_align
62 }
6364pub fn unadjusted_abi_align(self) -> Align {
65self.0.0.unadjusted_abi_align
66 }
67}
6869/// The layout of a type, alongside the type itself.
70/// Provides various type traversal APIs (e.g., recursing into fields).
71///
72/// Note that the layout is NOT guaranteed to always be identical
73/// to that obtained from `layout_of(ty)`, as we need to produce
74/// layouts for which Rust types do not exist, such as enum variants
75/// or synthetic fields of enums (i.e., discriminants) and wide pointers.
76#[derive(#[automatically_derived]impl<'a, Ty: ::core::marker::Copy>
::core::marker::Copy for TyAndLayout<'a, Ty> {
}Copy, #[automatically_derived]impl<'a, Ty: ::core::clone::Clone>
::core::clone::Clone for TyAndLayout<'a, Ty> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
TyAndLayout {
ty: ::core::clone::Clone::clone(&self.ty),
layout: ::core::clone::Clone::clone(&self.layout),
}
}
}Clone, #[automatically_derived]impl<'a, Ty: ::core::cmp::PartialEq>
::core::marker::StructuralPartialEq for TyAndLayout<'a, Ty> {
}
#[automatically_derived]impl<'a, Ty: ::core::cmp::PartialEq>
::core::cmp::PartialEq for TyAndLayout<'a, Ty> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.ty == other.ty && self.layout == other.layout
}
}PartialEq, #[automatically_derived]impl<'a, Ty: ::core::cmp::Eq> ::core::cmp::Eq for
TyAndLayout<'a, Ty> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Ty>;
let _: ::core::cmp::AssertParamIsEq<Layout<'a>>;
}
}Eq, #[automatically_derived]impl<'a, Ty: ::core::hash::Hash> ::core::hash::Hash
for TyAndLayout<'a, Ty> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.ty, state);
::core::hash::Hash::hash(&self.layout, state)
}
}Hash, const _: () =
{
impl<'a, Ty> ::rustc_data_structures::stable_hash::StableHash for
TyAndLayout<'a, Ty> where
Ty: ::rustc_data_structures::stable_hash::StableHash {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
TyAndLayout { ty: ref __binding_0, layout: ref __binding_1 }
=> {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
77pub struct TyAndLayout<'a, Ty> {
78pub ty: Ty,
79pub layout: Layout<'a>,
80}
8182impl<'a, Ty: fmt::Display> fmt::Debugfor TyAndLayout<'a, Ty> {
83fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84// Print the type in a readable way, not its debug representation.
85f.debug_struct("TyAndLayout")
86 .field("ty", &format_args!("{0}", self.ty)format_args!("{}", self.ty))
87 .field("layout", &self.layout)
88 .finish()
89 }
90}
9192impl<'a, Ty> Dereffor TyAndLayout<'a, Ty> {
93type Target = &'a LayoutData<FieldIdx, VariantIdx>;
94fn deref(&self) -> &&'a LayoutData<FieldIdx, VariantIdx> {
95&self.layout.0.0
96}
97}
9899impl<'a, Ty> AsRef<LayoutData<FieldIdx, VariantIdx>> for TyAndLayout<'a, Ty> {
100fn as_ref(&self) -> &LayoutData<FieldIdx, VariantIdx> {
101&*self.layout.0.0
102}
103}
104105/// Trait that needs to be implemented by the higher-level type representation
106/// (e.g. `rustc_middle::ty::Ty`), to provide `rustc_target::abi` functionality.
107pub trait TyAbiInterface<'a, C>: Sized + std::fmt::Debug + std::fmt::Display {
108fn ty_and_layout_for_variant(
109 this: TyAndLayout<'a, Self>,
110 cx: &C,
111 variant_index: VariantIdx,
112 ) -> TyAndLayout<'a, Self>;
113fn ty_and_layout_field(this: TyAndLayout<'a, Self>, cx: &C, i: usize) -> TyAndLayout<'a, Self>;
114fn ty_and_layout_pointee_info_at(
115 this: TyAndLayout<'a, Self>,
116 cx: &C,
117 offset: Size,
118 ) -> Option<PointeeInfo>;
119fn is_adt(this: TyAndLayout<'a, Self>) -> bool;
120fn is_enum(this: TyAndLayout<'a, Self>) -> bool;
121fn is_never(this: TyAndLayout<'a, Self>) -> bool;
122fn is_tuple(this: TyAndLayout<'a, Self>) -> bool;
123fn is_unit(this: TyAndLayout<'a, Self>) -> bool;
124fn is_transparent(this: TyAndLayout<'a, Self>) -> bool;
125fn is_complex_number_lang_item(this: TyAndLayout<'a, Self>, cx: &C) -> bool;
126fn is_x87_f80_lang_item(this: TyAndLayout<'a, Self>, cx: &C) -> bool;
127fn is_scalable_vector(this: TyAndLayout<'a, Self>) -> bool;
128/// See [`TyAndLayout::pass_indirectly_in_non_rustic_abis`] for details.
129fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'a, Self>) -> bool;
130}
131132impl<'a, Ty> TyAndLayout<'a, Ty> {
133/// Synthetize a layout representing the variant-specific fields of an enum-like layout.
134 ///
135 /// Note that the resulting layout *does not* fully describes `self.ty` at that specific
136 /// variant: prefix fields (e.g. in coroutines) and tag information are lost.
137 ///
138 /// If you don't need type information about the variant's fields, prefer using
139 /// `self.layout.variants` directly.
140pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
141where
142Ty: TyAbiInterface<'a, C>,
143 {
144 Ty::ty_and_layout_for_variant(self, cx, variant_index)
145 }
146147pub fn field<C>(self, cx: &C, i: usize) -> Self
148where
149Ty: TyAbiInterface<'a, C>,
150 {
151 Ty::ty_and_layout_field(self, cx, i)
152 }
153154pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
155where
156Ty: TyAbiInterface<'a, C>,
157 {
158 Ty::ty_and_layout_pointee_info_at(self, cx, offset)
159 }
160161pub fn is_single_vector_element<C>(self, cx: &C, expected_size: Size) -> bool162where
163Ty: TyAbiInterface<'a, C>,
164 C: HasDataLayout,
165 {
166match self.backend_repr {
167 BackendRepr::SimdVector { .. } => self.size == expected_size,
168 BackendRepr::Memory { .. } => {
169if self.fields.count() == 1 && self.fields.offset(0).bytes() == 0 {
170self.field(cx, 0).is_single_vector_element(cx, expected_size)
171 } else {
172false
173}
174 }
175_ => false,
176 }
177 }
178179pub fn is_adt<C>(self) -> bool180where
181Ty: TyAbiInterface<'a, C>,
182 {
183 Ty::is_adt(self)
184 }
185186pub fn is_enum<C>(self) -> bool187where
188Ty: TyAbiInterface<'a, C>,
189 {
190 Ty::is_enum(self)
191 }
192193pub fn is_never<C>(self) -> bool194where
195Ty: TyAbiInterface<'a, C>,
196 {
197 Ty::is_never(self)
198 }
199200pub fn is_tuple<C>(self) -> bool201where
202Ty: TyAbiInterface<'a, C>,
203 {
204 Ty::is_tuple(self)
205 }
206207pub fn is_unit<C>(self) -> bool208where
209Ty: TyAbiInterface<'a, C>,
210 {
211 Ty::is_unit(self)
212 }
213214pub fn is_transparent<C>(self) -> bool215where
216Ty: TyAbiInterface<'a, C>,
217 {
218 Ty::is_transparent(self)
219 }
220221/// Returns `true` if this type needs to match the ABI of the C `_Complex` type. See
222 /// [`TyAndLayout::complex_number`] for details.
223pub fn is_complex_number<C>(self, cx: &C) -> bool224where
225Ty: TyAbiInterface<'a, C> + Copy,
226 {
227self.complex_number(cx).is_some()
228 }
229230pub fn is_scalable_vector<C>(self) -> bool231where
232Ty: TyAbiInterface<'a, C>,
233 {
234 Ty::is_scalable_vector(self)
235 }
236237/// Returns `true` if this type is the `x87_f80` lang item.
238 ///
239 /// Note that this function returns `false` for the `x87_f80_raw` lang item.
240pub fn is_x87_f80<C>(self, cx: &C) -> bool241where
242Ty: TyAbiInterface<'a, C> + Copy,
243 {
244// A 1-ZST is never x87_f80.
245Ty::is_x87_f80_lang_item(self.peel_transparent_wrappers_from_non_1zst(cx), cx)
246 }
247248/// If this method returns `true`, then this type should always have a `PassMode` of
249 /// `Indirect { mode: IndirectMode::Pointer, .. }` when being used as the argument type of a
250 /// function with a non-Rustic ABI (this is true for structs annotated with the
251 /// `#[rustc_pass_indirectly_in_non_rustic_abis]` attribute).
252 ///
253 /// This is used to replicate some of the behaviour of C array-to-pointer decay; however unlike
254 /// C any changes the caller makes to the passed value will not be reflected in the callee, so
255 /// the attribute is only useful for types where observing the value in the caller after the
256 /// function call isn't allowed (a.k.a. `va_list`).
257 ///
258 /// This function handles transparent types automatically.
259pub fn pass_indirectly_in_non_rustic_abis<C>(self, cx: &C) -> bool260where
261Ty: TyAbiInterface<'a, C> + Copy,
262 {
263// FIXME: Peeling the wrappers above would not work correctly if we are a 1-ZST. So we make
264 // `#[rustc_pass_indirectly_in_non_rustic_abis]` a NOP on 1-ZST. In the future,
265 // `non_1zst_field` should become `non_trivial_abi_field` and
266 // `#[rustc_pass_indirectly_in_non_rustic_abis]` should make a type have non-trivial ABI.
267if self.is_1zst() {
268return false;
269 }
270271let base = self.peel_transparent_wrappers_from_non_1zst(cx);
272 Ty::is_pass_indirectly_in_non_rustic_abis_flag_set(base)
273 }
274275/// Recursively peel away transparent wrappers, returning the inner value.
276 /// Will not peel anything if `self` is a 1-ZST! Callers need to either check
277 /// that the result is not a 1-ZST, or have separate logic for that.
278 ///
279 /// The return value is not `repr(transparent)` and/or does
280 /// not have a non-1zst field.
281pub fn peel_transparent_wrappers_from_non_1zst<C>(mut self, cx: &C) -> Self
282where
283Ty: TyAbiInterface<'a, C> + Copy,
284 {
285while self.is_transparent()
286 && let Some((_, field)) = self.non_1zst_field(cx)
287 {
288self = field;
289 }
290291self292 }
293294/// Finds the one field that is not a 1-ZST.
295 /// Returns `None` if there are multiple non-1-ZST fields or only 1-ZST-fields.
296pub fn non_1zst_field<C>(&self, cx: &C) -> Option<(FieldIdx, Self)>
297where
298Ty: TyAbiInterface<'a, C> + Copy,
299 {
300let mut found = None;
301for field_idx in 0..self.fields.count() {
302let field = self.field(cx, field_idx);
303if field.is_1zst() {
304continue;
305 }
306if found.is_some() {
307// More than one non-1-ZST field.
308return None;
309 }
310 found = Some((FieldIdx::from_usize(field_idx), field));
311 }
312found313 }
314315/// Finds the one field that is not a ZST.
316 /// Returns `None` if there are multiple non-ZST fields or only ZST-fields.
317 ///
318 /// Note that this function checks for ZSTs, not just 1-ZSTs.
319pub fn non_zst_field_ignore_alignment<C>(&self, cx: &C) -> Option<(FieldIdx, Self)>
320where
321Ty: TyAbiInterface<'a, C> + Copy,
322 {
323let mut found = None;
324for field_idx in 0..self.fields.count() {
325let field = self.field(cx, field_idx);
326if field.is_zst() {
327continue;
328 }
329if found.is_some() {
330// More than one non-ZST field.
331return None;
332 }
333 found = Some((FieldIdx::from_usize(field_idx), field));
334 }
335found336 }
337338/// If this type should match the ABI of the C `_Complex` type, returns the primitive that is
339 /// used for its components.
340 ///
341 /// This function only returns `Some(T)` for `core::num::Complex<T>` where `T` is
342 /// either a float or an integer. `repr(transparent)` wrapper types are automatically handled.
343pub fn complex_number<C>(&self, cx: &C) -> Option<Numeric>
344where
345Ty: TyAbiInterface<'a, C> + Copy,
346 {
347// We're checking for scalar repr below which excludes 1-ZST.
348let complex = self.peel_transparent_wrappers_from_non_1zst(cx);
349if !Ty::is_complex_number_lang_item(complex, cx) {
350return None;
351 }
352353let component = complex.field(cx, 0).peel_transparent_wrappers_from_non_1zst(cx);
354355if component.is_x87_f80(cx) {
356return Some(Numeric::Float(Float::X87F80));
357 }
358359let BackendRepr::Scalar(scalar) = component.backend_repr else {
360return None;
361 };
362363// Only Complex<{ float }> and Complex<{ integer }> have special layout.
364 //
365 // Explicitly spell out all the float types so that any new ones have to be added to
366 // one of the match branches.
367let primitive = scalar.primitive();
368match primitive {
369 Primitive::Bool => Some(Numeric::Int(Integer::I8, false)),
370 Primitive::Int(integer, is_signed) => Some(Numeric::Int(integer, is_signed)),
371 Primitive::Float(
372 float @ (Float::F16 | Float::F32 | Float::F64 | Float::F128 | Float::PpcF128),
373 ) => Some(Numeric::Float(float)),
374 Primitive::Float(Float::X87F80) => None, // x87_f80_raw has incorrect alignment.
375Primitive::Pointer(..) | Primitive::Float(Float::F16B) => None,
376 }
377 }
378379/// Returns `Some` if this type has the ABI of the C `_Complex` type with float components.
380 /// See [`TyAndLayout::complex_number`] for details.
381pub fn complex_float<C>(&self, cx: &C) -> Option<Float>
382where
383Ty: TyAbiInterface<'a, C> + Copy,
384 {
385match self.complex_number(cx) {
386Some(Numeric::Float(float)) => Some(float),
387_ => None,
388 }
389 }
390391/// Whether this type/layout has any padding that is dependent on a variant, i.e. has bytes that
392 /// are padding for some, but not all, valid values of this type.
393pub fn has_variant_dependent_padding<C>(&self, cx: &C) -> bool394where
395Ty: TyAbiInterface<'a, C> + Copy,
396 {
397match self.variants {
398 Variants::Multiple { .. } => true,
399 Variants::Empty => false,
400 Variants::Single { .. } => match &self.fields {
401 FieldsShape::Primitive | FieldsShape::Union(_) => false,
402 FieldsShape::Array { count, .. } => {
403*count > 0 && self.field(cx, 0).has_variant_dependent_padding(cx)
404 }
405 FieldsShape::Arbitrary { offsets, .. } => {
406 (0..offsets.len()).any(|i| self.field(cx, i).has_variant_dependent_padding(cx))
407 }
408 },
409 }
410 }
411412/// The ranges of bytes that are always ignored by the representation relation of this type.
413 ///
414 /// In other words, for any sequence of bytes, if we reset the these padding bytes to uninit,
415 /// then these two sequences of bytes represent the same value (or they are both invalid).
416 /// This is the "guaranteed" padding. There may be more bytes that are padding for some
417 /// but not all variants of this type; those are not included.
418 /// (E.g. `Option<i8>` has no guaranteed padding so the empty range set is returned, but its `None` value still has padding).
419pub fn variant_independent_padding_ranges<C>(&self, cx: &C) -> Vec<Range<Size>>
420where
421Ty: TyAbiInterface<'a, C> + Copy,
422 {
423let mut data = RangeSet::new();
424self.add_data_ranges(cx, Size::ZERO, &mut data);
425426// Find gaps between the data ranges.
427let mut uninit_ranges = Vec::new();
428let mut covered_until = Size::ZERO;
429for &(offset, size) in data.0.iter() {
430if offset > covered_until {
431 uninit_ranges.push(covered_until..offset);
432 }
433 covered_until = Ord::max(covered_until, offset + size);
434 }
435436// Add trailing padding.
437if self.size > covered_until {
438uninit_ranges.push(covered_until..self.size);
439 }
440441uninit_ranges442 }
443444/// The ranges of bytes that are ignored by the representation relation of this variant.
445 ///
446 /// The result does not include variant-independent padding.
447pub fn variant_dependent_padding_ranges<C>(
448&self,
449 cx: &C,
450 variant_index: VariantIdx,
451 ) -> Vec<Range<Size>>
452where
453Ty: TyAbiInterface<'a, C> + Copy,
454 {
455let Variants::Multiple { .. } = self.variants else {
456return Vec::new();
457 };
458459// Bytes that are data in some variant.
460let mut any = RangeSet::new();
461self.add_data_ranges(cx, Size::ZERO, &mut any);
462463// Bytes that are data in this variant.
464let mut this = RangeSet::new();
465466// The variants do not contain e.g. the discriminant or coroutine upvars.
467let FieldsShape::Arbitrary { offsets, in_memory_order: _ } = &self.fields else {
468{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("a multi-variant layout should have `Arbitrary` fields")));
}unreachable!("a multi-variant layout should have `Arbitrary` fields")469 };
470471// So add them explicitly.
472for (field, &offset) in offsets.iter_enumerated() {
473let field = self.field(cx, field.as_usize());
474 field.add_data_ranges(cx, offset, &mut this);
475 }
476477self.for_variant(cx, variant_index).add_data_ranges(cx, Size::ZERO, &mut this);
478479// Padding specific to this variant: data in some variant, but not in this one.
480any.difference(&this).0.iter().map(|&(offset, size)| offset..offset + size).collect()
481 }
482483/// Extend `out` with all ranges of bytes that *may* carry relevant data for values of this type.
484 /// For enums and unions there are offsets that are initialized for some
485 /// variants but not for others; those offset *will* get added to `out`.
486fn add_data_ranges<C>(self, cx: &C, base_offset: Size, out: &mut RangeSet<Size>)
487where
488Ty: TyAbiInterface<'a, C> + Copy,
489 {
490if self.is_zst() {
491return;
492 }
493494// Visit the fields of this value. For enum values the fields include the discriminant.
495match &self.fields {
496 FieldsShape::Primitive => {
497out.add_range(base_offset, self.size);
498 }
499&FieldsShape::Union(field_count) => {
500for field in 0..field_count.get() {
501let field = self.field(cx, field);
502 field.add_data_ranges(cx, base_offset, out);
503 }
504 }
505&FieldsShape::Array { stride, count } => {
506let elem = self.field(cx, 0);
507508// For scalars we know there is no padding between the elements,
509 // so the entire array is a single big data range.
510if elem.backend_repr.is_scalar() {
511out.add_range(base_offset, elem.size * count);
512 } else {
513// FIXME: this is really inefficient for large arrays.
514for idx in 0..count {
515 elem.add_data_ranges(cx, base_offset + idx * stride, out);
516 }
517 }
518 }
519 FieldsShape::Arbitrary { offsets, in_memory_order: _ } => {
520for (field, &offset) in offsets.iter_enumerated() {
521let field = self.field(cx, field.as_usize());
522 field.add_data_ranges(cx, base_offset + offset, out);
523 }
524 }
525 }
526527// Visit the fields of each variant.
528match &self.variants {
529 Variants::Empty | Variants::Single { index: _ } => { /* done */ }
530 Variants::Multiple { variants, .. } => {
531for variant in variants.indices() {
532let variant = self.for_variant(cx, variant);
533 variant.add_data_ranges(cx, base_offset, out);
534 }
535 }
536 }
537 }
538}