]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/layout.rs
Auto merge of #47738 - nikomatsakis:issue-47139-master, r=arielb1
[rust.git] / src / librustc / ty / layout.rs
1 // Copyright 2016 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.
4 //
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.
10
11 pub use self::Integer::*;
12 pub use self::Primitive::*;
13
14 use session::{self, DataTypeKind, Session};
15 use ty::{self, Ty, TyCtxt, TypeFoldable, ReprOptions, ReprFlags};
16
17 use syntax::ast::{self, FloatTy, IntTy, UintTy};
18 use syntax::attr;
19 use syntax_pos::DUMMY_SP;
20
21 use std::cmp;
22 use std::fmt;
23 use std::i128;
24 use std::iter;
25 use std::mem;
26 use std::ops::{Add, Sub, Mul, AddAssign, Deref, RangeInclusive};
27
28 use ich::StableHashingContext;
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
30                                            StableHasherResult};
31
32 /// Parsed [Data layout](http://llvm.org/docs/LangRef.html#data-layout)
33 /// for a target, which contains everything needed to compute layouts.
34 pub struct TargetDataLayout {
35     pub endian: Endian,
36     pub i1_align: Align,
37     pub i8_align: Align,
38     pub i16_align: Align,
39     pub i32_align: Align,
40     pub i64_align: Align,
41     pub i128_align: Align,
42     pub f32_align: Align,
43     pub f64_align: Align,
44     pub pointer_size: Size,
45     pub pointer_align: Align,
46     pub aggregate_align: Align,
47
48     /// Alignments for vector types.
49     pub vector_align: Vec<(Size, Align)>
50 }
51
52 impl Default for TargetDataLayout {
53     /// Creates an instance of `TargetDataLayout`.
54     fn default() -> TargetDataLayout {
55         TargetDataLayout {
56             endian: Endian::Big,
57             i1_align: Align::from_bits(8, 8).unwrap(),
58             i8_align: Align::from_bits(8, 8).unwrap(),
59             i16_align: Align::from_bits(16, 16).unwrap(),
60             i32_align: Align::from_bits(32, 32).unwrap(),
61             i64_align: Align::from_bits(32, 64).unwrap(),
62             i128_align: Align::from_bits(32, 64).unwrap(),
63             f32_align: Align::from_bits(32, 32).unwrap(),
64             f64_align: Align::from_bits(64, 64).unwrap(),
65             pointer_size: Size::from_bits(64),
66             pointer_align: Align::from_bits(64, 64).unwrap(),
67             aggregate_align: Align::from_bits(0, 64).unwrap(),
68             vector_align: vec![
69                 (Size::from_bits(64), Align::from_bits(64, 64).unwrap()),
70                 (Size::from_bits(128), Align::from_bits(128, 128).unwrap())
71             ]
72         }
73     }
74 }
75
76 impl TargetDataLayout {
77     pub fn parse(sess: &Session) -> TargetDataLayout {
78         // Parse a bit count from a string.
79         let parse_bits = |s: &str, kind: &str, cause: &str| {
80             s.parse::<u64>().unwrap_or_else(|err| {
81                 sess.err(&format!("invalid {} `{}` for `{}` in \"data-layout\": {}",
82                                   kind, s, cause, err));
83                 0
84             })
85         };
86
87         // Parse a size string.
88         let size = |s: &str, cause: &str| {
89             Size::from_bits(parse_bits(s, "size", cause))
90         };
91
92         // Parse an alignment string.
93         let align = |s: &[&str], cause: &str| {
94             if s.is_empty() {
95                 sess.err(&format!("missing alignment for `{}` in \"data-layout\"", cause));
96             }
97             let abi = parse_bits(s[0], "alignment", cause);
98             let pref = s.get(1).map_or(abi, |pref| parse_bits(pref, "alignment", cause));
99             Align::from_bits(abi, pref).unwrap_or_else(|err| {
100                 sess.err(&format!("invalid alignment for `{}` in \"data-layout\": {}",
101                                   cause, err));
102                 Align::from_bits(8, 8).unwrap()
103             })
104         };
105
106         let mut dl = TargetDataLayout::default();
107         let mut i128_align_src = 64;
108         for spec in sess.target.target.data_layout.split("-") {
109             match &spec.split(":").collect::<Vec<_>>()[..] {
110                 &["e"] => dl.endian = Endian::Little,
111                 &["E"] => dl.endian = Endian::Big,
112                 &["a", ref a..] => dl.aggregate_align = align(a, "a"),
113                 &["f32", ref a..] => dl.f32_align = align(a, "f32"),
114                 &["f64", ref a..] => dl.f64_align = align(a, "f64"),
115                 &[p @ "p", s, ref a..] | &[p @ "p0", s, ref a..] => {
116                     dl.pointer_size = size(s, p);
117                     dl.pointer_align = align(a, p);
118                 }
119                 &[s, ref a..] if s.starts_with("i") => {
120                     let bits = match s[1..].parse::<u64>() {
121                         Ok(bits) => bits,
122                         Err(_) => {
123                             size(&s[1..], "i"); // For the user error.
124                             continue;
125                         }
126                     };
127                     let a = align(a, s);
128                     match bits {
129                         1 => dl.i1_align = a,
130                         8 => dl.i8_align = a,
131                         16 => dl.i16_align = a,
132                         32 => dl.i32_align = a,
133                         64 => dl.i64_align = a,
134                         _ => {}
135                     }
136                     if bits >= i128_align_src && bits <= 128 {
137                         // Default alignment for i128 is decided by taking the alignment of
138                         // largest-sized i{64...128}.
139                         i128_align_src = bits;
140                         dl.i128_align = a;
141                     }
142                 }
143                 &[s, ref a..] if s.starts_with("v") => {
144                     let v_size = size(&s[1..], "v");
145                     let a = align(a, s);
146                     if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) {
147                         v.1 = a;
148                         continue;
149                     }
150                     // No existing entry, add a new one.
151                     dl.vector_align.push((v_size, a));
152                 }
153                 _ => {} // Ignore everything else.
154             }
155         }
156
157         // Perform consistency checks against the Target information.
158         let endian_str = match dl.endian {
159             Endian::Little => "little",
160             Endian::Big => "big"
161         };
162         if endian_str != sess.target.target.target_endian {
163             sess.err(&format!("inconsistent target specification: \"data-layout\" claims \
164                                architecture is {}-endian, while \"target-endian\" is `{}`",
165                               endian_str, sess.target.target.target_endian));
166         }
167
168         if dl.pointer_size.bits().to_string() != sess.target.target.target_pointer_width {
169             sess.err(&format!("inconsistent target specification: \"data-layout\" claims \
170                                pointers are {}-bit, while \"target-pointer-width\" is `{}`",
171                               dl.pointer_size.bits(), sess.target.target.target_pointer_width));
172         }
173
174         dl
175     }
176
177     /// Return exclusive upper bound on object size.
178     ///
179     /// The theoretical maximum object size is defined as the maximum positive `isize` value.
180     /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly
181     /// index every address within an object along with one byte past the end, along with allowing
182     /// `isize` to store the difference between any two pointers into an object.
183     ///
184     /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer
185     /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is
186     /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable
187     /// address space on 64-bit ARMv8 and x86_64.
188     pub fn obj_size_bound(&self) -> u64 {
189         match self.pointer_size.bits() {
190             16 => 1 << 15,
191             32 => 1 << 31,
192             64 => 1 << 47,
193             bits => bug!("obj_size_bound: unknown pointer bit size {}", bits)
194         }
195     }
196
197     pub fn ptr_sized_integer(&self) -> Integer {
198         match self.pointer_size.bits() {
199             16 => I16,
200             32 => I32,
201             64 => I64,
202             bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits)
203         }
204     }
205
206     pub fn vector_align(&self, vec_size: Size) -> Align {
207         for &(size, align) in &self.vector_align {
208             if size == vec_size {
209                 return align;
210             }
211         }
212         // Default to natural alignment, which is what LLVM does.
213         // That is, use the size, rounded up to a power of 2.
214         let align = vec_size.bytes().next_power_of_two();
215         Align::from_bytes(align, align).unwrap()
216     }
217 }
218
219 pub trait HasDataLayout: Copy {
220     fn data_layout(&self) -> &TargetDataLayout;
221 }
222
223 impl<'a> HasDataLayout for &'a TargetDataLayout {
224     fn data_layout(&self) -> &TargetDataLayout {
225         self
226     }
227 }
228
229 /// Endianness of the target, which must match cfg(target-endian).
230 #[derive(Copy, Clone)]
231 pub enum Endian {
232     Little,
233     Big
234 }
235
236 /// Size of a type in bytes.
237 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
238 pub struct Size {
239     raw: u64
240 }
241
242 impl Size {
243     pub fn from_bits(bits: u64) -> Size {
244         // Avoid potential overflow from `bits + 7`.
245         Size::from_bytes(bits / 8 + ((bits % 8) + 7) / 8)
246     }
247
248     pub fn from_bytes(bytes: u64) -> Size {
249         if bytes >= (1 << 61) {
250             bug!("Size::from_bytes: {} bytes in bits doesn't fit in u64", bytes)
251         }
252         Size {
253             raw: bytes
254         }
255     }
256
257     pub fn bytes(self) -> u64 {
258         self.raw
259     }
260
261     pub fn bits(self) -> u64 {
262         self.bytes() * 8
263     }
264
265     pub fn abi_align(self, align: Align) -> Size {
266         let mask = align.abi() - 1;
267         Size::from_bytes((self.bytes() + mask) & !mask)
268     }
269
270     pub fn is_abi_aligned(self, align: Align) -> bool {
271         let mask = align.abi() - 1;
272         self.bytes() & mask == 0
273     }
274
275     pub fn checked_add<C: HasDataLayout>(self, offset: Size, cx: C) -> Option<Size> {
276         let dl = cx.data_layout();
277
278         // Each Size is less than dl.obj_size_bound(), so the sum is
279         // also less than 1 << 62 (and therefore can't overflow).
280         let bytes = self.bytes() + offset.bytes();
281
282         if bytes < dl.obj_size_bound() {
283             Some(Size::from_bytes(bytes))
284         } else {
285             None
286         }
287     }
288
289     pub fn checked_mul<C: HasDataLayout>(self, count: u64, cx: C) -> Option<Size> {
290         let dl = cx.data_layout();
291
292         match self.bytes().checked_mul(count) {
293             Some(bytes) if bytes < dl.obj_size_bound() => {
294                 Some(Size::from_bytes(bytes))
295             }
296             _ => None
297         }
298     }
299 }
300
301 // Panicking addition, subtraction and multiplication for convenience.
302 // Avoid during layout computation, return `LayoutError` instead.
303
304 impl Add for Size {
305     type Output = Size;
306     fn add(self, other: Size) -> Size {
307         // Each Size is less than 1 << 61, so the sum is
308         // less than 1 << 62 (and therefore can't overflow).
309         Size::from_bytes(self.bytes() + other.bytes())
310     }
311 }
312
313 impl Sub for Size {
314     type Output = Size;
315     fn sub(self, other: Size) -> Size {
316         // Each Size is less than 1 << 61, so an underflow
317         // would result in a value larger than 1 << 61,
318         // which Size::from_bytes will catch for us.
319         Size::from_bytes(self.bytes() - other.bytes())
320     }
321 }
322
323 impl Mul<u64> for Size {
324     type Output = Size;
325     fn mul(self, count: u64) -> Size {
326         match self.bytes().checked_mul(count) {
327             Some(bytes) => Size::from_bytes(bytes),
328             None => {
329                 bug!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count)
330             }
331         }
332     }
333 }
334
335 impl AddAssign for Size {
336     fn add_assign(&mut self, other: Size) {
337         *self = *self + other;
338     }
339 }
340
341 /// Alignment of a type in bytes, both ABI-mandated and preferred.
342 /// Each field is a power of two, giving the alignment a maximum
343 /// value of 2<sup>(2<sup>8</sup> - 1)</sup>, which is limited by LLVM to a i32, with
344 /// a maximum capacity of 2<sup>31</sup> - 1 or 2147483647.
345 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
346 pub struct Align {
347     abi: u8,
348     pref: u8,
349 }
350
351 impl Align {
352     pub fn from_bits(abi: u64, pref: u64) -> Result<Align, String> {
353         Align::from_bytes(Size::from_bits(abi).bytes(),
354                           Size::from_bits(pref).bytes())
355     }
356
357     pub fn from_bytes(abi: u64, pref: u64) -> Result<Align, String> {
358         let log2 = |align: u64| {
359             // Treat an alignment of 0 bytes like 1-byte alignment.
360             if align == 0 {
361                 return Ok(0);
362             }
363
364             let mut bytes = align;
365             let mut pow: u8 = 0;
366             while (bytes & 1) == 0 {
367                 pow += 1;
368                 bytes >>= 1;
369             }
370             if bytes != 1 {
371                 Err(format!("`{}` is not a power of 2", align))
372             } else if pow > 30 {
373                 Err(format!("`{}` is too large", align))
374             } else {
375                 Ok(pow)
376             }
377         };
378
379         Ok(Align {
380             abi: log2(abi)?,
381             pref: log2(pref)?,
382         })
383     }
384
385     pub fn abi(self) -> u64 {
386         1 << self.abi
387     }
388
389     pub fn pref(self) -> u64 {
390         1 << self.pref
391     }
392
393     pub fn abi_bits(self) -> u64 {
394         self.abi() * 8
395     }
396
397     pub fn pref_bits(self) -> u64 {
398         self.pref() * 8
399     }
400
401     pub fn min(self, other: Align) -> Align {
402         Align {
403             abi: cmp::min(self.abi, other.abi),
404             pref: cmp::min(self.pref, other.pref),
405         }
406     }
407
408     pub fn max(self, other: Align) -> Align {
409         Align {
410             abi: cmp::max(self.abi, other.abi),
411             pref: cmp::max(self.pref, other.pref),
412         }
413     }
414 }
415
416 /// Integers, also used for enum discriminants.
417 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
418 pub enum Integer {
419     I8,
420     I16,
421     I32,
422     I64,
423     I128,
424 }
425
426 impl<'a, 'tcx> Integer {
427     pub fn size(&self) -> Size {
428         match *self {
429             I8 => Size::from_bytes(1),
430             I16 => Size::from_bytes(2),
431             I32 => Size::from_bytes(4),
432             I64  => Size::from_bytes(8),
433             I128  => Size::from_bytes(16),
434         }
435     }
436
437     pub fn align<C: HasDataLayout>(&self, cx: C) -> Align {
438         let dl = cx.data_layout();
439
440         match *self {
441             I8 => dl.i8_align,
442             I16 => dl.i16_align,
443             I32 => dl.i32_align,
444             I64 => dl.i64_align,
445             I128 => dl.i128_align,
446         }
447     }
448
449     pub fn to_ty(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, signed: bool) -> Ty<'tcx> {
450         match (*self, signed) {
451             (I8, false) => tcx.types.u8,
452             (I16, false) => tcx.types.u16,
453             (I32, false) => tcx.types.u32,
454             (I64, false) => tcx.types.u64,
455             (I128, false) => tcx.types.u128,
456             (I8, true) => tcx.types.i8,
457             (I16, true) => tcx.types.i16,
458             (I32, true) => tcx.types.i32,
459             (I64, true) => tcx.types.i64,
460             (I128, true) => tcx.types.i128,
461         }
462     }
463
464     /// Find the smallest Integer type which can represent the signed value.
465     pub fn fit_signed(x: i128) -> Integer {
466         match x {
467             -0x0000_0000_0000_0080...0x0000_0000_0000_007f => I8,
468             -0x0000_0000_0000_8000...0x0000_0000_0000_7fff => I16,
469             -0x0000_0000_8000_0000...0x0000_0000_7fff_ffff => I32,
470             -0x8000_0000_0000_0000...0x7fff_ffff_ffff_ffff => I64,
471             _ => I128
472         }
473     }
474
475     /// Find the smallest Integer type which can represent the unsigned value.
476     pub fn fit_unsigned(x: u128) -> Integer {
477         match x {
478             0...0x0000_0000_0000_00ff => I8,
479             0...0x0000_0000_0000_ffff => I16,
480             0...0x0000_0000_ffff_ffff => I32,
481             0...0xffff_ffff_ffff_ffff => I64,
482             _ => I128,
483         }
484     }
485
486     /// Find the smallest integer with the given alignment.
487     pub fn for_abi_align<C: HasDataLayout>(cx: C, align: Align) -> Option<Integer> {
488         let dl = cx.data_layout();
489
490         let wanted = align.abi();
491         for &candidate in &[I8, I16, I32, I64, I128] {
492             if wanted == candidate.align(dl).abi() && wanted == candidate.size().bytes() {
493                 return Some(candidate);
494             }
495         }
496         None
497     }
498
499     /// Find the largest integer with the given alignment or less.
500     pub fn approximate_abi_align<C: HasDataLayout>(cx: C, align: Align) -> Integer {
501         let dl = cx.data_layout();
502
503         let wanted = align.abi();
504         // FIXME(eddyb) maybe include I128 in the future, when it works everywhere.
505         for &candidate in &[I64, I32, I16] {
506             if wanted >= candidate.align(dl).abi() && wanted >= candidate.size().bytes() {
507                 return candidate;
508             }
509         }
510         I8
511     }
512
513     /// Get the Integer type from an attr::IntType.
514     pub fn from_attr<C: HasDataLayout>(cx: C, ity: attr::IntType) -> Integer {
515         let dl = cx.data_layout();
516
517         match ity {
518             attr::SignedInt(IntTy::I8) | attr::UnsignedInt(UintTy::U8) => I8,
519             attr::SignedInt(IntTy::I16) | attr::UnsignedInt(UintTy::U16) => I16,
520             attr::SignedInt(IntTy::I32) | attr::UnsignedInt(UintTy::U32) => I32,
521             attr::SignedInt(IntTy::I64) | attr::UnsignedInt(UintTy::U64) => I64,
522             attr::SignedInt(IntTy::I128) | attr::UnsignedInt(UintTy::U128) => I128,
523             attr::SignedInt(IntTy::Isize) | attr::UnsignedInt(UintTy::Usize) => {
524                 dl.ptr_sized_integer()
525             }
526         }
527     }
528
529     /// Find the appropriate Integer type and signedness for the given
530     /// signed discriminant range and #[repr] attribute.
531     /// N.B.: u128 values above i128::MAX will be treated as signed, but
532     /// that shouldn't affect anything, other than maybe debuginfo.
533     fn repr_discr(tcx: TyCtxt<'a, 'tcx, 'tcx>,
534                   ty: Ty<'tcx>,
535                   repr: &ReprOptions,
536                   min: i128,
537                   max: i128)
538                   -> (Integer, bool) {
539         // Theoretically, negative values could be larger in unsigned representation
540         // than the unsigned representation of the signed minimum. However, if there
541         // are any negative values, the only valid unsigned representation is u128
542         // which can fit all i128 values, so the result remains unaffected.
543         let unsigned_fit = Integer::fit_unsigned(cmp::max(min as u128, max as u128));
544         let signed_fit = cmp::max(Integer::fit_signed(min), Integer::fit_signed(max));
545
546         let mut min_from_extern = None;
547         let min_default = I8;
548
549         if let Some(ity) = repr.int {
550             let discr = Integer::from_attr(tcx, ity);
551             let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
552             if discr < fit {
553                 bug!("Integer::repr_discr: `#[repr]` hint too small for \
554                   discriminant range of enum `{}", ty)
555             }
556             return (discr, ity.is_signed());
557         }
558
559         if repr.c() {
560             match &tcx.sess.target.target.arch[..] {
561                 // WARNING: the ARM EABI has two variants; the one corresponding
562                 // to `at_least == I32` appears to be used on Linux and NetBSD,
563                 // but some systems may use the variant corresponding to no
564                 // lower bound.  However, we don't run on those yet...?
565                 "arm" => min_from_extern = Some(I32),
566                 _ => min_from_extern = Some(I32),
567             }
568         }
569
570         let at_least = min_from_extern.unwrap_or(min_default);
571
572         // If there are no negative values, we can use the unsigned fit.
573         if min >= 0 {
574             (cmp::max(unsigned_fit, at_least), false)
575         } else {
576             (cmp::max(signed_fit, at_least), true)
577         }
578     }
579 }
580
581 /// Fundamental unit of memory access and layout.
582 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
583 pub enum Primitive {
584     /// The `bool` is the signedness of the `Integer` type.
585     ///
586     /// One would think we would not care about such details this low down,
587     /// but some ABIs are described in terms of C types and ISAs where the
588     /// integer arithmetic is done on {sign,zero}-extended registers, e.g.
589     /// a negative integer passed by zero-extension will appear positive in
590     /// the callee, and most operations on it will produce the wrong values.
591     Int(Integer, bool),
592     F32,
593     F64,
594     Pointer
595 }
596
597 impl<'a, 'tcx> Primitive {
598     pub fn size<C: HasDataLayout>(self, cx: C) -> Size {
599         let dl = cx.data_layout();
600
601         match self {
602             Int(i, _) => i.size(),
603             F32 => Size::from_bits(32),
604             F64 => Size::from_bits(64),
605             Pointer => dl.pointer_size
606         }
607     }
608
609     pub fn align<C: HasDataLayout>(self, cx: C) -> Align {
610         let dl = cx.data_layout();
611
612         match self {
613             Int(i, _) => i.align(dl),
614             F32 => dl.f32_align,
615             F64 => dl.f64_align,
616             Pointer => dl.pointer_align
617         }
618     }
619
620     pub fn to_ty(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
621         match *self {
622             Int(i, signed) => i.to_ty(tcx, signed),
623             F32 => tcx.types.f32,
624             F64 => tcx.types.f64,
625             Pointer => tcx.mk_mut_ptr(tcx.mk_nil()),
626         }
627     }
628 }
629
630 /// Information about one scalar component of a Rust type.
631 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
632 pub struct Scalar {
633     pub value: Primitive,
634
635     /// Inclusive wrap-around range of valid values, that is, if
636     /// min > max, it represents min..=u128::MAX followed by 0..=max.
637     // FIXME(eddyb) always use the shortest range, e.g. by finding
638     // the largest space between two consecutive valid values and
639     // taking everything else as the (shortest) valid range.
640     pub valid_range: RangeInclusive<u128>,
641 }
642
643 impl Scalar {
644     pub fn is_bool(&self) -> bool {
645         if let Int(I8, _) = self.value {
646             self.valid_range == (0..=1)
647         } else {
648             false
649         }
650     }
651 }
652
653 /// The first half of a fat pointer.
654 ///
655 /// - For a trait object, this is the address of the box.
656 /// - For a slice, this is the base address.
657 pub const FAT_PTR_ADDR: usize = 0;
658
659 /// The second half of a fat pointer.
660 ///
661 /// - For a trait object, this is the address of the vtable.
662 /// - For a slice, this is the length.
663 pub const FAT_PTR_EXTRA: usize = 1;
664
665 /// Describes how the fields of a type are located in memory.
666 #[derive(PartialEq, Eq, Hash, Debug)]
667 pub enum FieldPlacement {
668     /// All fields start at no offset. The `usize` is the field count.
669     Union(usize),
670
671     /// Array/vector-like placement, with all fields of identical types.
672     Array {
673         stride: Size,
674         count: u64
675     },
676
677     /// Struct-like placement, with precomputed offsets.
678     ///
679     /// Fields are guaranteed to not overlap, but note that gaps
680     /// before, between and after all the fields are NOT always
681     /// padding, and as such their contents may not be discarded.
682     /// For example, enum variants leave a gap at the start,
683     /// where the discriminant field in the enum layout goes.
684     Arbitrary {
685         /// Offsets for the first byte of each field,
686         /// ordered to match the source definition order.
687         /// This vector does not go in increasing order.
688         // FIXME(eddyb) use small vector optimization for the common case.
689         offsets: Vec<Size>,
690
691         /// Maps source order field indices to memory order indices,
692         /// depending how fields were permuted.
693         // FIXME(camlorn) also consider small vector  optimization here.
694         memory_index: Vec<u32>
695     }
696 }
697
698 impl FieldPlacement {
699     pub fn count(&self) -> usize {
700         match *self {
701             FieldPlacement::Union(count) => count,
702             FieldPlacement::Array { count, .. } => {
703                 let usize_count = count as usize;
704                 assert_eq!(usize_count as u64, count);
705                 usize_count
706             }
707             FieldPlacement::Arbitrary { ref offsets, .. } => offsets.len()
708         }
709     }
710
711     pub fn offset(&self, i: usize) -> Size {
712         match *self {
713             FieldPlacement::Union(_) => Size::from_bytes(0),
714             FieldPlacement::Array { stride, count } => {
715                 let i = i as u64;
716                 assert!(i < count);
717                 stride * i
718             }
719             FieldPlacement::Arbitrary { ref offsets, .. } => offsets[i]
720         }
721     }
722
723     pub fn memory_index(&self, i: usize) -> usize {
724         match *self {
725             FieldPlacement::Union(_) |
726             FieldPlacement::Array { .. } => i,
727             FieldPlacement::Arbitrary { ref memory_index, .. } => {
728                 let r = memory_index[i];
729                 assert_eq!(r as usize as u32, r);
730                 r as usize
731             }
732         }
733     }
734
735     /// Get source indices of the fields by increasing offsets.
736     #[inline]
737     pub fn index_by_increasing_offset<'a>(&'a self) -> impl iter::Iterator<Item=usize>+'a {
738         let mut inverse_small = [0u8; 64];
739         let mut inverse_big = vec![];
740         let use_small = self.count() <= inverse_small.len();
741
742         // We have to write this logic twice in order to keep the array small.
743         if let FieldPlacement::Arbitrary { ref memory_index, .. } = *self {
744             if use_small {
745                 for i in 0..self.count() {
746                     inverse_small[memory_index[i] as usize] = i as u8;
747                 }
748             } else {
749                 inverse_big = vec![0; self.count()];
750                 for i in 0..self.count() {
751                     inverse_big[memory_index[i] as usize] = i as u32;
752                 }
753             }
754         }
755
756         (0..self.count()).map(move |i| {
757             match *self {
758                 FieldPlacement::Union(_) |
759                 FieldPlacement::Array { .. } => i,
760                 FieldPlacement::Arbitrary { .. } => {
761                     if use_small { inverse_small[i] as usize }
762                     else { inverse_big[i] as usize }
763                 }
764             }
765         })
766     }
767 }
768
769 /// Describes how values of the type are passed by target ABIs,
770 /// in terms of categories of C types there are ABI rules for.
771 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
772 pub enum Abi {
773     Uninhabited,
774     Scalar(Scalar),
775     ScalarPair(Scalar, Scalar),
776     Vector {
777         element: Scalar,
778         count: u64
779     },
780     Aggregate {
781         /// If true, the size is exact, otherwise it's only a lower bound.
782         sized: bool,
783     }
784 }
785
786 impl Abi {
787     /// Returns true if the layout corresponds to an unsized type.
788     pub fn is_unsized(&self) -> bool {
789         match *self {
790             Abi::Uninhabited |
791             Abi::Scalar(_) |
792             Abi::ScalarPair(..) |
793             Abi::Vector { .. } => false,
794             Abi::Aggregate { sized } => !sized
795         }
796     }
797 }
798
799 #[derive(PartialEq, Eq, Hash, Debug)]
800 pub enum Variants {
801     /// Single enum variants, structs/tuples, unions, and all non-ADTs.
802     Single {
803         index: usize
804     },
805
806     /// General-case enums: for each case there is a struct, and they all have
807     /// all space reserved for the discriminant, and their first field starts
808     /// at a non-0 offset, after where the discriminant would go.
809     Tagged {
810         discr: Scalar,
811         variants: Vec<LayoutDetails>,
812     },
813
814     /// Multiple cases distinguished by a niche (values invalid for a type):
815     /// the variant `dataful_variant` contains a niche at an arbitrary
816     /// offset (field 0 of the enum), which for a variant with discriminant
817     /// `d` is set to `(d - niche_variants.start).wrapping_add(niche_start)`.
818     ///
819     /// For example, `Option<(usize, &T)>`  is represented such that
820     /// `None` has a null pointer for the second tuple field, and
821     /// `Some` is the identity function (with a non-null reference).
822     NicheFilling {
823         dataful_variant: usize,
824         niche_variants: RangeInclusive<usize>,
825         niche: Scalar,
826         niche_start: u128,
827         variants: Vec<LayoutDetails>,
828     }
829 }
830
831 #[derive(Copy, Clone, Debug)]
832 pub enum LayoutError<'tcx> {
833     Unknown(Ty<'tcx>),
834     SizeOverflow(Ty<'tcx>)
835 }
836
837 impl<'tcx> fmt::Display for LayoutError<'tcx> {
838     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
839         match *self {
840             LayoutError::Unknown(ty) => {
841                 write!(f, "the type `{:?}` has an unknown layout", ty)
842             }
843             LayoutError::SizeOverflow(ty) => {
844                 write!(f, "the type `{:?}` is too big for the current architecture", ty)
845             }
846         }
847     }
848 }
849
850 #[derive(PartialEq, Eq, Hash, Debug)]
851 pub struct LayoutDetails {
852     pub variants: Variants,
853     pub fields: FieldPlacement,
854     pub abi: Abi,
855     pub align: Align,
856     pub size: Size
857 }
858
859 impl LayoutDetails {
860     fn scalar<C: HasDataLayout>(cx: C, scalar: Scalar) -> Self {
861         let size = scalar.value.size(cx);
862         let align = scalar.value.align(cx);
863         LayoutDetails {
864             variants: Variants::Single { index: 0 },
865             fields: FieldPlacement::Union(0),
866             abi: Abi::Scalar(scalar),
867             size,
868             align,
869         }
870     }
871
872     fn uninhabited(field_count: usize) -> Self {
873         let align = Align::from_bytes(1, 1).unwrap();
874         LayoutDetails {
875             variants: Variants::Single { index: 0 },
876             fields: FieldPlacement::Union(field_count),
877             abi: Abi::Uninhabited,
878             align,
879             size: Size::from_bytes(0)
880         }
881     }
882 }
883
884 fn layout_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
885                         query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
886                         -> Result<&'tcx LayoutDetails, LayoutError<'tcx>>
887 {
888     let (param_env, ty) = query.into_parts();
889
890     let rec_limit = tcx.sess.recursion_limit.get();
891     let depth = tcx.layout_depth.get();
892     if depth > rec_limit {
893         tcx.sess.fatal(
894             &format!("overflow representing the type `{}`", ty));
895     }
896
897     tcx.layout_depth.set(depth+1);
898     let layout = LayoutDetails::compute_uncached(tcx, param_env, ty);
899     tcx.layout_depth.set(depth);
900
901     layout
902 }
903
904 pub fn provide(providers: &mut ty::maps::Providers) {
905     *providers = ty::maps::Providers {
906         layout_raw,
907         ..*providers
908     };
909 }
910
911 impl<'a, 'tcx> LayoutDetails {
912     fn compute_uncached(tcx: TyCtxt<'a, 'tcx, 'tcx>,
913                         param_env: ty::ParamEnv<'tcx>,
914                         ty: Ty<'tcx>)
915                         -> Result<&'tcx Self, LayoutError<'tcx>> {
916         let cx = (tcx, param_env);
917         let dl = cx.data_layout();
918         let scalar_unit = |value: Primitive| {
919             let bits = value.size(dl).bits();
920             assert!(bits <= 128);
921             Scalar {
922                 value,
923                 valid_range: 0..=(!0 >> (128 - bits))
924             }
925         };
926         let scalar = |value: Primitive| {
927             tcx.intern_layout(LayoutDetails::scalar(cx, scalar_unit(value)))
928         };
929         let scalar_pair = |a: Scalar, b: Scalar| {
930             let align = a.value.align(dl).max(b.value.align(dl)).max(dl.aggregate_align);
931             let b_offset = a.value.size(dl).abi_align(b.value.align(dl));
932             let size = (b_offset + b.value.size(dl)).abi_align(align);
933             LayoutDetails {
934                 variants: Variants::Single { index: 0 },
935                 fields: FieldPlacement::Arbitrary {
936                     offsets: vec![Size::from_bytes(0), b_offset],
937                     memory_index: vec![0, 1]
938                 },
939                 abi: Abi::ScalarPair(a, b),
940                 align,
941                 size
942             }
943         };
944
945         #[derive(Copy, Clone, Debug)]
946         enum StructKind {
947             /// A tuple, closure, or univariant which cannot be coerced to unsized.
948             AlwaysSized,
949             /// A univariant, the last field of which may be coerced to unsized.
950             MaybeUnsized,
951             /// A univariant, but with a prefix of an arbitrary size & alignment (e.g. enum tag).
952             Prefixed(Size, Align),
953         }
954         let univariant_uninterned = |fields: &[TyLayout], repr: &ReprOptions, kind| {
955             let packed = repr.packed();
956             if packed && repr.align > 0 {
957                 bug!("struct cannot be packed and aligned");
958             }
959
960             let mut align = if packed {
961                 dl.i8_align
962             } else {
963                 dl.aggregate_align
964             };
965
966             let mut sized = true;
967             let mut offsets = vec![Size::from_bytes(0); fields.len()];
968             let mut inverse_memory_index: Vec<u32> = (0..fields.len() as u32).collect();
969
970             // Anything with repr(C) or repr(packed) doesn't optimize.
971             let mut optimize = (repr.flags & ReprFlags::IS_UNOPTIMISABLE).is_empty();
972             if let StructKind::Prefixed(_, align) = kind {
973                 optimize &= align.abi() == 1;
974             }
975
976             if optimize {
977                 let end = if let StructKind::MaybeUnsized = kind {
978                     fields.len() - 1
979                 } else {
980                     fields.len()
981                 };
982                 let optimizing = &mut inverse_memory_index[..end];
983                 match kind {
984                     StructKind::AlwaysSized |
985                     StructKind::MaybeUnsized => {
986                         optimizing.sort_by_key(|&x| {
987                             // Place ZSTs first to avoid "interesting offsets",
988                             // especially with only one or two non-ZST fields.
989                             let f = &fields[x as usize];
990                             (!f.is_zst(), cmp::Reverse(f.align.abi()))
991                         })
992                     }
993                     StructKind::Prefixed(..) => {
994                         optimizing.sort_by_key(|&x| fields[x as usize].align.abi());
995                     }
996                 }
997             }
998
999             // inverse_memory_index holds field indices by increasing memory offset.
1000             // That is, if field 5 has offset 0, the first element of inverse_memory_index is 5.
1001             // We now write field offsets to the corresponding offset slot;
1002             // field 5 with offset 0 puts 0 in offsets[5].
1003             // At the bottom of this function, we use inverse_memory_index to produce memory_index.
1004
1005             let mut offset = Size::from_bytes(0);
1006
1007             if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
1008                 if !packed {
1009                     align = align.max(prefix_align);
1010                 }
1011                 offset = prefix_size.abi_align(prefix_align);
1012             }
1013
1014             for &i in &inverse_memory_index {
1015                 let field = fields[i as usize];
1016                 if !sized {
1017                     bug!("univariant: field #{} of `{}` comes after unsized field",
1018                         offsets.len(), ty);
1019                 }
1020
1021                 if field.abi == Abi::Uninhabited {
1022                     return Ok(LayoutDetails::uninhabited(fields.len()));
1023                 }
1024
1025                 if field.is_unsized() {
1026                     sized = false;
1027                 }
1028
1029                 // Invariant: offset < dl.obj_size_bound() <= 1<<61
1030                 if !packed {
1031                     offset = offset.abi_align(field.align);
1032                     align = align.max(field.align);
1033                 }
1034
1035                 debug!("univariant offset: {:?} field: {:#?}", offset, field);
1036                 offsets[i as usize] = offset;
1037
1038                 offset = offset.checked_add(field.size, dl)
1039                     .ok_or(LayoutError::SizeOverflow(ty))?;
1040             }
1041
1042             if repr.align > 0 {
1043                 let repr_align = repr.align as u64;
1044                 align = align.max(Align::from_bytes(repr_align, repr_align).unwrap());
1045                 debug!("univariant repr_align: {:?}", repr_align);
1046             }
1047
1048             debug!("univariant min_size: {:?}", offset);
1049             let min_size = offset;
1050
1051             // As stated above, inverse_memory_index holds field indices by increasing offset.
1052             // This makes it an already-sorted view of the offsets vec.
1053             // To invert it, consider:
1054             // If field 5 has offset 0, offsets[0] is 5, and memory_index[5] should be 0.
1055             // Field 5 would be the first element, so memory_index is i:
1056             // Note: if we didn't optimize, it's already right.
1057
1058             let mut memory_index;
1059             if optimize {
1060                 memory_index = vec![0; inverse_memory_index.len()];
1061
1062                 for i in 0..inverse_memory_index.len() {
1063                     memory_index[inverse_memory_index[i] as usize]  = i as u32;
1064                 }
1065             } else {
1066                 memory_index = inverse_memory_index;
1067             }
1068
1069             let size = min_size.abi_align(align);
1070             let mut abi = Abi::Aggregate { sized };
1071
1072             // Unpack newtype ABIs and find scalar pairs.
1073             if sized && size.bytes() > 0 {
1074                 // All other fields must be ZSTs, and we need them to all start at 0.
1075                 let mut zst_offsets =
1076                     offsets.iter().enumerate().filter(|&(i, _)| fields[i].is_zst());
1077                 if zst_offsets.all(|(_, o)| o.bytes() == 0) {
1078                     let mut non_zst_fields =
1079                         fields.iter().enumerate().filter(|&(_, f)| !f.is_zst());
1080
1081                     match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
1082                         // We have exactly one non-ZST field.
1083                         (Some((i, field)), None, None) => {
1084                             // Field fills the struct and it has a scalar or scalar pair ABI.
1085                             if offsets[i].bytes() == 0 &&
1086                                align.abi() == field.align.abi() &&
1087                                size == field.size {
1088                                 match field.abi {
1089                                     // For plain scalars, or vectors of them, we can't unpack
1090                                     // newtypes for `#[repr(C)]`, as that affects C ABIs.
1091                                     Abi::Scalar(_) | Abi::Vector { .. } if optimize => {
1092                                         abi = field.abi.clone();
1093                                     }
1094                                     // But scalar pairs are Rust-specific and get
1095                                     // treated as aggregates by C ABIs anyway.
1096                                     Abi::ScalarPair(..) => {
1097                                         abi = field.abi.clone();
1098                                     }
1099                                     _ => {}
1100                                 }
1101                             }
1102                         }
1103
1104                         // Two non-ZST fields, and they're both scalars.
1105                         (Some((i, &TyLayout {
1106                             details: &LayoutDetails { abi: Abi::Scalar(ref a), .. }, ..
1107                         })), Some((j, &TyLayout {
1108                             details: &LayoutDetails { abi: Abi::Scalar(ref b), .. }, ..
1109                         })), None) => {
1110                             // Order by the memory placement, not source order.
1111                             let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
1112                                 ((i, a), (j, b))
1113                             } else {
1114                                 ((j, b), (i, a))
1115                             };
1116                             let pair = scalar_pair(a.clone(), b.clone());
1117                             let pair_offsets = match pair.fields {
1118                                 FieldPlacement::Arbitrary {
1119                                     ref offsets,
1120                                     ref memory_index
1121                                 } => {
1122                                     assert_eq!(memory_index, &[0, 1]);
1123                                     offsets
1124                                 }
1125                                 _ => bug!()
1126                             };
1127                             if offsets[i] == pair_offsets[0] &&
1128                                offsets[j] == pair_offsets[1] &&
1129                                align == pair.align &&
1130                                size == pair.size {
1131                                 // We can use `ScalarPair` only when it matches our
1132                                 // already computed layout (including `#[repr(C)]`).
1133                                 abi = pair.abi;
1134                             }
1135                         }
1136
1137                         _ => {}
1138                     }
1139                 }
1140             }
1141
1142             Ok(LayoutDetails {
1143                 variants: Variants::Single { index: 0 },
1144                 fields: FieldPlacement::Arbitrary {
1145                     offsets,
1146                     memory_index
1147                 },
1148                 abi,
1149                 align,
1150                 size
1151             })
1152         };
1153         let univariant = |fields: &[TyLayout], repr: &ReprOptions, kind| {
1154             Ok(tcx.intern_layout(univariant_uninterned(fields, repr, kind)?))
1155         };
1156         assert!(!ty.has_infer_types());
1157
1158         Ok(match ty.sty {
1159             // Basic scalars.
1160             ty::TyBool => {
1161                 tcx.intern_layout(LayoutDetails::scalar(cx, Scalar {
1162                     value: Int(I8, false),
1163                     valid_range: 0..=1
1164                 }))
1165             }
1166             ty::TyChar => {
1167                 tcx.intern_layout(LayoutDetails::scalar(cx, Scalar {
1168                     value: Int(I32, false),
1169                     valid_range: 0..=0x10FFFF
1170                 }))
1171             }
1172             ty::TyInt(ity) => {
1173                 scalar(Int(Integer::from_attr(dl, attr::SignedInt(ity)), true))
1174             }
1175             ty::TyUint(ity) => {
1176                 scalar(Int(Integer::from_attr(dl, attr::UnsignedInt(ity)), false))
1177             }
1178             ty::TyFloat(FloatTy::F32) => scalar(F32),
1179             ty::TyFloat(FloatTy::F64) => scalar(F64),
1180             ty::TyFnPtr(_) => {
1181                 let mut ptr = scalar_unit(Pointer);
1182                 ptr.valid_range.start = 1;
1183                 tcx.intern_layout(LayoutDetails::scalar(cx, ptr))
1184             }
1185
1186             // The never type.
1187             ty::TyNever => {
1188                 tcx.intern_layout(LayoutDetails::uninhabited(0))
1189             }
1190
1191             // Potentially-fat pointers.
1192             ty::TyRef(_, ty::TypeAndMut { ty: pointee, .. }) |
1193             ty::TyRawPtr(ty::TypeAndMut { ty: pointee, .. }) => {
1194                 let mut data_ptr = scalar_unit(Pointer);
1195                 if !ty.is_unsafe_ptr() {
1196                     data_ptr.valid_range.start = 1;
1197                 }
1198
1199                 let pointee = tcx.normalize_associated_type_in_env(&pointee, param_env);
1200                 if pointee.is_sized(tcx, param_env, DUMMY_SP) {
1201                     return Ok(tcx.intern_layout(LayoutDetails::scalar(cx, data_ptr)));
1202                 }
1203
1204                 let unsized_part = tcx.struct_tail(pointee);
1205                 let metadata = match unsized_part.sty {
1206                     ty::TyForeign(..) => {
1207                         return Ok(tcx.intern_layout(LayoutDetails::scalar(cx, data_ptr)));
1208                     }
1209                     ty::TySlice(_) | ty::TyStr => {
1210                         scalar_unit(Int(dl.ptr_sized_integer(), false))
1211                     }
1212                     ty::TyDynamic(..) => {
1213                         let mut vtable = scalar_unit(Pointer);
1214                         vtable.valid_range.start = 1;
1215                         vtable
1216                     }
1217                     _ => return Err(LayoutError::Unknown(unsized_part))
1218                 };
1219
1220                 // Effectively a (ptr, meta) tuple.
1221                 tcx.intern_layout(scalar_pair(data_ptr, metadata))
1222             }
1223
1224             // Arrays and slices.
1225             ty::TyArray(element, mut count) => {
1226                 if count.has_projections() {
1227                     count = tcx.normalize_associated_type_in_env(&count, param_env);
1228                     if count.has_projections() {
1229                         return Err(LayoutError::Unknown(ty));
1230                     }
1231                 }
1232
1233                 let element = cx.layout_of(element)?;
1234                 let count = count.val.to_const_int().unwrap().to_u64().unwrap();
1235                 let size = element.size.checked_mul(count, dl)
1236                     .ok_or(LayoutError::SizeOverflow(ty))?;
1237
1238                 tcx.intern_layout(LayoutDetails {
1239                     variants: Variants::Single { index: 0 },
1240                     fields: FieldPlacement::Array {
1241                         stride: element.size,
1242                         count
1243                     },
1244                     abi: Abi::Aggregate { sized: true },
1245                     align: element.align,
1246                     size
1247                 })
1248             }
1249             ty::TySlice(element) => {
1250                 let element = cx.layout_of(element)?;
1251                 tcx.intern_layout(LayoutDetails {
1252                     variants: Variants::Single { index: 0 },
1253                     fields: FieldPlacement::Array {
1254                         stride: element.size,
1255                         count: 0
1256                     },
1257                     abi: Abi::Aggregate { sized: false },
1258                     align: element.align,
1259                     size: Size::from_bytes(0)
1260                 })
1261             }
1262             ty::TyStr => {
1263                 tcx.intern_layout(LayoutDetails {
1264                     variants: Variants::Single { index: 0 },
1265                     fields: FieldPlacement::Array {
1266                         stride: Size::from_bytes(1),
1267                         count: 0
1268                     },
1269                     abi: Abi::Aggregate { sized: false },
1270                     align: dl.i8_align,
1271                     size: Size::from_bytes(0)
1272                 })
1273             }
1274
1275             // Odd unit types.
1276             ty::TyFnDef(..) => {
1277                 univariant(&[], &ReprOptions::default(), StructKind::AlwaysSized)?
1278             }
1279             ty::TyDynamic(..) | ty::TyForeign(..) => {
1280                 let mut unit = univariant_uninterned(&[], &ReprOptions::default(),
1281                   StructKind::AlwaysSized)?;
1282                 match unit.abi {
1283                     Abi::Aggregate { ref mut sized } => *sized = false,
1284                     _ => bug!()
1285                 }
1286                 tcx.intern_layout(unit)
1287             }
1288
1289             // Tuples, generators and closures.
1290             ty::TyGenerator(def_id, ref substs, _) => {
1291                 let tys = substs.field_tys(def_id, tcx);
1292                 univariant(&tys.map(|ty| cx.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
1293                     &ReprOptions::default(),
1294                     StructKind::AlwaysSized)?
1295             }
1296
1297             ty::TyClosure(def_id, ref substs) => {
1298                 let tys = substs.upvar_tys(def_id, tcx);
1299                 univariant(&tys.map(|ty| cx.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
1300                     &ReprOptions::default(),
1301                     StructKind::AlwaysSized)?
1302             }
1303
1304             ty::TyTuple(tys, _) => {
1305                 let kind = if tys.len() == 0 {
1306                     StructKind::AlwaysSized
1307                 } else {
1308                     StructKind::MaybeUnsized
1309                 };
1310
1311                 univariant(&tys.iter().map(|ty| cx.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
1312                     &ReprOptions::default(), kind)?
1313             }
1314
1315             // SIMD vector types.
1316             ty::TyAdt(def, ..) if def.repr.simd() => {
1317                 let element = cx.layout_of(ty.simd_type(tcx))?;
1318                 let count = ty.simd_size(tcx) as u64;
1319                 assert!(count > 0);
1320                 let scalar = match element.abi {
1321                     Abi::Scalar(ref scalar) => scalar.clone(),
1322                     _ => {
1323                         tcx.sess.fatal(&format!("monomorphising SIMD type `{}` with \
1324                                                 a non-machine element type `{}`",
1325                                                 ty, element.ty));
1326                     }
1327                 };
1328                 let size = element.size.checked_mul(count, dl)
1329                     .ok_or(LayoutError::SizeOverflow(ty))?;
1330                 let align = dl.vector_align(size);
1331                 let size = size.abi_align(align);
1332
1333                 tcx.intern_layout(LayoutDetails {
1334                     variants: Variants::Single { index: 0 },
1335                     fields: FieldPlacement::Array {
1336                         stride: element.size,
1337                         count
1338                     },
1339                     abi: Abi::Vector {
1340                         element: scalar,
1341                         count
1342                     },
1343                     size,
1344                     align,
1345                 })
1346             }
1347
1348             // ADTs.
1349             ty::TyAdt(def, substs) => {
1350                 // Cache the field layouts.
1351                 let variants = def.variants.iter().map(|v| {
1352                     v.fields.iter().map(|field| {
1353                         cx.layout_of(field.ty(tcx, substs))
1354                     }).collect::<Result<Vec<_>, _>>()
1355                 }).collect::<Result<Vec<_>, _>>()?;
1356
1357                 if def.is_union() {
1358                     let packed = def.repr.packed();
1359                     if packed && def.repr.align > 0 {
1360                         bug!("Union cannot be packed and aligned");
1361                     }
1362
1363                     let mut align = if def.repr.packed() {
1364                         dl.i8_align
1365                     } else {
1366                         dl.aggregate_align
1367                     };
1368
1369                     if def.repr.align > 0 {
1370                         let repr_align = def.repr.align as u64;
1371                         align = align.max(
1372                             Align::from_bytes(repr_align, repr_align).unwrap());
1373                     }
1374
1375                     let mut size = Size::from_bytes(0);
1376                     for field in &variants[0] {
1377                         assert!(!field.is_unsized());
1378
1379                         if !packed {
1380                             align = align.max(field.align);
1381                         }
1382                         size = cmp::max(size, field.size);
1383                     }
1384
1385                     return Ok(tcx.intern_layout(LayoutDetails {
1386                         variants: Variants::Single { index: 0 },
1387                         fields: FieldPlacement::Union(variants[0].len()),
1388                         abi: Abi::Aggregate { sized: true },
1389                         align,
1390                         size: size.abi_align(align)
1391                     }));
1392                 }
1393
1394                 let (inh_first, inh_second) = {
1395                     let mut inh_variants = (0..variants.len()).filter(|&v| {
1396                         variants[v].iter().all(|f| f.abi != Abi::Uninhabited)
1397                     });
1398                     (inh_variants.next(), inh_variants.next())
1399                 };
1400                 if inh_first.is_none() {
1401                     // Uninhabited because it has no variants, or only uninhabited ones.
1402                     return Ok(tcx.intern_layout(LayoutDetails::uninhabited(0)));
1403                 }
1404
1405                 let is_struct = !def.is_enum() ||
1406                     // Only one variant is inhabited.
1407                     (inh_second.is_none() &&
1408                     // Representation optimizations are allowed.
1409                      !def.repr.inhibit_enum_layout_opt() &&
1410                     // Inhabited variant either has data ...
1411                      (!variants[inh_first.unwrap()].is_empty() ||
1412                     // ... or there other, uninhabited, variants.
1413                       variants.len() > 1));
1414                 if is_struct {
1415                     // Struct, or univariant enum equivalent to a struct.
1416                     // (Typechecking will reject discriminant-sizing attrs.)
1417
1418                     let v = inh_first.unwrap();
1419                     let kind = if def.is_enum() || variants[v].len() == 0 {
1420                         StructKind::AlwaysSized
1421                     } else {
1422                         let param_env = tcx.param_env(def.did);
1423                         let last_field = def.variants[v].fields.last().unwrap();
1424                         let always_sized = tcx.type_of(last_field.did)
1425                           .is_sized(tcx, param_env, DUMMY_SP);
1426                         if !always_sized { StructKind::MaybeUnsized }
1427                         else { StructKind::AlwaysSized }
1428                     };
1429
1430                     let mut st = univariant_uninterned(&variants[v], &def.repr, kind)?;
1431                     st.variants = Variants::Single { index: v };
1432                     // Exclude 0 from the range of a newtype ABI NonZero<T>.
1433                     if Some(def.did) == cx.tcx().lang_items().non_zero() {
1434                         match st.abi {
1435                             Abi::Scalar(ref mut scalar) |
1436                             Abi::ScalarPair(ref mut scalar, _) => {
1437                                 if scalar.valid_range.start == 0 {
1438                                     scalar.valid_range.start = 1;
1439                                 }
1440                             }
1441                             _ => {}
1442                         }
1443                     }
1444                     return Ok(tcx.intern_layout(st));
1445                 }
1446
1447                 let no_explicit_discriminants = def.variants.iter().enumerate()
1448                     .all(|(i, v)| v.discr == ty::VariantDiscr::Relative(i));
1449
1450                 // Niche-filling enum optimization.
1451                 if !def.repr.inhibit_enum_layout_opt() && no_explicit_discriminants {
1452                     let mut dataful_variant = None;
1453                     let mut niche_variants = usize::max_value()..=0;
1454
1455                     // Find one non-ZST variant.
1456                     'variants: for (v, fields) in variants.iter().enumerate() {
1457                         for f in fields {
1458                             if f.abi == Abi::Uninhabited {
1459                                 continue 'variants;
1460                             }
1461                             if !f.is_zst() {
1462                                 if dataful_variant.is_none() {
1463                                     dataful_variant = Some(v);
1464                                     continue 'variants;
1465                                 } else {
1466                                     dataful_variant = None;
1467                                     break 'variants;
1468                                 }
1469                             }
1470                         }
1471                         if niche_variants.start > v {
1472                             niche_variants.start = v;
1473                         }
1474                         niche_variants.end = v;
1475                     }
1476
1477                     if niche_variants.start > niche_variants.end {
1478                         dataful_variant = None;
1479                     }
1480
1481                     if let Some(i) = dataful_variant {
1482                         let count = (niche_variants.end - niche_variants.start + 1) as u128;
1483                         for (field_index, field) in variants[i].iter().enumerate() {
1484                             let (offset, niche, niche_start) =
1485                                 match field.find_niche(cx, count)? {
1486                                     Some(niche) => niche,
1487                                     None => continue
1488                                 };
1489                             let mut align = dl.aggregate_align;
1490                             let st = variants.iter().enumerate().map(|(j, v)| {
1491                                 let mut st = univariant_uninterned(v,
1492                                     &def.repr, StructKind::AlwaysSized)?;
1493                                 st.variants = Variants::Single { index: j };
1494
1495                                 align = align.max(st.align);
1496
1497                                 Ok(st)
1498                             }).collect::<Result<Vec<_>, _>>()?;
1499
1500                             let offset = st[i].fields.offset(field_index) + offset;
1501                             let size = st[i].size;
1502
1503                             let abi = if offset.bytes() == 0 && niche.value.size(dl) == size {
1504                                 Abi::Scalar(niche.clone())
1505                             } else {
1506                                 Abi::Aggregate { sized: true }
1507                             };
1508
1509                             return Ok(tcx.intern_layout(LayoutDetails {
1510                                 variants: Variants::NicheFilling {
1511                                     dataful_variant: i,
1512                                     niche_variants,
1513                                     niche,
1514                                     niche_start,
1515                                     variants: st,
1516                                 },
1517                                 fields: FieldPlacement::Arbitrary {
1518                                     offsets: vec![offset],
1519                                     memory_index: vec![0]
1520                                 },
1521                                 abi,
1522                                 size,
1523                                 align,
1524                             }));
1525                         }
1526                     }
1527                 }
1528
1529                 let (mut min, mut max) = (i128::max_value(), i128::min_value());
1530                 for (i, discr) in def.discriminants(tcx).enumerate() {
1531                     if variants[i].iter().any(|f| f.abi == Abi::Uninhabited) {
1532                         continue;
1533                     }
1534                     let x = discr.to_u128_unchecked() as i128;
1535                     if x < min { min = x; }
1536                     if x > max { max = x; }
1537                 }
1538                 assert!(min <= max, "discriminant range is {}...{}", min, max);
1539                 let (min_ity, signed) = Integer::repr_discr(tcx, ty, &def.repr, min, max);
1540
1541                 let mut align = dl.aggregate_align;
1542                 let mut size = Size::from_bytes(0);
1543
1544                 // We're interested in the smallest alignment, so start large.
1545                 let mut start_align = Align::from_bytes(256, 256).unwrap();
1546                 assert_eq!(Integer::for_abi_align(dl, start_align), None);
1547
1548                 // repr(C) on an enum tells us to make a (tag, union) layout,
1549                 // so we need to grow the prefix alignment to be at least
1550                 // the alignment of the union. (This value is used both for
1551                 // determining the alignment of the overall enum, and the
1552                 // determining the alignment of the payload after the tag.)
1553                 let mut prefix_align = min_ity.align(dl);
1554                 if def.repr.c() {
1555                     for fields in &variants {
1556                         for field in fields {
1557                             prefix_align = prefix_align.max(field.align);
1558                         }
1559                     }
1560                 }
1561
1562                 // Create the set of structs that represent each variant.
1563                 let mut variants = variants.into_iter().enumerate().map(|(i, field_layouts)| {
1564                     let mut st = univariant_uninterned(&field_layouts,
1565                         &def.repr, StructKind::Prefixed(min_ity.size(), prefix_align))?;
1566                     st.variants = Variants::Single { index: i };
1567                     // Find the first field we can't move later
1568                     // to make room for a larger discriminant.
1569                     for field in st.fields.index_by_increasing_offset().map(|j| field_layouts[j]) {
1570                         if !field.is_zst() || field.align.abi() != 1 {
1571                             start_align = start_align.min(field.align);
1572                             break;
1573                         }
1574                     }
1575                     size = cmp::max(size, st.size);
1576                     align = align.max(st.align);
1577                     Ok(st)
1578                 }).collect::<Result<Vec<_>, _>>()?;
1579
1580                 // Align the maximum variant size to the largest alignment.
1581                 size = size.abi_align(align);
1582
1583                 if size.bytes() >= dl.obj_size_bound() {
1584                     return Err(LayoutError::SizeOverflow(ty));
1585                 }
1586
1587                 let typeck_ity = Integer::from_attr(dl, def.repr.discr_type());
1588                 if typeck_ity < min_ity {
1589                     // It is a bug if Layout decided on a greater discriminant size than typeck for
1590                     // some reason at this point (based on values discriminant can take on). Mostly
1591                     // because this discriminant will be loaded, and then stored into variable of
1592                     // type calculated by typeck. Consider such case (a bug): typeck decided on
1593                     // byte-sized discriminant, but layout thinks we need a 16-bit to store all
1594                     // discriminant values. That would be a bug, because then, in trans, in order
1595                     // to store this 16-bit discriminant into 8-bit sized temporary some of the
1596                     // space necessary to represent would have to be discarded (or layout is wrong
1597                     // on thinking it needs 16 bits)
1598                     bug!("layout decided on a larger discriminant type ({:?}) than typeck ({:?})",
1599                          min_ity, typeck_ity);
1600                     // However, it is fine to make discr type however large (as an optimisation)
1601                     // after this point â€“ we’ll just truncate the value we load in trans.
1602                 }
1603
1604                 // Check to see if we should use a different type for the
1605                 // discriminant. We can safely use a type with the same size
1606                 // as the alignment of the first field of each variant.
1607                 // We increase the size of the discriminant to avoid LLVM copying
1608                 // padding when it doesn't need to. This normally causes unaligned
1609                 // load/stores and excessive memcpy/memset operations. By using a
1610                 // bigger integer size, LLVM can be sure about it's contents and
1611                 // won't be so conservative.
1612
1613                 // Use the initial field alignment
1614                 let mut ity = Integer::for_abi_align(dl, start_align).unwrap_or(min_ity);
1615
1616                 // If the alignment is not larger than the chosen discriminant size,
1617                 // don't use the alignment as the final size.
1618                 if ity <= min_ity {
1619                     ity = min_ity;
1620                 } else {
1621                     // Patch up the variants' first few fields.
1622                     let old_ity_size = min_ity.size();
1623                     let new_ity_size = ity.size();
1624                     for variant in &mut variants {
1625                         if variant.abi == Abi::Uninhabited {
1626                             continue;
1627                         }
1628                         match variant.fields {
1629                             FieldPlacement::Arbitrary { ref mut offsets, .. } => {
1630                                 for i in offsets {
1631                                     if *i <= old_ity_size {
1632                                         assert_eq!(*i, old_ity_size);
1633                                         *i = new_ity_size;
1634                                     }
1635                                 }
1636                                 // We might be making the struct larger.
1637                                 if variant.size <= old_ity_size {
1638                                     variant.size = new_ity_size;
1639                                 }
1640                             }
1641                             _ => bug!()
1642                         }
1643                     }
1644                 }
1645
1646                 let discr = Scalar {
1647                     value: Int(ity, signed),
1648                     valid_range: (min as u128)..=(max as u128)
1649                 };
1650                 let abi = if discr.value.size(dl) == size {
1651                     Abi::Scalar(discr.clone())
1652                 } else {
1653                     Abi::Aggregate { sized: true }
1654                 };
1655                 tcx.intern_layout(LayoutDetails {
1656                     variants: Variants::Tagged {
1657                         discr,
1658                         variants
1659                     },
1660                     fields: FieldPlacement::Arbitrary {
1661                         offsets: vec![Size::from_bytes(0)],
1662                         memory_index: vec![0]
1663                     },
1664                     abi,
1665                     align,
1666                     size
1667                 })
1668             }
1669
1670             // Types with no meaningful known layout.
1671             ty::TyProjection(_) | ty::TyAnon(..) => {
1672                 let normalized = tcx.normalize_associated_type_in_env(&ty, param_env);
1673                 if ty == normalized {
1674                     return Err(LayoutError::Unknown(ty));
1675                 }
1676                 tcx.layout_raw(param_env.and(normalized))?
1677             }
1678             ty::TyParam(_) => {
1679                 return Err(LayoutError::Unknown(ty));
1680             }
1681             ty::TyGeneratorWitness(..) | ty::TyInfer(_) | ty::TyError => {
1682                 bug!("LayoutDetails::compute: unexpected type `{}`", ty)
1683             }
1684         })
1685     }
1686
1687     /// This is invoked by the `layout_raw` query to record the final
1688     /// layout of each type.
1689     #[inline]
1690     fn record_layout_for_printing(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1691                                   ty: Ty<'tcx>,
1692                                   param_env: ty::ParamEnv<'tcx>,
1693                                   layout: TyLayout<'tcx>) {
1694         // If we are running with `-Zprint-type-sizes`, record layouts for
1695         // dumping later. Ignore layouts that are done with non-empty
1696         // environments or non-monomorphic layouts, as the user only wants
1697         // to see the stuff resulting from the final trans session.
1698         if
1699             !tcx.sess.opts.debugging_opts.print_type_sizes ||
1700             ty.has_param_types() ||
1701             ty.has_self_ty() ||
1702             !param_env.caller_bounds.is_empty()
1703         {
1704             return;
1705         }
1706
1707         Self::record_layout_for_printing_outlined(tcx, ty, param_env, layout)
1708     }
1709
1710     fn record_layout_for_printing_outlined(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1711                                            ty: Ty<'tcx>,
1712                                            param_env: ty::ParamEnv<'tcx>,
1713                                            layout: TyLayout<'tcx>) {
1714         let cx = (tcx, param_env);
1715         // (delay format until we actually need it)
1716         let record = |kind, opt_discr_size, variants| {
1717             let type_desc = format!("{:?}", ty);
1718             tcx.sess.code_stats.borrow_mut().record_type_size(kind,
1719                                                               type_desc,
1720                                                               layout.align,
1721                                                               layout.size,
1722                                                               opt_discr_size,
1723                                                               variants);
1724         };
1725
1726         let adt_def = match ty.sty {
1727             ty::TyAdt(ref adt_def, _) => {
1728                 debug!("print-type-size t: `{:?}` process adt", ty);
1729                 adt_def
1730             }
1731
1732             ty::TyClosure(..) => {
1733                 debug!("print-type-size t: `{:?}` record closure", ty);
1734                 record(DataTypeKind::Closure, None, vec![]);
1735                 return;
1736             }
1737
1738             _ => {
1739                 debug!("print-type-size t: `{:?}` skip non-nominal", ty);
1740                 return;
1741             }
1742         };
1743
1744         let adt_kind = adt_def.adt_kind();
1745
1746         let build_variant_info = |n: Option<ast::Name>,
1747                                   flds: &[ast::Name],
1748                                   layout: TyLayout<'tcx>| {
1749             let mut min_size = Size::from_bytes(0);
1750             let field_info: Vec<_> = flds.iter().enumerate().map(|(i, &name)| {
1751                 match layout.field(cx, i) {
1752                     Err(err) => {
1753                         bug!("no layout found for field {}: `{:?}`", name, err);
1754                     }
1755                     Ok(field_layout) => {
1756                         let offset = layout.fields.offset(i);
1757                         let field_end = offset + field_layout.size;
1758                         if min_size < field_end {
1759                             min_size = field_end;
1760                         }
1761                         session::FieldInfo {
1762                             name: name.to_string(),
1763                             offset: offset.bytes(),
1764                             size: field_layout.size.bytes(),
1765                             align: field_layout.align.abi(),
1766                         }
1767                     }
1768                 }
1769             }).collect();
1770
1771             session::VariantInfo {
1772                 name: n.map(|n|n.to_string()),
1773                 kind: if layout.is_unsized() {
1774                     session::SizeKind::Min
1775                 } else {
1776                     session::SizeKind::Exact
1777                 },
1778                 align: layout.align.abi(),
1779                 size: if min_size.bytes() == 0 {
1780                     layout.size.bytes()
1781                 } else {
1782                     min_size.bytes()
1783                 },
1784                 fields: field_info,
1785             }
1786         };
1787
1788         match layout.variants {
1789             Variants::Single { index } => {
1790                 debug!("print-type-size `{:#?}` variant {}",
1791                        layout, adt_def.variants[index].name);
1792                 if !adt_def.variants.is_empty() {
1793                     let variant_def = &adt_def.variants[index];
1794                     let fields: Vec<_> =
1795                         variant_def.fields.iter().map(|f| f.name).collect();
1796                     record(adt_kind.into(),
1797                            None,
1798                            vec![build_variant_info(Some(variant_def.name),
1799                                                    &fields,
1800                                                    layout)]);
1801                 } else {
1802                     // (This case arises for *empty* enums; so give it
1803                     // zero variants.)
1804                     record(adt_kind.into(), None, vec![]);
1805                 }
1806             }
1807
1808             Variants::NicheFilling { .. } |
1809             Variants::Tagged { .. } => {
1810                 debug!("print-type-size `{:#?}` adt general variants def {}",
1811                        ty, adt_def.variants.len());
1812                 let variant_infos: Vec<_> =
1813                     adt_def.variants.iter().enumerate().map(|(i, variant_def)| {
1814                         let fields: Vec<_> =
1815                             variant_def.fields.iter().map(|f| f.name).collect();
1816                         build_variant_info(Some(variant_def.name),
1817                                             &fields,
1818                                             layout.for_variant(cx, i))
1819                     })
1820                     .collect();
1821                 record(adt_kind.into(), match layout.variants {
1822                     Variants::Tagged { ref discr, .. } => Some(discr.value.size(tcx)),
1823                     _ => None
1824                 }, variant_infos);
1825             }
1826         }
1827     }
1828 }
1829
1830 /// Type size "skeleton", i.e. the only information determining a type's size.
1831 /// While this is conservative, (aside from constant sizes, only pointers,
1832 /// newtypes thereof and null pointer optimized enums are allowed), it is
1833 /// enough to statically check common usecases of transmute.
1834 #[derive(Copy, Clone, Debug)]
1835 pub enum SizeSkeleton<'tcx> {
1836     /// Any statically computable Layout.
1837     Known(Size),
1838
1839     /// A potentially-fat pointer.
1840     Pointer {
1841         /// If true, this pointer is never null.
1842         non_zero: bool,
1843         /// The type which determines the unsized metadata, if any,
1844         /// of this pointer. Either a type parameter or a projection
1845         /// depending on one, with regions erased.
1846         tail: Ty<'tcx>
1847     }
1848 }
1849
1850 impl<'a, 'tcx> SizeSkeleton<'tcx> {
1851     pub fn compute(ty: Ty<'tcx>,
1852                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
1853                    param_env: ty::ParamEnv<'tcx>)
1854                    -> Result<SizeSkeleton<'tcx>, LayoutError<'tcx>> {
1855         assert!(!ty.has_infer_types());
1856
1857         // First try computing a static layout.
1858         let err = match (tcx, param_env).layout_of(ty) {
1859             Ok(layout) => {
1860                 return Ok(SizeSkeleton::Known(layout.size));
1861             }
1862             Err(err) => err
1863         };
1864
1865         match ty.sty {
1866             ty::TyRef(_, ty::TypeAndMut { ty: pointee, .. }) |
1867             ty::TyRawPtr(ty::TypeAndMut { ty: pointee, .. }) => {
1868                 let non_zero = !ty.is_unsafe_ptr();
1869                 let tail = tcx.struct_tail(pointee);
1870                 match tail.sty {
1871                     ty::TyParam(_) | ty::TyProjection(_) => {
1872                         assert!(tail.has_param_types() || tail.has_self_ty());
1873                         Ok(SizeSkeleton::Pointer {
1874                             non_zero,
1875                             tail: tcx.erase_regions(&tail)
1876                         })
1877                     }
1878                     _ => {
1879                         bug!("SizeSkeleton::compute({}): layout errored ({}), yet \
1880                               tail `{}` is not a type parameter or a projection",
1881                              ty, err, tail)
1882                     }
1883                 }
1884             }
1885
1886             ty::TyAdt(def, substs) => {
1887                 // Only newtypes and enums w/ nullable pointer optimization.
1888                 if def.is_union() || def.variants.is_empty() || def.variants.len() > 2 {
1889                     return Err(err);
1890                 }
1891
1892                 // Get a zero-sized variant or a pointer newtype.
1893                 let zero_or_ptr_variant = |i: usize| {
1894                     let fields = def.variants[i].fields.iter().map(|field| {
1895                         SizeSkeleton::compute(field.ty(tcx, substs), tcx, param_env)
1896                     });
1897                     let mut ptr = None;
1898                     for field in fields {
1899                         let field = field?;
1900                         match field {
1901                             SizeSkeleton::Known(size) => {
1902                                 if size.bytes() > 0 {
1903                                     return Err(err);
1904                                 }
1905                             }
1906                             SizeSkeleton::Pointer {..} => {
1907                                 if ptr.is_some() {
1908                                     return Err(err);
1909                                 }
1910                                 ptr = Some(field);
1911                             }
1912                         }
1913                     }
1914                     Ok(ptr)
1915                 };
1916
1917                 let v0 = zero_or_ptr_variant(0)?;
1918                 // Newtype.
1919                 if def.variants.len() == 1 {
1920                     if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
1921                         return Ok(SizeSkeleton::Pointer {
1922                             non_zero: non_zero ||
1923                                 Some(def.did) == tcx.lang_items().non_zero(),
1924                             tail,
1925                         });
1926                     } else {
1927                         return Err(err);
1928                     }
1929                 }
1930
1931                 let v1 = zero_or_ptr_variant(1)?;
1932                 // Nullable pointer enum optimization.
1933                 match (v0, v1) {
1934                     (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None) |
1935                     (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
1936                         Ok(SizeSkeleton::Pointer {
1937                             non_zero: false,
1938                             tail,
1939                         })
1940                     }
1941                     _ => Err(err)
1942                 }
1943             }
1944
1945             ty::TyProjection(_) | ty::TyAnon(..) => {
1946                 let normalized = tcx.normalize_associated_type_in_env(&ty, param_env);
1947                 if ty == normalized {
1948                     Err(err)
1949                 } else {
1950                     SizeSkeleton::compute(normalized, tcx, param_env)
1951                 }
1952             }
1953
1954             _ => Err(err)
1955         }
1956     }
1957
1958     pub fn same_size(self, other: SizeSkeleton) -> bool {
1959         match (self, other) {
1960             (SizeSkeleton::Known(a), SizeSkeleton::Known(b)) => a == b,
1961             (SizeSkeleton::Pointer { tail: a, .. },
1962              SizeSkeleton::Pointer { tail: b, .. }) => a == b,
1963             _ => false
1964         }
1965     }
1966 }
1967
1968 /// The details of the layout of a type, alongside the type itself.
1969 /// Provides various type traversal APIs (e.g. recursing into fields).
1970 ///
1971 /// Note that the details are NOT guaranteed to always be identical
1972 /// to those obtained from `layout_of(ty)`, as we need to produce
1973 /// layouts for which Rust types do not exist, such as enum variants
1974 /// or synthetic fields of enums (i.e. discriminants) and fat pointers.
1975 #[derive(Copy, Clone, Debug)]
1976 pub struct TyLayout<'tcx> {
1977     pub ty: Ty<'tcx>,
1978     details: &'tcx LayoutDetails
1979 }
1980
1981 impl<'tcx> Deref for TyLayout<'tcx> {
1982     type Target = &'tcx LayoutDetails;
1983     fn deref(&self) -> &&'tcx LayoutDetails {
1984         &self.details
1985     }
1986 }
1987
1988 pub trait HasTyCtxt<'tcx>: HasDataLayout {
1989     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx>;
1990 }
1991
1992 impl<'a, 'gcx, 'tcx> HasDataLayout for TyCtxt<'a, 'gcx, 'tcx> {
1993     fn data_layout(&self) -> &TargetDataLayout {
1994         &self.data_layout
1995     }
1996 }
1997
1998 impl<'a, 'gcx, 'tcx> HasTyCtxt<'gcx> for TyCtxt<'a, 'gcx, 'tcx> {
1999     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'gcx> {
2000         self.global_tcx()
2001     }
2002 }
2003
2004 impl<'a, 'gcx, 'tcx, T: Copy> HasDataLayout for (TyCtxt<'a, 'gcx, 'tcx>, T) {
2005     fn data_layout(&self) -> &TargetDataLayout {
2006         self.0.data_layout()
2007     }
2008 }
2009
2010 impl<'a, 'gcx, 'tcx, T: Copy> HasTyCtxt<'gcx> for (TyCtxt<'a, 'gcx, 'tcx>, T) {
2011     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'gcx> {
2012         self.0.tcx()
2013     }
2014 }
2015
2016 pub trait MaybeResult<T> {
2017     fn from_ok(x: T) -> Self;
2018     fn map_same<F: FnOnce(T) -> T>(self, f: F) -> Self;
2019 }
2020
2021 impl<T> MaybeResult<T> for T {
2022     fn from_ok(x: T) -> Self {
2023         x
2024     }
2025     fn map_same<F: FnOnce(T) -> T>(self, f: F) -> Self {
2026         f(self)
2027     }
2028 }
2029
2030 impl<T, E> MaybeResult<T> for Result<T, E> {
2031     fn from_ok(x: T) -> Self {
2032         Ok(x)
2033     }
2034     fn map_same<F: FnOnce(T) -> T>(self, f: F) -> Self {
2035         self.map(f)
2036     }
2037 }
2038
2039 pub trait LayoutOf<T> {
2040     type TyLayout;
2041
2042     fn layout_of(self, ty: T) -> Self::TyLayout;
2043 }
2044
2045 impl<'a, 'tcx> LayoutOf<Ty<'tcx>> for (TyCtxt<'a, 'tcx, 'tcx>, ty::ParamEnv<'tcx>) {
2046     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
2047
2048     /// Computes the layout of a type. Note that this implicitly
2049     /// executes in "reveal all" mode.
2050     #[inline]
2051     fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
2052         let (tcx, param_env) = self;
2053
2054         let ty = tcx.normalize_associated_type_in_env(&ty, param_env.reveal_all());
2055         let details = tcx.layout_raw(param_env.reveal_all().and(ty))?;
2056         let layout = TyLayout {
2057             ty,
2058             details
2059         };
2060
2061         // NB: This recording is normally disabled; when enabled, it
2062         // can however trigger recursive invocations of `layout_of`.
2063         // Therefore, we execute it *after* the main query has
2064         // completed, to avoid problems around recursive structures
2065         // and the like. (Admitedly, I wasn't able to reproduce a problem
2066         // here, but it seems like the right thing to do. -nmatsakis)
2067         LayoutDetails::record_layout_for_printing(tcx, ty, param_env, layout);
2068
2069         Ok(layout)
2070     }
2071 }
2072
2073 impl<'a, 'tcx> LayoutOf<Ty<'tcx>> for (ty::maps::TyCtxtAt<'a, 'tcx, 'tcx>,
2074                                        ty::ParamEnv<'tcx>) {
2075     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
2076
2077     /// Computes the layout of a type. Note that this implicitly
2078     /// executes in "reveal all" mode.
2079     #[inline]
2080     fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
2081         let (tcx_at, param_env) = self;
2082
2083         let ty = tcx_at.tcx.normalize_associated_type_in_env(&ty, param_env.reveal_all());
2084         let details = tcx_at.layout_raw(param_env.reveal_all().and(ty))?;
2085         let layout = TyLayout {
2086             ty,
2087             details
2088         };
2089
2090         // NB: This recording is normally disabled; when enabled, it
2091         // can however trigger recursive invocations of `layout_of`.
2092         // Therefore, we execute it *after* the main query has
2093         // completed, to avoid problems around recursive structures
2094         // and the like. (Admitedly, I wasn't able to reproduce a problem
2095         // here, but it seems like the right thing to do. -nmatsakis)
2096         LayoutDetails::record_layout_for_printing(tcx_at.tcx, ty, param_env, layout);
2097
2098         Ok(layout)
2099     }
2100 }
2101
2102 impl<'a, 'tcx> TyLayout<'tcx> {
2103     pub fn for_variant<C>(&self, cx: C, variant_index: usize) -> Self
2104         where C: LayoutOf<Ty<'tcx>> + HasTyCtxt<'tcx>,
2105               C::TyLayout: MaybeResult<TyLayout<'tcx>>
2106     {
2107         let details = match self.variants {
2108             Variants::Single { index } if index == variant_index => self.details,
2109
2110             Variants::Single { index } => {
2111                 // Deny calling for_variant more than once for non-Single enums.
2112                 cx.layout_of(self.ty).map_same(|layout| {
2113                     assert_eq!(layout.variants, Variants::Single { index });
2114                     layout
2115                 });
2116
2117                 let fields = match self.ty.sty {
2118                     ty::TyAdt(def, _) => def.variants[variant_index].fields.len(),
2119                     _ => bug!()
2120                 };
2121                 let mut details = LayoutDetails::uninhabited(fields);
2122                 details.variants = Variants::Single { index: variant_index };
2123                 cx.tcx().intern_layout(details)
2124             }
2125
2126             Variants::NicheFilling { ref variants, .. } |
2127             Variants::Tagged { ref variants, .. } => {
2128                 &variants[variant_index]
2129             }
2130         };
2131
2132         assert_eq!(details.variants, Variants::Single { index: variant_index });
2133
2134         TyLayout {
2135             ty: self.ty,
2136             details
2137         }
2138     }
2139
2140     pub fn field<C>(&self, cx: C, i: usize) -> C::TyLayout
2141         where C: LayoutOf<Ty<'tcx>> + HasTyCtxt<'tcx>,
2142               C::TyLayout: MaybeResult<TyLayout<'tcx>>
2143     {
2144         let tcx = cx.tcx();
2145         cx.layout_of(match self.ty.sty {
2146             ty::TyBool |
2147             ty::TyChar |
2148             ty::TyInt(_) |
2149             ty::TyUint(_) |
2150             ty::TyFloat(_) |
2151             ty::TyFnPtr(_) |
2152             ty::TyNever |
2153             ty::TyFnDef(..) |
2154             ty::TyGeneratorWitness(..) |
2155             ty::TyForeign(..) |
2156             ty::TyDynamic(..) => {
2157                 bug!("TyLayout::field_type({:?}): not applicable", self)
2158             }
2159
2160             // Potentially-fat pointers.
2161             ty::TyRef(_, ty::TypeAndMut { ty: pointee, .. }) |
2162             ty::TyRawPtr(ty::TypeAndMut { ty: pointee, .. }) => {
2163                 assert!(i < 2);
2164
2165                 // Reuse the fat *T type as its own thin pointer data field.
2166                 // This provides information about e.g. DST struct pointees
2167                 // (which may have no non-DST form), and will work as long
2168                 // as the `Abi` or `FieldPlacement` is checked by users.
2169                 if i == 0 {
2170                     let nil = tcx.mk_nil();
2171                     let ptr_ty = if self.ty.is_unsafe_ptr() {
2172                         tcx.mk_mut_ptr(nil)
2173                     } else {
2174                         tcx.mk_mut_ref(tcx.types.re_static, nil)
2175                     };
2176                     return cx.layout_of(ptr_ty).map_same(|mut ptr_layout| {
2177                         ptr_layout.ty = self.ty;
2178                         ptr_layout
2179                     });
2180                 }
2181
2182                 match tcx.struct_tail(pointee).sty {
2183                     ty::TySlice(_) |
2184                     ty::TyStr => tcx.types.usize,
2185                     ty::TyDynamic(..) => {
2186                         // FIXME(eddyb) use an usize/fn() array with
2187                         // the correct number of vtables slots.
2188                         tcx.mk_imm_ref(tcx.types.re_static, tcx.mk_nil())
2189                     }
2190                     _ => bug!("TyLayout::field_type({:?}): not applicable", self)
2191                 }
2192             }
2193
2194             // Arrays and slices.
2195             ty::TyArray(element, _) |
2196             ty::TySlice(element) => element,
2197             ty::TyStr => tcx.types.u8,
2198
2199             // Tuples, generators and closures.
2200             ty::TyClosure(def_id, ref substs) => {
2201                 substs.upvar_tys(def_id, tcx).nth(i).unwrap()
2202             }
2203
2204             ty::TyGenerator(def_id, ref substs, _) => {
2205                 substs.field_tys(def_id, tcx).nth(i).unwrap()
2206             }
2207
2208             ty::TyTuple(tys, _) => tys[i],
2209
2210             // SIMD vector types.
2211             ty::TyAdt(def, ..) if def.repr.simd() => {
2212                 self.ty.simd_type(tcx)
2213             }
2214
2215             // ADTs.
2216             ty::TyAdt(def, substs) => {
2217                 match self.variants {
2218                     Variants::Single { index } => {
2219                         def.variants[index].fields[i].ty(tcx, substs)
2220                     }
2221
2222                     // Discriminant field for enums (where applicable).
2223                     Variants::Tagged { ref discr, .. } |
2224                     Variants::NicheFilling { niche: ref discr, .. } => {
2225                         assert_eq!(i, 0);
2226                         let layout = LayoutDetails::scalar(tcx, discr.clone());
2227                         return MaybeResult::from_ok(TyLayout {
2228                             details: tcx.intern_layout(layout),
2229                             ty: discr.value.to_ty(tcx)
2230                         });
2231                     }
2232                 }
2233             }
2234
2235             ty::TyProjection(_) | ty::TyAnon(..) | ty::TyParam(_) |
2236             ty::TyInfer(_) | ty::TyError => {
2237                 bug!("TyLayout::field_type: unexpected type `{}`", self.ty)
2238             }
2239         })
2240     }
2241
2242     /// Returns true if the layout corresponds to an unsized type.
2243     pub fn is_unsized(&self) -> bool {
2244         self.abi.is_unsized()
2245     }
2246
2247     /// Returns true if the type is a ZST and not unsized.
2248     pub fn is_zst(&self) -> bool {
2249         match self.abi {
2250             Abi::Uninhabited => true,
2251             Abi::Scalar(_) |
2252             Abi::ScalarPair(..) |
2253             Abi::Vector { .. } => false,
2254             Abi::Aggregate { sized } => sized && self.size.bytes() == 0
2255         }
2256     }
2257
2258     pub fn size_and_align(&self) -> (Size, Align) {
2259         (self.size, self.align)
2260     }
2261
2262     /// Find the offset of a niche leaf field, starting from
2263     /// the given type and recursing through aggregates, which
2264     /// has at least `count` consecutive invalid values.
2265     /// The tuple is `(offset, scalar, niche_value)`.
2266     // FIXME(eddyb) traverse already optimized enums.
2267     fn find_niche<C>(&self, cx: C, count: u128)
2268         -> Result<Option<(Size, Scalar, u128)>, LayoutError<'tcx>>
2269         where C: LayoutOf<Ty<'tcx>, TyLayout = Result<Self, LayoutError<'tcx>>> +
2270                  HasTyCtxt<'tcx>
2271     {
2272         let scalar_component = |scalar: &Scalar, offset| {
2273             let Scalar { value, valid_range: ref v } = *scalar;
2274
2275             let bits = value.size(cx).bits();
2276             assert!(bits <= 128);
2277             let max_value = !0u128 >> (128 - bits);
2278
2279             // Find out how many values are outside the valid range.
2280             let niches = if v.start <= v.end {
2281                 v.start + (max_value - v.end)
2282             } else {
2283                 v.start - v.end - 1
2284             };
2285
2286             // Give up if we can't fit `count` consecutive niches.
2287             if count > niches {
2288                 return None;
2289             }
2290
2291             let niche_start = v.end.wrapping_add(1) & max_value;
2292             let niche_end = v.end.wrapping_add(count) & max_value;
2293             Some((offset, Scalar {
2294                 value,
2295                 valid_range: v.start..=niche_end
2296             }, niche_start))
2297         };
2298
2299         // Locals variables which live across yields are stored
2300         // in the generator type as fields. These may be uninitialized
2301         // so we don't look for niches there.
2302         if let ty::TyGenerator(..) = self.ty.sty {
2303             return Ok(None);
2304         }
2305
2306         match self.abi {
2307             Abi::Scalar(ref scalar) => {
2308                 return Ok(scalar_component(scalar, Size::from_bytes(0)));
2309             }
2310             Abi::ScalarPair(ref a, ref b) => {
2311                 return Ok(scalar_component(a, Size::from_bytes(0)).or_else(|| {
2312                     scalar_component(b, a.value.size(cx).abi_align(b.value.align(cx)))
2313                 }));
2314             }
2315             Abi::Vector { ref element, .. } => {
2316                 return Ok(scalar_component(element, Size::from_bytes(0)));
2317             }
2318             _ => {}
2319         }
2320
2321         // Perhaps one of the fields is non-zero, let's recurse and find out.
2322         if let FieldPlacement::Union(_) = self.fields {
2323             // Only Rust enums have safe-to-inspect fields
2324             // (a discriminant), other unions are unsafe.
2325             if let Variants::Single { .. } = self.variants {
2326                 return Ok(None);
2327             }
2328         }
2329         if let FieldPlacement::Array { .. } = self.fields {
2330             if self.fields.count() > 0 {
2331                 return self.field(cx, 0)?.find_niche(cx, count);
2332             }
2333         }
2334         for i in 0..self.fields.count() {
2335             let r = self.field(cx, i)?.find_niche(cx, count)?;
2336             if let Some((offset, scalar, niche_value)) = r {
2337                 let offset = self.fields.offset(i) + offset;
2338                 return Ok(Some((offset, scalar, niche_value)));
2339             }
2340         }
2341         Ok(None)
2342     }
2343 }
2344
2345 impl<'gcx> HashStable<StableHashingContext<'gcx>> for Variants {
2346     fn hash_stable<W: StableHasherResult>(&self,
2347                                           hcx: &mut StableHashingContext<'gcx>,
2348                                           hasher: &mut StableHasher<W>) {
2349         use ty::layout::Variants::*;
2350         mem::discriminant(self).hash_stable(hcx, hasher);
2351
2352         match *self {
2353             Single { index } => {
2354                 index.hash_stable(hcx, hasher);
2355             }
2356             Tagged {
2357                 ref discr,
2358                 ref variants,
2359             } => {
2360                 discr.hash_stable(hcx, hasher);
2361                 variants.hash_stable(hcx, hasher);
2362             }
2363             NicheFilling {
2364                 dataful_variant,
2365                 niche_variants: RangeInclusive { start, end },
2366                 ref niche,
2367                 niche_start,
2368                 ref variants,
2369             } => {
2370                 dataful_variant.hash_stable(hcx, hasher);
2371                 start.hash_stable(hcx, hasher);
2372                 end.hash_stable(hcx, hasher);
2373                 niche.hash_stable(hcx, hasher);
2374                 niche_start.hash_stable(hcx, hasher);
2375                 variants.hash_stable(hcx, hasher);
2376             }
2377         }
2378     }
2379 }
2380
2381 impl<'gcx> HashStable<StableHashingContext<'gcx>> for FieldPlacement {
2382     fn hash_stable<W: StableHasherResult>(&self,
2383                                           hcx: &mut StableHashingContext<'gcx>,
2384                                           hasher: &mut StableHasher<W>) {
2385         use ty::layout::FieldPlacement::*;
2386         mem::discriminant(self).hash_stable(hcx, hasher);
2387
2388         match *self {
2389             Union(count) => {
2390                 count.hash_stable(hcx, hasher);
2391             }
2392             Array { count, stride } => {
2393                 count.hash_stable(hcx, hasher);
2394                 stride.hash_stable(hcx, hasher);
2395             }
2396             Arbitrary { ref offsets, ref memory_index } => {
2397                 offsets.hash_stable(hcx, hasher);
2398                 memory_index.hash_stable(hcx, hasher);
2399             }
2400         }
2401     }
2402 }
2403
2404 impl<'gcx> HashStable<StableHashingContext<'gcx>> for Abi {
2405     fn hash_stable<W: StableHasherResult>(&self,
2406                                           hcx: &mut StableHashingContext<'gcx>,
2407                                           hasher: &mut StableHasher<W>) {
2408         use ty::layout::Abi::*;
2409         mem::discriminant(self).hash_stable(hcx, hasher);
2410
2411         match *self {
2412             Uninhabited => {}
2413             Scalar(ref value) => {
2414                 value.hash_stable(hcx, hasher);
2415             }
2416             ScalarPair(ref a, ref b) => {
2417                 a.hash_stable(hcx, hasher);
2418                 b.hash_stable(hcx, hasher);
2419             }
2420             Vector { ref element, count } => {
2421                 element.hash_stable(hcx, hasher);
2422                 count.hash_stable(hcx, hasher);
2423             }
2424             Aggregate { sized } => {
2425                 sized.hash_stable(hcx, hasher);
2426             }
2427         }
2428     }
2429 }
2430
2431 impl<'gcx> HashStable<StableHashingContext<'gcx>> for Scalar {
2432     fn hash_stable<W: StableHasherResult>(&self,
2433                                           hcx: &mut StableHashingContext<'gcx>,
2434                                           hasher: &mut StableHasher<W>) {
2435         let Scalar { value, valid_range: RangeInclusive { start, end } } = *self;
2436         value.hash_stable(hcx, hasher);
2437         start.hash_stable(hcx, hasher);
2438         end.hash_stable(hcx, hasher);
2439     }
2440 }
2441
2442 impl_stable_hash_for!(struct ::ty::layout::LayoutDetails {
2443     variants,
2444     fields,
2445     abi,
2446     size,
2447     align
2448 });
2449
2450 impl_stable_hash_for!(enum ::ty::layout::Integer {
2451     I8,
2452     I16,
2453     I32,
2454     I64,
2455     I128
2456 });
2457
2458 impl_stable_hash_for!(enum ::ty::layout::Primitive {
2459     Int(integer, signed),
2460     F32,
2461     F64,
2462     Pointer
2463 });
2464
2465 impl_stable_hash_for!(struct ::ty::layout::Align {
2466     abi,
2467     pref
2468 });
2469
2470 impl_stable_hash_for!(struct ::ty::layout::Size {
2471     raw
2472 });
2473
2474 impl<'gcx> HashStable<StableHashingContext<'gcx>> for LayoutError<'gcx>
2475 {
2476     fn hash_stable<W: StableHasherResult>(&self,
2477                                           hcx: &mut StableHashingContext<'gcx>,
2478                                           hasher: &mut StableHasher<W>) {
2479         use ty::layout::LayoutError::*;
2480         mem::discriminant(self).hash_stable(hcx, hasher);
2481
2482         match *self {
2483             Unknown(t) |
2484             SizeOverflow(t) => t.hash_stable(hcx, hasher)
2485         }
2486     }
2487 }