1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::Integer::*;
12 pub use self::Primitive::*;
17 use std::ops::{Add, Deref, Sub, Mul, AddAssign, Range, RangeInclusive};
19 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
20 use rustc_serialize::{Decodable, Decoder};
24 /// Parsed [Data layout](http://llvm.org/docs/LangRef.html#data-layout)
25 /// for a target, which contains everything needed to compute layouts.
26 pub struct TargetDataLayout {
28 pub i1_align: AbiAndPrefAlign,
29 pub i8_align: AbiAndPrefAlign,
30 pub i16_align: AbiAndPrefAlign,
31 pub i32_align: AbiAndPrefAlign,
32 pub i64_align: AbiAndPrefAlign,
33 pub i128_align: AbiAndPrefAlign,
34 pub f32_align: AbiAndPrefAlign,
35 pub f64_align: AbiAndPrefAlign,
36 pub pointer_size: Size,
37 pub pointer_align: AbiAndPrefAlign,
38 pub aggregate_align: AbiAndPrefAlign,
40 /// Alignments for vector types.
41 pub vector_align: Vec<(Size, AbiAndPrefAlign)>,
43 pub instruction_address_space: u32,
46 impl Default for TargetDataLayout {
47 /// Creates an instance of `TargetDataLayout`.
48 fn default() -> TargetDataLayout {
49 let align = |bits| Align::from_bits(bits).unwrap();
52 i1_align: AbiAndPrefAlign::new(align(8)),
53 i8_align: AbiAndPrefAlign::new(align(8)),
54 i16_align: AbiAndPrefAlign::new(align(16)),
55 i32_align: AbiAndPrefAlign::new(align(32)),
56 i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
57 i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
58 f32_align: AbiAndPrefAlign::new(align(32)),
59 f64_align: AbiAndPrefAlign::new(align(64)),
60 pointer_size: Size::from_bits(64),
61 pointer_align: AbiAndPrefAlign::new(align(64)),
62 aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) },
64 (Size::from_bits(64), AbiAndPrefAlign::new(align(64))),
65 (Size::from_bits(128), AbiAndPrefAlign::new(align(128))),
67 instruction_address_space: 0,
72 impl TargetDataLayout {
73 pub fn parse(target: &Target) -> Result<TargetDataLayout, String> {
74 // Parse an address space index from a string.
75 let parse_address_space = |s: &str, cause: &str| {
76 s.parse::<u32>().map_err(|err| {
77 format!("invalid address space `{}` for `{}` in \"data-layout\": {}",
82 // Parse a bit count from a string.
83 let parse_bits = |s: &str, kind: &str, cause: &str| {
84 s.parse::<u64>().map_err(|err| {
85 format!("invalid {} `{}` for `{}` in \"data-layout\": {}",
90 // Parse a size string.
91 let size = |s: &str, cause: &str| {
92 parse_bits(s, "size", cause).map(Size::from_bits)
95 // Parse an alignment string.
96 let align = |s: &[&str], cause: &str| {
98 return Err(format!("missing alignment for `{}` in \"data-layout\"", cause));
100 let align_from_bits = |bits| {
101 Align::from_bits(bits).map_err(|err| {
102 format!("invalid alignment for `{}` in \"data-layout\": {}",
106 let abi = parse_bits(s[0], "alignment", cause)?;
107 let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?;
109 abi: align_from_bits(abi)?,
110 pref: align_from_bits(pref)?,
114 let mut dl = TargetDataLayout::default();
115 let mut i128_align_src = 64;
116 for spec in target.data_layout.split('-') {
117 match spec.split(':').collect::<Vec<_>>()[..] {
118 ["e"] => dl.endian = Endian::Little,
119 ["E"] => dl.endian = Endian::Big,
120 [p] if p.starts_with("P") => {
121 dl.instruction_address_space = parse_address_space(&p[1..], "P")?
123 ["a", ref a..] => dl.aggregate_align = align(a, "a")?,
124 ["f32", ref a..] => dl.f32_align = align(a, "f32")?,
125 ["f64", ref a..] => dl.f64_align = align(a, "f64")?,
126 [p @ "p", s, ref a..] | [p @ "p0", s, ref a..] => {
127 dl.pointer_size = size(s, p)?;
128 dl.pointer_align = align(a, p)?;
130 [s, ref a..] if s.starts_with("i") => {
131 let bits = match s[1..].parse::<u64>() {
134 size(&s[1..], "i")?; // For the user error.
138 let a = align(a, s)?;
140 1 => dl.i1_align = a,
141 8 => dl.i8_align = a,
142 16 => dl.i16_align = a,
143 32 => dl.i32_align = a,
144 64 => dl.i64_align = a,
147 if bits >= i128_align_src && bits <= 128 {
148 // Default alignment for i128 is decided by taking the alignment of
149 // largest-sized i{64...128}.
150 i128_align_src = bits;
154 [s, ref a..] if s.starts_with("v") => {
155 let v_size = size(&s[1..], "v")?;
156 let a = align(a, s)?;
157 if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) {
161 // No existing entry, add a new one.
162 dl.vector_align.push((v_size, a));
164 _ => {} // Ignore everything else.
168 // Perform consistency checks against the Target information.
169 let endian_str = match dl.endian {
170 Endian::Little => "little",
173 if endian_str != target.target_endian {
174 return Err(format!("inconsistent target specification: \"data-layout\" claims \
175 architecture is {}-endian, while \"target-endian\" is `{}`",
176 endian_str, target.target_endian));
179 if dl.pointer_size.bits().to_string() != target.target_pointer_width {
180 return Err(format!("inconsistent target specification: \"data-layout\" claims \
181 pointers are {}-bit, while \"target-pointer-width\" is `{}`",
182 dl.pointer_size.bits(), target.target_pointer_width));
188 /// Return exclusive upper bound on object size.
190 /// The theoretical maximum object size is defined as the maximum positive `isize` value.
191 /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly
192 /// index every address within an object along with one byte past the end, along with allowing
193 /// `isize` to store the difference between any two pointers into an object.
195 /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer
196 /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is
197 /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable
198 /// address space on 64-bit ARMv8 and x86_64.
199 pub fn obj_size_bound(&self) -> u64 {
200 match self.pointer_size.bits() {
204 bits => panic!("obj_size_bound: unknown pointer bit size {}", bits)
208 pub fn ptr_sized_integer(&self) -> Integer {
209 match self.pointer_size.bits() {
213 bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits)
217 pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign {
218 for &(size, align) in &self.vector_align {
219 if size == vec_size {
223 // Default to natural alignment, which is what LLVM does.
224 // That is, use the size, rounded up to a power of 2.
225 AbiAndPrefAlign::new(Align::from_bytes(vec_size.bytes().next_power_of_two()).unwrap())
229 pub trait HasDataLayout {
230 fn data_layout(&self) -> &TargetDataLayout;
233 impl HasDataLayout for TargetDataLayout {
234 fn data_layout(&self) -> &TargetDataLayout {
239 /// Endianness of the target, which must match cfg(target-endian).
240 #[derive(Copy, Clone, PartialEq)]
246 /// Size of a type in bytes.
247 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
253 pub const ZERO: Size = Self::from_bytes(0);
256 pub fn from_bits(bits: u64) -> Size {
257 // Avoid potential overflow from `bits + 7`.
258 Size::from_bytes(bits / 8 + ((bits % 8) + 7) / 8)
262 pub const fn from_bytes(bytes: u64) -> Size {
269 pub fn bytes(self) -> u64 {
274 pub fn bits(self) -> u64 {
275 self.bytes().checked_mul(8).unwrap_or_else(|| {
276 panic!("Size::bits: {} bytes in bits doesn't fit in u64", self.bytes())
281 pub fn align_to(self, align: Align) -> Size {
282 let mask = align.bytes() - 1;
283 Size::from_bytes((self.bytes() + mask) & !mask)
287 pub fn is_aligned(self, align: Align) -> bool {
288 let mask = align.bytes() - 1;
289 self.bytes() & mask == 0
293 pub fn checked_add<C: HasDataLayout>(self, offset: Size, cx: &C) -> Option<Size> {
294 let dl = cx.data_layout();
296 let bytes = self.bytes().checked_add(offset.bytes())?;
298 if bytes < dl.obj_size_bound() {
299 Some(Size::from_bytes(bytes))
306 pub fn checked_mul<C: HasDataLayout>(self, count: u64, cx: &C) -> Option<Size> {
307 let dl = cx.data_layout();
309 let bytes = self.bytes().checked_mul(count)?;
310 if bytes < dl.obj_size_bound() {
311 Some(Size::from_bytes(bytes))
318 // Panicking addition, subtraction and multiplication for convenience.
319 // Avoid during layout computation, return `LayoutError` instead.
324 fn add(self, other: Size) -> Size {
325 Size::from_bytes(self.bytes().checked_add(other.bytes()).unwrap_or_else(|| {
326 panic!("Size::add: {} + {} doesn't fit in u64", self.bytes(), other.bytes())
334 fn sub(self, other: Size) -> Size {
335 Size::from_bytes(self.bytes().checked_sub(other.bytes()).unwrap_or_else(|| {
336 panic!("Size::sub: {} - {} would result in negative size", self.bytes(), other.bytes())
341 impl Mul<Size> for u64 {
344 fn mul(self, size: Size) -> Size {
349 impl Mul<u64> for Size {
352 fn mul(self, count: u64) -> Size {
353 match self.bytes().checked_mul(count) {
354 Some(bytes) => Size::from_bytes(bytes),
356 panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count)
362 impl AddAssign for Size {
364 fn add_assign(&mut self, other: Size) {
365 *self = *self + other;
369 /// Alignment of a type in bytes (always a power of two).
370 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
376 pub fn from_bits(bits: u64) -> Result<Align, String> {
377 Align::from_bytes(Size::from_bits(bits).bytes())
380 pub fn from_bytes(align: u64) -> Result<Align, String> {
381 // Treat an alignment of 0 bytes like 1-byte alignment.
383 return Ok(Align { pow2: 0 });
386 let mut bytes = align;
387 let mut pow2: u8 = 0;
388 while (bytes & 1) == 0 {
393 return Err(format!("`{}` is not a power of 2", align));
396 return Err(format!("`{}` is too large", align));
402 pub fn bytes(self) -> u64 {
406 pub fn bits(self) -> u64 {
410 /// Compute the best alignment possible for the given offset
411 /// (the largest power of two that the offset is a multiple of).
413 /// NB: for an offset of `0`, this happens to return `2^64`.
414 pub fn max_for_offset(offset: Size) -> Align {
416 pow2: offset.bytes().trailing_zeros() as u8,
420 /// Lower the alignment, if necessary, such that the given offset
421 /// is aligned to it (the offset is a multiple of the alignment).
422 pub fn restrict_for_offset(self, offset: Size) -> Align {
423 self.min(Align::max_for_offset(offset))
427 /// A pair of aligments, ABI-mandated and preferred.
428 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
429 pub struct AbiAndPrefAlign {
434 impl AbiAndPrefAlign {
435 pub fn new(align: Align) -> AbiAndPrefAlign {
442 pub fn min(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
444 abi: self.abi.min(other.abi),
445 pref: self.pref.min(other.pref),
449 pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
451 abi: self.abi.max(other.abi),
452 pref: self.pref.max(other.pref),
457 /// Integers, also used for enum discriminants.
458 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
468 pub fn size(self) -> Size {
470 I8 => Size::from_bytes(1),
471 I16 => Size::from_bytes(2),
472 I32 => Size::from_bytes(4),
473 I64 => Size::from_bytes(8),
474 I128 => Size::from_bytes(16),
478 pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
479 let dl = cx.data_layout();
486 I128 => dl.i128_align,
490 /// Find the smallest Integer type which can represent the signed value.
491 pub fn fit_signed(x: i128) -> Integer {
493 -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8,
494 -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16,
495 -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32,
496 -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64,
501 /// Find the smallest Integer type which can represent the unsigned value.
502 pub fn fit_unsigned(x: u128) -> Integer {
504 0..=0x0000_0000_0000_00ff => I8,
505 0..=0x0000_0000_0000_ffff => I16,
506 0..=0x0000_0000_ffff_ffff => I32,
507 0..=0xffff_ffff_ffff_ffff => I64,
512 /// Find the smallest integer with the given alignment.
513 pub fn for_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Option<Integer> {
514 let dl = cx.data_layout();
516 for &candidate in &[I8, I16, I32, I64, I128] {
517 if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() {
518 return Some(candidate);
524 /// Find the largest integer with the given alignment or less.
525 pub fn approximate_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Integer {
526 let dl = cx.data_layout();
528 // FIXME(eddyb) maybe include I128 in the future, when it works everywhere.
529 for &candidate in &[I64, I32, I16] {
530 if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() {
539 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
546 impl fmt::Debug for FloatTy {
547 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
548 fmt::Display::fmt(self, f)
552 impl fmt::Display for FloatTy {
553 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
554 write!(f, "{}", self.ty_to_string())
559 pub fn ty_to_string(self) -> &'static str {
561 FloatTy::F32 => "f32",
562 FloatTy::F64 => "f64",
566 pub fn bit_width(self) -> usize {
574 /// Fundamental unit of memory access and layout.
575 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
577 /// The `bool` is the signedness of the `Integer` type.
579 /// One would think we would not care about such details this low down,
580 /// but some ABIs are described in terms of C types and ISAs where the
581 /// integer arithmetic is done on {sign,zero}-extended registers, e.g.
582 /// a negative integer passed by zero-extension will appear positive in
583 /// the callee, and most operations on it will produce the wrong values.
589 impl<'a, 'tcx> Primitive {
590 pub fn size<C: HasDataLayout>(self, cx: &C) -> Size {
591 let dl = cx.data_layout();
594 Int(i, _) => i.size(),
595 Float(FloatTy::F32) => Size::from_bits(32),
596 Float(FloatTy::F64) => Size::from_bits(64),
597 Pointer => dl.pointer_size
601 pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
602 let dl = cx.data_layout();
605 Int(i, _) => i.align(dl),
606 Float(FloatTy::F32) => dl.f32_align,
607 Float(FloatTy::F64) => dl.f64_align,
608 Pointer => dl.pointer_align
612 pub fn is_float(self) -> bool {
619 pub fn is_int(self) -> bool {
627 /// Information about one scalar component of a Rust type.
628 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
630 pub value: Primitive,
632 /// Inclusive wrap-around range of valid values, that is, if
633 /// start > end, it represents `start..=max_value()`,
634 /// followed by `0..=end`.
636 /// That is, for an i8 primitive, a range of `254..=2` means following
639 /// 254 (-2), 255 (-1), 0, 1, 2
641 /// This is intended specifically to mirror LLVM’s `!range` metadata,
643 // FIXME(eddyb) always use the shortest range, e.g. by finding
644 // the largest space between two consecutive valid values and
645 // taking everything else as the (shortest) valid range.
646 pub valid_range: RangeInclusive<u128>,
650 pub fn is_bool(&self) -> bool {
651 if let Int(I8, _) = self.value {
652 self.valid_range == (0..=1)
658 /// Returns the valid range as a `x..y` range.
660 /// If `x` and `y` are equal, the range is full, not empty.
661 pub fn valid_range_exclusive<C: HasDataLayout>(&self, cx: &C) -> Range<u128> {
662 // For a (max) value of -1, max will be `-1 as usize`, which overflows.
663 // However, that is fine here (it would still represent the full range),
664 // i.e., if the range is everything.
665 let bits = self.value.size(cx).bits();
666 assert!(bits <= 128);
667 let mask = !0u128 >> (128 - bits);
668 let start = *self.valid_range.start();
669 let end = *self.valid_range.end();
670 assert_eq!(start, start & mask);
671 assert_eq!(end, end & mask);
672 start..(end.wrapping_add(1) & mask)
676 /// Describes how the fields of a type are located in memory.
677 #[derive(PartialEq, Eq, Hash, Debug)]
678 pub enum FieldPlacement {
679 /// All fields start at no offset. The `usize` is the field count.
681 /// In the case of primitives the number of fields is `0`.
684 /// Array/vector-like placement, with all fields of identical types.
690 /// Struct-like placement, with precomputed offsets.
692 /// Fields are guaranteed to not overlap, but note that gaps
693 /// before, between and after all the fields are NOT always
694 /// padding, and as such their contents may not be discarded.
695 /// For example, enum variants leave a gap at the start,
696 /// where the discriminant field in the enum layout goes.
698 /// Offsets for the first byte of each field,
699 /// ordered to match the source definition order.
700 /// This vector does not go in increasing order.
701 // FIXME(eddyb) use small vector optimization for the common case.
704 /// Maps source order field indices to memory order indices,
705 /// depending how fields were permuted.
706 // FIXME(camlorn) also consider small vector optimization here.
707 memory_index: Vec<u32>
711 impl FieldPlacement {
712 pub fn count(&self) -> usize {
714 FieldPlacement::Union(count) => count,
715 FieldPlacement::Array { count, .. } => {
716 let usize_count = count as usize;
717 assert_eq!(usize_count as u64, count);
720 FieldPlacement::Arbitrary { ref offsets, .. } => offsets.len()
724 pub fn offset(&self, i: usize) -> Size {
726 FieldPlacement::Union(_) => Size::ZERO,
727 FieldPlacement::Array { stride, count } => {
732 FieldPlacement::Arbitrary { ref offsets, .. } => offsets[i]
736 pub fn memory_index(&self, i: usize) -> usize {
738 FieldPlacement::Union(_) |
739 FieldPlacement::Array { .. } => i,
740 FieldPlacement::Arbitrary { ref memory_index, .. } => {
741 let r = memory_index[i];
742 assert_eq!(r as usize as u32, r);
748 /// Get source indices of the fields by increasing offsets.
750 pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator<Item=usize>+'a {
751 let mut inverse_small = [0u8; 64];
752 let mut inverse_big = vec![];
753 let use_small = self.count() <= inverse_small.len();
755 // We have to write this logic twice in order to keep the array small.
756 if let FieldPlacement::Arbitrary { ref memory_index, .. } = *self {
758 for i in 0..self.count() {
759 inverse_small[memory_index[i] as usize] = i as u8;
762 inverse_big = vec![0; self.count()];
763 for i in 0..self.count() {
764 inverse_big[memory_index[i] as usize] = i as u32;
769 (0..self.count()).map(move |i| {
771 FieldPlacement::Union(_) |
772 FieldPlacement::Array { .. } => i,
773 FieldPlacement::Arbitrary { .. } => {
774 if use_small { inverse_small[i] as usize }
775 else { inverse_big[i] as usize }
782 /// Describes how values of the type are passed by target ABIs,
783 /// in terms of categories of C types there are ABI rules for.
784 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
788 ScalarPair(Scalar, Scalar),
794 /// If true, the size is exact, otherwise it's only a lower bound.
800 /// Returns true if the layout corresponds to an unsized type.
801 pub fn is_unsized(&self) -> bool {
805 Abi::ScalarPair(..) |
806 Abi::Vector { .. } => false,
807 Abi::Aggregate { sized } => !sized
811 /// Returns true if this is a single signed integer scalar
812 pub fn is_signed(&self) -> bool {
814 Abi::Scalar(ref scal) => match scal.value {
815 Primitive::Int(_, signed) => signed,
822 /// Returns true if this is an uninhabited type
823 pub fn is_uninhabited(&self) -> bool {
825 Abi::Uninhabited => true,
832 pub struct VariantIdx { .. }
835 #[derive(PartialEq, Eq, Hash, Debug)]
837 /// Single enum variants, structs/tuples, unions, and all non-ADTs.
842 /// General-case enums: for each case there is a struct, and they all have
843 /// all space reserved for the tag, and their first field starts
844 /// at a non-0 offset, after where the tag would go.
847 variants: IndexVec<VariantIdx, LayoutDetails>,
850 /// Multiple cases distinguished by a niche (values invalid for a type):
851 /// the variant `dataful_variant` contains a niche at an arbitrary
852 /// offset (field 0 of the enum), which for a variant with discriminant
853 /// `d` is set to `(d - niche_variants.start).wrapping_add(niche_start)`.
855 /// For example, `Option<(usize, &T)>` is represented such that
856 /// `None` has a null pointer for the second tuple field, and
857 /// `Some` is the identity function (with a non-null reference).
859 dataful_variant: VariantIdx,
860 niche_variants: RangeInclusive<VariantIdx>,
863 variants: IndexVec<VariantIdx, LayoutDetails>,
867 #[derive(PartialEq, Eq, Hash, Debug)]
868 pub struct LayoutDetails {
869 pub variants: Variants,
870 pub fields: FieldPlacement,
872 pub align: AbiAndPrefAlign,
877 pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
878 let size = scalar.value.size(cx);
879 let align = scalar.value.align(cx);
881 variants: Variants::Single { index: VariantIdx::new(0) },
882 fields: FieldPlacement::Union(0),
883 abi: Abi::Scalar(scalar),
890 /// The details of the layout of a type, alongside the type itself.
891 /// Provides various type traversal APIs (e.g. recursing into fields).
893 /// Note that the details are NOT guaranteed to always be identical
894 /// to those obtained from `layout_of(ty)`, as we need to produce
895 /// layouts for which Rust types do not exist, such as enum variants
896 /// or synthetic fields of enums (i.e. discriminants) and fat pointers.
897 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
898 pub struct TyLayout<'a, Ty> {
900 pub details: &'a LayoutDetails
903 impl<'a, Ty> Deref for TyLayout<'a, Ty> {
904 type Target = &'a LayoutDetails;
905 fn deref(&self) -> &&'a LayoutDetails {
914 fn layout_of(&self, ty: Self::Ty) -> Self::TyLayout;
917 pub trait TyLayoutMethods<'a, C: LayoutOf<Ty = Self>>: Sized {
919 this: TyLayout<'a, Self>,
921 variant_index: VariantIdx,
922 ) -> TyLayout<'a, Self>;
923 fn field(this: TyLayout<'a, Self>, cx: &C, i: usize) -> C::TyLayout;
926 impl<'a, Ty> TyLayout<'a, Ty> {
927 pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
928 where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> {
929 Ty::for_variant(self, cx, variant_index)
931 pub fn field<C>(self, cx: &C, i: usize) -> C::TyLayout
932 where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> {
933 Ty::field(self, cx, i)
937 impl<'a, Ty> TyLayout<'a, Ty> {
938 /// Returns true if the layout corresponds to an unsized type.
939 pub fn is_unsized(&self) -> bool {
940 self.abi.is_unsized()
943 /// Returns true if the type is a ZST and not unsized.
944 pub fn is_zst(&self) -> bool {
947 Abi::ScalarPair(..) |
948 Abi::Vector { .. } => false,
949 Abi::Uninhabited => self.size.bytes() == 0,
950 Abi::Aggregate { sized } => sized && self.size.bytes() == 0