]> git.lizzy.rs Git - rust.git/blob - src/librustc_target/abi/mod.rs
Simplify SaveHandler trait
[rust.git] / src / librustc_target / abi / mod.rs
1 pub use Integer::*;
2 pub use Primitive::*;
3
4 use crate::spec::Target;
5
6 use std::fmt;
7 use std::ops::{Add, Deref, Sub, Mul, AddAssign, Range, RangeInclusive};
8
9 use rustc_data_structures::newtype_index;
10 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
11 use syntax_pos::symbol::{sym, Symbol};
12
13 pub mod call;
14
15 /// Parsed [Data layout](http://llvm.org/docs/LangRef.html#data-layout)
16 /// for a target, which contains everything needed to compute layouts.
17 pub struct TargetDataLayout {
18     pub endian: Endian,
19     pub i1_align: AbiAndPrefAlign,
20     pub i8_align: AbiAndPrefAlign,
21     pub i16_align: AbiAndPrefAlign,
22     pub i32_align: AbiAndPrefAlign,
23     pub i64_align: AbiAndPrefAlign,
24     pub i128_align: AbiAndPrefAlign,
25     pub f32_align: AbiAndPrefAlign,
26     pub f64_align: AbiAndPrefAlign,
27     pub pointer_size: Size,
28     pub pointer_align: AbiAndPrefAlign,
29     pub aggregate_align: AbiAndPrefAlign,
30
31     /// Alignments for vector types.
32     pub vector_align: Vec<(Size, AbiAndPrefAlign)>,
33
34     pub instruction_address_space: u32,
35 }
36
37 impl Default for TargetDataLayout {
38     /// Creates an instance of `TargetDataLayout`.
39     fn default() -> TargetDataLayout {
40         let align = |bits| Align::from_bits(bits).unwrap();
41         TargetDataLayout {
42             endian: Endian::Big,
43             i1_align: AbiAndPrefAlign::new(align(8)),
44             i8_align: AbiAndPrefAlign::new(align(8)),
45             i16_align: AbiAndPrefAlign::new(align(16)),
46             i32_align: AbiAndPrefAlign::new(align(32)),
47             i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
48             i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
49             f32_align: AbiAndPrefAlign::new(align(32)),
50             f64_align: AbiAndPrefAlign::new(align(64)),
51             pointer_size: Size::from_bits(64),
52             pointer_align: AbiAndPrefAlign::new(align(64)),
53             aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) },
54             vector_align: vec![
55                 (Size::from_bits(64), AbiAndPrefAlign::new(align(64))),
56                 (Size::from_bits(128), AbiAndPrefAlign::new(align(128))),
57             ],
58             instruction_address_space: 0,
59         }
60     }
61 }
62
63 impl TargetDataLayout {
64     pub fn parse(target: &Target) -> Result<TargetDataLayout, String> {
65         // Parse an address space index from a string.
66         let parse_address_space = |s: &str, cause: &str| {
67             s.parse::<u32>().map_err(|err| {
68                 format!("invalid address space `{}` for `{}` in \"data-layout\": {}",
69                         s, cause, err)
70             })
71         };
72
73         // Parse a bit count from a string.
74         let parse_bits = |s: &str, kind: &str, cause: &str| {
75             s.parse::<u64>().map_err(|err| {
76                 format!("invalid {} `{}` for `{}` in \"data-layout\": {}",
77                         kind, s, cause, err)
78             })
79         };
80
81         // Parse a size string.
82         let size = |s: &str, cause: &str| {
83             parse_bits(s, "size", cause).map(Size::from_bits)
84         };
85
86         // Parse an alignment string.
87         let align = |s: &[&str], cause: &str| {
88             if s.is_empty() {
89                 return Err(format!("missing alignment for `{}` in \"data-layout\"", cause));
90             }
91             let align_from_bits = |bits| {
92                 Align::from_bits(bits).map_err(|err| {
93                     format!("invalid alignment for `{}` in \"data-layout\": {}",
94                             cause, err)
95                 })
96             };
97             let abi = parse_bits(s[0], "alignment", cause)?;
98             let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?;
99             Ok(AbiAndPrefAlign {
100                 abi: align_from_bits(abi)?,
101                 pref: align_from_bits(pref)?,
102             })
103         };
104
105         let mut dl = TargetDataLayout::default();
106         let mut i128_align_src = 64;
107         for spec in target.data_layout.split('-') {
108             match spec.split(':').collect::<Vec<_>>()[..] {
109                 ["e"] => dl.endian = Endian::Little,
110                 ["E"] => dl.endian = Endian::Big,
111                 [p] if p.starts_with("P") => {
112                     dl.instruction_address_space = parse_address_space(&p[1..], "P")?
113                 }
114                 ["a", ref a..] => dl.aggregate_align = align(a, "a")?,
115                 ["f32", ref a..] => dl.f32_align = align(a, "f32")?,
116                 ["f64", ref a..] => dl.f64_align = align(a, "f64")?,
117                 [p @ "p", s, ref a..] | [p @ "p0", s, ref a..] => {
118                     dl.pointer_size = size(s, p)?;
119                     dl.pointer_align = align(a, p)?;
120                 }
121                 [s, ref a..] if s.starts_with("i") => {
122                     let bits = match s[1..].parse::<u64>() {
123                         Ok(bits) => bits,
124                         Err(_) => {
125                             size(&s[1..], "i")?; // For the user error.
126                             continue;
127                         }
128                     };
129                     let a = align(a, s)?;
130                     match bits {
131                         1 => dl.i1_align = a,
132                         8 => dl.i8_align = a,
133                         16 => dl.i16_align = a,
134                         32 => dl.i32_align = a,
135                         64 => dl.i64_align = a,
136                         _ => {}
137                     }
138                     if bits >= i128_align_src && bits <= 128 {
139                         // Default alignment for i128 is decided by taking the alignment of
140                         // largest-sized i{64..=128}.
141                         i128_align_src = bits;
142                         dl.i128_align = a;
143                     }
144                 }
145                 [s, ref a..] if s.starts_with("v") => {
146                     let v_size = size(&s[1..], "v")?;
147                     let a = align(a, s)?;
148                     if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) {
149                         v.1 = a;
150                         continue;
151                     }
152                     // No existing entry, add a new one.
153                     dl.vector_align.push((v_size, a));
154                 }
155                 _ => {} // Ignore everything else.
156             }
157         }
158
159         // Perform consistency checks against the Target information.
160         let endian_str = match dl.endian {
161             Endian::Little => "little",
162             Endian::Big => "big"
163         };
164         if endian_str != target.target_endian {
165             return Err(format!("inconsistent target specification: \"data-layout\" claims \
166                                 architecture is {}-endian, while \"target-endian\" is `{}`",
167                                endian_str, target.target_endian));
168         }
169
170         if dl.pointer_size.bits().to_string() != target.target_pointer_width {
171             return Err(format!("inconsistent target specification: \"data-layout\" claims \
172                                 pointers are {}-bit, while \"target-pointer-width\" is `{}`",
173                                dl.pointer_size.bits(), target.target_pointer_width));
174         }
175
176         Ok(dl)
177     }
178
179     /// Returns exclusive upper bound on object size.
180     ///
181     /// The theoretical maximum object size is defined as the maximum positive `isize` value.
182     /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly
183     /// index every address within an object along with one byte past the end, along with allowing
184     /// `isize` to store the difference between any two pointers into an object.
185     ///
186     /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer
187     /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is
188     /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable
189     /// address space on 64-bit ARMv8 and x86_64.
190     pub fn obj_size_bound(&self) -> u64 {
191         match self.pointer_size.bits() {
192             16 => 1 << 15,
193             32 => 1 << 31,
194             64 => 1 << 47,
195             bits => panic!("obj_size_bound: unknown pointer bit size {}", bits)
196         }
197     }
198
199     pub fn ptr_sized_integer(&self) -> Integer {
200         match self.pointer_size.bits() {
201             16 => I16,
202             32 => I32,
203             64 => I64,
204             bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits)
205         }
206     }
207
208     pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign {
209         for &(size, align) in &self.vector_align {
210             if size == vec_size {
211                 return align;
212             }
213         }
214         // Default to natural alignment, which is what LLVM does.
215         // That is, use the size, rounded up to a power of 2.
216         AbiAndPrefAlign::new(Align::from_bytes(vec_size.bytes().next_power_of_two()).unwrap())
217     }
218 }
219
220 pub trait HasDataLayout {
221     fn data_layout(&self) -> &TargetDataLayout;
222 }
223
224 impl HasDataLayout for TargetDataLayout {
225     fn data_layout(&self) -> &TargetDataLayout {
226         self
227     }
228 }
229
230 /// Endianness of the target, which must match cfg(target-endian).
231 #[derive(Copy, Clone, PartialEq)]
232 pub enum Endian {
233     Little,
234     Big
235 }
236
237 /// Size of a type in bytes.
238 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
239 pub struct Size {
240     raw: u64
241 }
242
243 impl Size {
244     pub const ZERO: Size = Self::from_bytes(0);
245
246     #[inline]
247     pub fn from_bits(bits: u64) -> Size {
248         // Avoid potential overflow from `bits + 7`.
249         Size::from_bytes(bits / 8 + ((bits % 8) + 7) / 8)
250     }
251
252     #[inline]
253     pub const fn from_bytes(bytes: u64) -> Size {
254         Size {
255             raw: bytes
256         }
257     }
258
259     #[inline]
260     pub fn bytes(self) -> u64 {
261         self.raw
262     }
263
264     #[inline]
265     pub fn bits(self) -> u64 {
266         self.bytes().checked_mul(8).unwrap_or_else(|| {
267             panic!("Size::bits: {} bytes in bits doesn't fit in u64", self.bytes())
268         })
269     }
270
271     #[inline]
272     pub fn align_to(self, align: Align) -> Size {
273         let mask = align.bytes() - 1;
274         Size::from_bytes((self.bytes() + mask) & !mask)
275     }
276
277     #[inline]
278     pub fn is_aligned(self, align: Align) -> bool {
279         let mask = align.bytes() - 1;
280         self.bytes() & mask == 0
281     }
282
283     #[inline]
284     pub fn checked_add<C: HasDataLayout>(self, offset: Size, cx: &C) -> Option<Size> {
285         let dl = cx.data_layout();
286
287         let bytes = self.bytes().checked_add(offset.bytes())?;
288
289         if bytes < dl.obj_size_bound() {
290             Some(Size::from_bytes(bytes))
291         } else {
292             None
293         }
294     }
295
296     #[inline]
297     pub fn checked_mul<C: HasDataLayout>(self, count: u64, cx: &C) -> Option<Size> {
298         let dl = cx.data_layout();
299
300         let bytes = self.bytes().checked_mul(count)?;
301         if bytes < dl.obj_size_bound() {
302             Some(Size::from_bytes(bytes))
303         } else {
304             None
305         }
306     }
307 }
308
309 // Panicking addition, subtraction and multiplication for convenience.
310 // Avoid during layout computation, return `LayoutError` instead.
311
312 impl Add for Size {
313     type Output = Size;
314     #[inline]
315     fn add(self, other: Size) -> Size {
316         Size::from_bytes(self.bytes().checked_add(other.bytes()).unwrap_or_else(|| {
317             panic!("Size::add: {} + {} doesn't fit in u64", self.bytes(), other.bytes())
318         }))
319     }
320 }
321
322 impl Sub for Size {
323     type Output = Size;
324     #[inline]
325     fn sub(self, other: Size) -> Size {
326         Size::from_bytes(self.bytes().checked_sub(other.bytes()).unwrap_or_else(|| {
327             panic!("Size::sub: {} - {} would result in negative size", self.bytes(), other.bytes())
328         }))
329     }
330 }
331
332 impl Mul<Size> for u64 {
333     type Output = Size;
334     #[inline]
335     fn mul(self, size: Size) -> Size {
336         size * self
337     }
338 }
339
340 impl Mul<u64> for Size {
341     type Output = Size;
342     #[inline]
343     fn mul(self, count: u64) -> Size {
344         match self.bytes().checked_mul(count) {
345             Some(bytes) => Size::from_bytes(bytes),
346             None => {
347                 panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count)
348             }
349         }
350     }
351 }
352
353 impl AddAssign for Size {
354     #[inline]
355     fn add_assign(&mut self, other: Size) {
356         *self = *self + other;
357     }
358 }
359
360 /// Alignment of a type in bytes (always a power of two).
361 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
362 pub struct Align {
363     pow2: u8,
364 }
365
366 impl Align {
367     pub fn from_bits(bits: u64) -> Result<Align, String> {
368         Align::from_bytes(Size::from_bits(bits).bytes())
369     }
370
371     pub fn from_bytes(align: u64) -> Result<Align, String> {
372         // Treat an alignment of 0 bytes like 1-byte alignment.
373         if align == 0 {
374             return Ok(Align { pow2: 0 });
375         }
376
377         let mut bytes = align;
378         let mut pow2: u8 = 0;
379         while (bytes & 1) == 0 {
380             pow2 += 1;
381             bytes >>= 1;
382         }
383         if bytes != 1 {
384             return Err(format!("`{}` is not a power of 2", align));
385         }
386         if pow2 > 29 {
387             return Err(format!("`{}` is too large", align));
388         }
389
390         Ok(Align { pow2 })
391     }
392
393     pub fn bytes(self) -> u64 {
394         1 << self.pow2
395     }
396
397     pub fn bits(self) -> u64 {
398         self.bytes() * 8
399     }
400
401     /// Computes the best alignment possible for the given offset
402     /// (the largest power of two that the offset is a multiple of).
403     ///
404     /// N.B., for an offset of `0`, this happens to return `2^64`.
405     pub fn max_for_offset(offset: Size) -> Align {
406         Align {
407             pow2: offset.bytes().trailing_zeros() as u8,
408         }
409     }
410
411     /// Lower the alignment, if necessary, such that the given offset
412     /// is aligned to it (the offset is a multiple of the alignment).
413     pub fn restrict_for_offset(self, offset: Size) -> Align {
414         self.min(Align::max_for_offset(offset))
415     }
416 }
417
418 /// A pair of aligments, ABI-mandated and preferred.
419 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
420 pub struct AbiAndPrefAlign {
421     pub abi: Align,
422     pub pref: Align,
423 }
424
425 impl AbiAndPrefAlign {
426     pub fn new(align: Align) -> AbiAndPrefAlign {
427         AbiAndPrefAlign {
428             abi: align,
429             pref: align,
430         }
431     }
432
433     pub fn min(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
434         AbiAndPrefAlign {
435             abi: self.abi.min(other.abi),
436             pref: self.pref.min(other.pref),
437         }
438     }
439
440     pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
441         AbiAndPrefAlign {
442             abi: self.abi.max(other.abi),
443             pref: self.pref.max(other.pref),
444         }
445     }
446 }
447
448 /// Integers, also used for enum discriminants.
449 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
450 pub enum Integer {
451     I8,
452     I16,
453     I32,
454     I64,
455     I128,
456 }
457
458 impl Integer {
459     pub fn size(self) -> Size {
460         match self {
461             I8 => Size::from_bytes(1),
462             I16 => Size::from_bytes(2),
463             I32 => Size::from_bytes(4),
464             I64  => Size::from_bytes(8),
465             I128  => Size::from_bytes(16),
466         }
467     }
468
469     pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
470         let dl = cx.data_layout();
471
472         match self {
473             I8 => dl.i8_align,
474             I16 => dl.i16_align,
475             I32 => dl.i32_align,
476             I64 => dl.i64_align,
477             I128 => dl.i128_align,
478         }
479     }
480
481     /// Finds the smallest Integer type which can represent the signed value.
482     pub fn fit_signed(x: i128) -> Integer {
483         match x {
484             -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8,
485             -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16,
486             -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32,
487             -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64,
488             _ => I128
489         }
490     }
491
492     /// Finds the smallest Integer type which can represent the unsigned value.
493     pub fn fit_unsigned(x: u128) -> Integer {
494         match x {
495             0..=0x0000_0000_0000_00ff => I8,
496             0..=0x0000_0000_0000_ffff => I16,
497             0..=0x0000_0000_ffff_ffff => I32,
498             0..=0xffff_ffff_ffff_ffff => I64,
499             _ => I128,
500         }
501     }
502
503     /// Finds the smallest integer with the given alignment.
504     pub fn for_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Option<Integer> {
505         let dl = cx.data_layout();
506
507         for &candidate in &[I8, I16, I32, I64, I128] {
508             if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() {
509                 return Some(candidate);
510             }
511         }
512         None
513     }
514
515     /// Find the largest integer with the given alignment or less.
516     pub fn approximate_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Integer {
517         let dl = cx.data_layout();
518
519         // FIXME(eddyb) maybe include I128 in the future, when it works everywhere.
520         for &candidate in &[I64, I32, I16] {
521             if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() {
522                 return candidate;
523             }
524         }
525         I8
526     }
527 }
528
529
530 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
531          PartialOrd, Ord)]
532 pub enum FloatTy {
533     F32,
534     F64,
535 }
536
537 impl fmt::Debug for FloatTy {
538     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539         fmt::Display::fmt(self, f)
540     }
541 }
542
543 impl fmt::Display for FloatTy {
544     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545         write!(f, "{}", self.ty_to_string())
546     }
547 }
548
549 impl FloatTy {
550     pub fn ty_to_string(self) -> &'static str {
551         match self {
552             FloatTy::F32 => "f32",
553             FloatTy::F64 => "f64",
554         }
555     }
556
557     pub fn to_symbol(self) -> Symbol {
558         match self {
559             FloatTy::F32 => sym::f32,
560             FloatTy::F64 => sym::f64,
561         }
562     }
563
564     pub fn bit_width(self) -> usize {
565         match self {
566             FloatTy::F32 => 32,
567             FloatTy::F64 => 64,
568         }
569     }
570 }
571
572 /// Fundamental unit of memory access and layout.
573 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
574 pub enum Primitive {
575     /// The `bool` is the signedness of the `Integer` type.
576     ///
577     /// One would think we would not care about such details this low down,
578     /// but some ABIs are described in terms of C types and ISAs where the
579     /// integer arithmetic is done on {sign,zero}-extended registers, e.g.
580     /// a negative integer passed by zero-extension will appear positive in
581     /// the callee, and most operations on it will produce the wrong values.
582     Int(Integer, bool),
583     Float(FloatTy),
584     Pointer
585 }
586
587 impl Primitive {
588     pub fn size<C: HasDataLayout>(self, cx: &C) -> Size {
589         let dl = cx.data_layout();
590
591         match self {
592             Int(i, _) => i.size(),
593             Float(FloatTy::F32) => Size::from_bits(32),
594             Float(FloatTy::F64) => Size::from_bits(64),
595             Pointer => dl.pointer_size
596         }
597     }
598
599     pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
600         let dl = cx.data_layout();
601
602         match self {
603             Int(i, _) => i.align(dl),
604             Float(FloatTy::F32) => dl.f32_align,
605             Float(FloatTy::F64) => dl.f64_align,
606             Pointer => dl.pointer_align
607         }
608     }
609
610     pub fn is_float(self) -> bool {
611         match self {
612             Float(_) => true,
613             _ => false
614         }
615     }
616
617     pub fn is_int(self) -> bool {
618         match self {
619             Int(..) => true,
620             _ => false,
621         }
622     }
623 }
624
625 /// Information about one scalar component of a Rust type.
626 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
627 pub struct Scalar {
628     pub value: Primitive,
629
630     /// Inclusive wrap-around range of valid values, that is, if
631     /// start > end, it represents `start..=max_value()`,
632     /// followed by `0..=end`.
633     ///
634     /// That is, for an i8 primitive, a range of `254..=2` means following
635     /// sequence:
636     ///
637     ///    254 (-2), 255 (-1), 0, 1, 2
638     ///
639     /// This is intended specifically to mirror LLVM’s `!range` metadata,
640     /// semantics.
641     // FIXME(eddyb) always use the shortest range, e.g., by finding
642     // the largest space between two consecutive valid values and
643     // taking everything else as the (shortest) valid range.
644     pub valid_range: RangeInclusive<u128>,
645 }
646
647 impl Scalar {
648     pub fn is_bool(&self) -> bool {
649         if let Int(I8, _) = self.value {
650             self.valid_range == (0..=1)
651         } else {
652             false
653         }
654     }
655
656     /// Returns the valid range as a `x..y` range.
657     ///
658     /// If `x` and `y` are equal, the range is full, not empty.
659     pub fn valid_range_exclusive<C: HasDataLayout>(&self, cx: &C) -> Range<u128> {
660         // For a (max) value of -1, max will be `-1 as usize`, which overflows.
661         // However, that is fine here (it would still represent the full range),
662         // i.e., if the range is everything.
663         let bits = self.value.size(cx).bits();
664         assert!(bits <= 128);
665         let mask = !0u128 >> (128 - bits);
666         let start = *self.valid_range.start();
667         let end = *self.valid_range.end();
668         assert_eq!(start, start & mask);
669         assert_eq!(end, end & mask);
670         start..(end.wrapping_add(1) & mask)
671     }
672 }
673
674 /// Describes how the fields of a type are located in memory.
675 #[derive(PartialEq, Eq, Hash, Debug)]
676 pub enum FieldPlacement {
677     /// All fields start at no offset. The `usize` is the field count.
678     ///
679     /// In the case of primitives the number of fields is `0`.
680     Union(usize),
681
682     /// Array/vector-like placement, with all fields of identical types.
683     Array {
684         stride: Size,
685         count: u64
686     },
687
688     /// Struct-like placement, with precomputed offsets.
689     ///
690     /// Fields are guaranteed to not overlap, but note that gaps
691     /// before, between and after all the fields are NOT always
692     /// padding, and as such their contents may not be discarded.
693     /// For example, enum variants leave a gap at the start,
694     /// where the discriminant field in the enum layout goes.
695     Arbitrary {
696         /// Offsets for the first byte of each field,
697         /// ordered to match the source definition order.
698         /// This vector does not go in increasing order.
699         // FIXME(eddyb) use small vector optimization for the common case.
700         offsets: Vec<Size>,
701
702         /// Maps source order field indices to memory order indices,
703         /// depending on how the fields were reordered (if at all).
704         /// This is a permutation, with both the source order and the
705         /// memory order using the same (0..n) index ranges.
706         ///
707         /// Note that during computation of `memory_index`, sometimes
708         /// it is easier to operate on the inverse mapping (that is,
709         /// from memory order to source order), and that is usually
710         /// named `inverse_memory_index`.
711         ///
712         // FIXME(eddyb) build a better abstraction for permutations, if possible.
713         // FIXME(camlorn) also consider small vector  optimization here.
714         memory_index: Vec<u32>
715     }
716 }
717
718 impl FieldPlacement {
719     pub fn count(&self) -> usize {
720         match *self {
721             FieldPlacement::Union(count) => count,
722             FieldPlacement::Array { count, .. } => {
723                 let usize_count = count as usize;
724                 assert_eq!(usize_count as u64, count);
725                 usize_count
726             }
727             FieldPlacement::Arbitrary { ref offsets, .. } => offsets.len()
728         }
729     }
730
731     pub fn offset(&self, i: usize) -> Size {
732         match *self {
733             FieldPlacement::Union(_) => Size::ZERO,
734             FieldPlacement::Array { stride, count } => {
735                 let i = i as u64;
736                 assert!(i < count);
737                 stride * i
738             }
739             FieldPlacement::Arbitrary { ref offsets, .. } => offsets[i]
740         }
741     }
742
743     pub fn memory_index(&self, i: usize) -> usize {
744         match *self {
745             FieldPlacement::Union(_) |
746             FieldPlacement::Array { .. } => i,
747             FieldPlacement::Arbitrary { ref memory_index, .. } => {
748                 let r = memory_index[i];
749                 assert_eq!(r as usize as u32, r);
750                 r as usize
751             }
752         }
753     }
754
755     /// Gets source indices of the fields by increasing offsets.
756     #[inline]
757     pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator<Item=usize>+'a {
758         let mut inverse_small = [0u8; 64];
759         let mut inverse_big = vec![];
760         let use_small = self.count() <= inverse_small.len();
761
762         // We have to write this logic twice in order to keep the array small.
763         if let FieldPlacement::Arbitrary { ref memory_index, .. } = *self {
764             if use_small {
765                 for i in 0..self.count() {
766                     inverse_small[memory_index[i] as usize] = i as u8;
767                 }
768             } else {
769                 inverse_big = vec![0; self.count()];
770                 for i in 0..self.count() {
771                     inverse_big[memory_index[i] as usize] = i as u32;
772                 }
773             }
774         }
775
776         (0..self.count()).map(move |i| {
777             match *self {
778                 FieldPlacement::Union(_) |
779                 FieldPlacement::Array { .. } => i,
780                 FieldPlacement::Arbitrary { .. } => {
781                     if use_small { inverse_small[i] as usize }
782                     else { inverse_big[i] as usize }
783                 }
784             }
785         })
786     }
787 }
788
789 /// Describes how values of the type are passed by target ABIs,
790 /// in terms of categories of C types there are ABI rules for.
791 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
792 pub enum Abi {
793     Uninhabited,
794     Scalar(Scalar),
795     ScalarPair(Scalar, Scalar),
796     Vector {
797         element: Scalar,
798         count: u64
799     },
800     Aggregate {
801         /// If true, the size is exact, otherwise it's only a lower bound.
802         sized: bool,
803     }
804 }
805
806 impl Abi {
807     /// Returns `true` if the layout corresponds to an unsized type.
808     pub fn is_unsized(&self) -> bool {
809         match *self {
810             Abi::Uninhabited |
811             Abi::Scalar(_) |
812             Abi::ScalarPair(..) |
813             Abi::Vector { .. } => false,
814             Abi::Aggregate { sized } => !sized
815         }
816     }
817
818     /// Returns `true` if this is a single signed integer scalar
819     pub fn is_signed(&self) -> bool {
820         match *self {
821             Abi::Scalar(ref scal) => match scal.value {
822                 Primitive::Int(_, signed) => signed,
823                 _ => false,
824             },
825             _ => false,
826         }
827     }
828
829     /// Returns `true` if this is an uninhabited type
830     pub fn is_uninhabited(&self) -> bool {
831         match *self {
832             Abi::Uninhabited => true,
833             _ => false,
834         }
835     }
836 }
837
838 newtype_index! {
839     pub struct VariantIdx { .. }
840 }
841
842 #[derive(PartialEq, Eq, Hash, Debug)]
843 pub enum Variants {
844     /// Single enum variants, structs/tuples, unions, and all non-ADTs.
845     Single {
846         index: VariantIdx,
847     },
848
849     /// Enum-likes with more than one inhabited variant: for each case there is
850     /// a struct, and they all have space reserved for the discriminant.
851     /// For enums this is the sole field of the layout.
852     Multiple {
853         discr: Scalar,
854         discr_kind: DiscriminantKind,
855         discr_index: usize,
856         variants: IndexVec<VariantIdx, LayoutDetails>,
857     },
858 }
859
860 #[derive(PartialEq, Eq, Hash, Debug)]
861 pub enum DiscriminantKind {
862     /// Integer tag holding the discriminant value itself.
863     Tag,
864
865     /// Niche (values invalid for a type) encoding the discriminant:
866     /// the variant `dataful_variant` contains a niche at an arbitrary
867     /// offset (field `discr_index` of the enum), which for a variant with
868     /// discriminant `d` is set to
869     /// `(d - niche_variants.start).wrapping_add(niche_start)`.
870     ///
871     /// For example, `Option<(usize, &T)>`  is represented such that
872     /// `None` has a null pointer for the second tuple field, and
873     /// `Some` is the identity function (with a non-null reference).
874     Niche {
875         dataful_variant: VariantIdx,
876         niche_variants: RangeInclusive<VariantIdx>,
877         niche_start: u128,
878     },
879 }
880
881 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
882 pub struct Niche {
883     pub offset: Size,
884     pub scalar: Scalar,
885 }
886
887 impl Niche {
888     pub fn from_scalar<C: HasDataLayout>(cx: &C, offset: Size, scalar: Scalar) -> Option<Self> {
889         let niche = Niche {
890             offset,
891             scalar,
892         };
893         if niche.available(cx) > 0 {
894             Some(niche)
895         } else {
896             None
897         }
898     }
899
900     pub fn available<C: HasDataLayout>(&self, cx: &C) -> u128 {
901         let Scalar { value, valid_range: ref v } = self.scalar;
902         let bits = value.size(cx).bits();
903         assert!(bits <= 128);
904         let max_value = !0u128 >> (128 - bits);
905
906         // Find out how many values are outside the valid range.
907         let niche = v.end().wrapping_add(1)..*v.start();
908         niche.end.wrapping_sub(niche.start) & max_value
909     }
910
911     pub fn reserve<C: HasDataLayout>(&self, cx: &C, count: u128) -> Option<(u128, Scalar)> {
912         assert!(count > 0);
913
914         let Scalar { value, valid_range: ref v } = self.scalar;
915         let bits = value.size(cx).bits();
916         assert!(bits <= 128);
917         let max_value = !0u128 >> (128 - bits);
918
919         if count > max_value {
920             return None;
921         }
922
923         // Compute the range of invalid values being reserved.
924         let start = v.end().wrapping_add(1) & max_value;
925         let end = v.end().wrapping_add(count) & max_value;
926
927         // If the `end` of our range is inside the valid range,
928         // then we ran out of invalid values.
929         // FIXME(eddyb) abstract this with a wraparound range type.
930         let valid_range_contains = |x| {
931             if v.start() <= v.end() {
932                 *v.start() <= x && x <= *v.end()
933             } else {
934                 *v.start() <= x || x <= *v.end()
935             }
936         };
937         if valid_range_contains(end) {
938             return None;
939         }
940
941         Some((start, Scalar { value, valid_range: *v.start()..=end }))
942     }
943 }
944
945 #[derive(PartialEq, Eq, Hash, Debug)]
946 pub struct LayoutDetails {
947     pub variants: Variants,
948     pub fields: FieldPlacement,
949     pub abi: Abi,
950
951     /// The leaf scalar with the largest number of invalid values
952     /// (i.e. outside of its `valid_range`), if it exists.
953     pub largest_niche: Option<Niche>,
954
955     pub align: AbiAndPrefAlign,
956     pub size: Size
957 }
958
959 impl LayoutDetails {
960     pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
961         let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar.clone());
962         let size = scalar.value.size(cx);
963         let align = scalar.value.align(cx);
964         LayoutDetails {
965             variants: Variants::Single { index: VariantIdx::new(0) },
966             fields: FieldPlacement::Union(0),
967             abi: Abi::Scalar(scalar),
968             largest_niche,
969             size,
970             align,
971         }
972     }
973 }
974
975 /// The details of the layout of a type, alongside the type itself.
976 /// Provides various type traversal APIs (e.g., recursing into fields).
977 ///
978 /// Note that the details are NOT guaranteed to always be identical
979 /// to those obtained from `layout_of(ty)`, as we need to produce
980 /// layouts for which Rust types do not exist, such as enum variants
981 /// or synthetic fields of enums (i.e., discriminants) and fat pointers.
982 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
983 pub struct TyLayout<'a, Ty> {
984     pub ty: Ty,
985     pub details: &'a LayoutDetails
986 }
987
988 impl<'a, Ty> Deref for TyLayout<'a, Ty> {
989     type Target = &'a LayoutDetails;
990     fn deref(&self) -> &&'a LayoutDetails {
991         &self.details
992     }
993 }
994
995 pub trait LayoutOf {
996     type Ty;
997     type TyLayout;
998
999     fn layout_of(&self, ty: Self::Ty) -> Self::TyLayout;
1000 }
1001
1002 #[derive(Copy, Clone, PartialEq, Eq)]
1003 pub enum PointerKind {
1004     /// Most general case, we know no restrictions to tell LLVM.
1005     Shared,
1006
1007     /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
1008     Frozen,
1009
1010     /// `&mut T`, when we know `noalias` is safe for LLVM.
1011     UniqueBorrowed,
1012
1013     /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
1014     UniqueOwned
1015 }
1016
1017 #[derive(Copy, Clone)]
1018 pub struct PointeeInfo {
1019     pub size: Size,
1020     pub align: Align,
1021     pub safe: Option<PointerKind>,
1022 }
1023
1024 pub trait TyLayoutMethods<'a, C: LayoutOf<Ty = Self>>: Sized {
1025     fn for_variant(
1026         this: TyLayout<'a, Self>,
1027         cx: &C,
1028         variant_index: VariantIdx,
1029     ) -> TyLayout<'a, Self>;
1030     fn field(this: TyLayout<'a, Self>, cx: &C, i: usize) -> C::TyLayout;
1031     fn pointee_info_at(
1032         this: TyLayout<'a, Self>,
1033         cx: &C,
1034         offset: Size,
1035     ) -> Option<PointeeInfo>;
1036 }
1037
1038 impl<'a, Ty> TyLayout<'a, Ty> {
1039     pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
1040     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> {
1041         Ty::for_variant(self, cx, variant_index)
1042     }
1043     pub fn field<C>(self, cx: &C, i: usize) -> C::TyLayout
1044     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> {
1045         Ty::field(self, cx, i)
1046     }
1047     pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
1048     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> {
1049         Ty::pointee_info_at(self, cx, offset)
1050     }
1051 }
1052
1053 impl<'a, Ty> TyLayout<'a, Ty> {
1054     /// Returns `true` if the layout corresponds to an unsized type.
1055     pub fn is_unsized(&self) -> bool {
1056         self.abi.is_unsized()
1057     }
1058
1059     /// Returns `true` if the type is a ZST and not unsized.
1060     pub fn is_zst(&self) -> bool {
1061         match self.abi {
1062             Abi::Scalar(_) |
1063             Abi::ScalarPair(..) |
1064             Abi::Vector { .. } => false,
1065             Abi::Uninhabited => self.size.bytes() == 0,
1066             Abi::Aggregate { sized } => sized && self.size.bytes() == 0
1067         }
1068     }
1069 }