]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_target/src/abi/mod.rs
Rollup merge of #96913 - Urgau:rfc3239-part2, r=petrochenkov
[rust.git] / compiler / rustc_target / src / abi / mod.rs
1 pub use Integer::*;
2 pub use Primitive::*;
3
4 use crate::spec::Target;
5
6 use std::convert::{TryFrom, TryInto};
7 use std::fmt;
8 use std::iter::Step;
9 use std::num::NonZeroUsize;
10 use std::ops::{Add, AddAssign, Deref, Mul, RangeInclusive, Sub};
11 use std::str::FromStr;
12
13 use rustc_data_structures::intern::Interned;
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_macros::HashStable_Generic;
16 use rustc_serialize::json::{Json, ToJson};
17
18 pub mod call;
19
20 /// Parsed [Data layout](https://llvm.org/docs/LangRef.html#data-layout)
21 /// for a target, which contains everything needed to compute layouts.
22 pub struct TargetDataLayout {
23     pub endian: Endian,
24     pub i1_align: AbiAndPrefAlign,
25     pub i8_align: AbiAndPrefAlign,
26     pub i16_align: AbiAndPrefAlign,
27     pub i32_align: AbiAndPrefAlign,
28     pub i64_align: AbiAndPrefAlign,
29     pub i128_align: AbiAndPrefAlign,
30     pub f32_align: AbiAndPrefAlign,
31     pub f64_align: AbiAndPrefAlign,
32     pub pointer_size: Size,
33     pub pointer_align: AbiAndPrefAlign,
34     pub aggregate_align: AbiAndPrefAlign,
35
36     /// Alignments for vector types.
37     pub vector_align: Vec<(Size, AbiAndPrefAlign)>,
38
39     pub instruction_address_space: AddressSpace,
40
41     /// Minimum size of #[repr(C)] enums (default I32 bits)
42     pub c_enum_min_size: Integer,
43 }
44
45 impl Default for TargetDataLayout {
46     /// Creates an instance of `TargetDataLayout`.
47     fn default() -> TargetDataLayout {
48         let align = |bits| Align::from_bits(bits).unwrap();
49         TargetDataLayout {
50             endian: Endian::Big,
51             i1_align: AbiAndPrefAlign::new(align(8)),
52             i8_align: AbiAndPrefAlign::new(align(8)),
53             i16_align: AbiAndPrefAlign::new(align(16)),
54             i32_align: AbiAndPrefAlign::new(align(32)),
55             i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
56             i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
57             f32_align: AbiAndPrefAlign::new(align(32)),
58             f64_align: AbiAndPrefAlign::new(align(64)),
59             pointer_size: Size::from_bits(64),
60             pointer_align: AbiAndPrefAlign::new(align(64)),
61             aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) },
62             vector_align: vec![
63                 (Size::from_bits(64), AbiAndPrefAlign::new(align(64))),
64                 (Size::from_bits(128), AbiAndPrefAlign::new(align(128))),
65             ],
66             instruction_address_space: AddressSpace::DATA,
67             c_enum_min_size: Integer::I32,
68         }
69     }
70 }
71
72 impl TargetDataLayout {
73     pub fn parse(target: &Target) -> Result<TargetDataLayout, String> {
74         // Parse an address space index from a string.
75         let parse_address_space = |s: &str, cause: &str| {
76             s.parse::<u32>().map(AddressSpace).map_err(|err| {
77                 format!("invalid address space `{}` for `{}` in \"data-layout\": {}", s, cause, err)
78             })
79         };
80
81         // Parse a bit count from a string.
82         let parse_bits = |s: &str, kind: &str, cause: &str| {
83             s.parse::<u64>().map_err(|err| {
84                 format!("invalid {} `{}` for `{}` in \"data-layout\": {}", kind, s, cause, err)
85             })
86         };
87
88         // Parse a size string.
89         let size = |s: &str, cause: &str| parse_bits(s, "size", cause).map(Size::from_bits);
90
91         // Parse an alignment string.
92         let align = |s: &[&str], cause: &str| {
93             if s.is_empty() {
94                 return Err(format!("missing alignment for `{}` in \"data-layout\"", cause));
95             }
96             let align_from_bits = |bits| {
97                 Align::from_bits(bits).map_err(|err| {
98                     format!("invalid alignment for `{}` in \"data-layout\": {}", cause, err)
99                 })
100             };
101             let abi = parse_bits(s[0], "alignment", cause)?;
102             let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?;
103             Ok(AbiAndPrefAlign { abi: align_from_bits(abi)?, pref: align_from_bits(pref)? })
104         };
105
106         let mut dl = TargetDataLayout::default();
107         let mut i128_align_src = 64;
108         for spec in target.data_layout.split('-') {
109             let spec_parts = spec.split(':').collect::<Vec<_>>();
110
111             match &*spec_parts {
112                 ["e"] => dl.endian = Endian::Little,
113                 ["E"] => dl.endian = Endian::Big,
114                 [p] if p.starts_with('P') => {
115                     dl.instruction_address_space = parse_address_space(&p[1..], "P")?
116                 }
117                 ["a", ref a @ ..] => dl.aggregate_align = align(a, "a")?,
118                 ["f32", ref a @ ..] => dl.f32_align = align(a, "f32")?,
119                 ["f64", ref a @ ..] => dl.f64_align = align(a, "f64")?,
120                 [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => {
121                     dl.pointer_size = size(s, p)?;
122                     dl.pointer_align = align(a, p)?;
123                 }
124                 [s, ref a @ ..] if s.starts_with('i') => {
125                     let Ok(bits) = s[1..].parse::<u64>() else {
126                         size(&s[1..], "i")?; // For the user error.
127                         continue;
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         if dl.endian != target.endian {
161             return Err(format!(
162                 "inconsistent target specification: \"data-layout\" claims \
163                  architecture is {}-endian, while \"target-endian\" is `{}`",
164                 dl.endian.as_str(),
165                 target.endian.as_str(),
166             ));
167         }
168
169         if dl.pointer_size.bits() != target.pointer_width.into() {
170             return Err(format!(
171                 "inconsistent target specification: \"data-layout\" claims \
172                  pointers are {}-bit, while \"target-pointer-width\" is `{}`",
173                 dl.pointer_size.bits(),
174                 target.pointer_width
175             ));
176         }
177
178         dl.c_enum_min_size = Integer::from_size(Size::from_bits(target.c_enum_min_bits))?;
179
180         Ok(dl)
181     }
182
183     /// Returns exclusive upper bound on object size.
184     ///
185     /// The theoretical maximum object size is defined as the maximum positive `isize` value.
186     /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly
187     /// index every address within an object along with one byte past the end, along with allowing
188     /// `isize` to store the difference between any two pointers into an object.
189     ///
190     /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer
191     /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is
192     /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable
193     /// address space on 64-bit ARMv8 and x86_64.
194     #[inline]
195     pub fn obj_size_bound(&self) -> u64 {
196         match self.pointer_size.bits() {
197             16 => 1 << 15,
198             32 => 1 << 31,
199             64 => 1 << 47,
200             bits => panic!("obj_size_bound: unknown pointer bit size {}", bits),
201         }
202     }
203
204     #[inline]
205     pub fn ptr_sized_integer(&self) -> Integer {
206         match self.pointer_size.bits() {
207             16 => I16,
208             32 => I32,
209             64 => I64,
210             bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits),
211         }
212     }
213
214     #[inline]
215     pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign {
216         for &(size, align) in &self.vector_align {
217             if size == vec_size {
218                 return align;
219             }
220         }
221         // Default to natural alignment, which is what LLVM does.
222         // That is, use the size, rounded up to a power of 2.
223         AbiAndPrefAlign::new(Align::from_bytes(vec_size.bytes().next_power_of_two()).unwrap())
224     }
225 }
226
227 pub trait HasDataLayout {
228     fn data_layout(&self) -> &TargetDataLayout;
229 }
230
231 impl HasDataLayout for TargetDataLayout {
232     #[inline]
233     fn data_layout(&self) -> &TargetDataLayout {
234         self
235     }
236 }
237
238 /// Endianness of the target, which must match cfg(target-endian).
239 #[derive(Copy, Clone, PartialEq)]
240 pub enum Endian {
241     Little,
242     Big,
243 }
244
245 impl Endian {
246     pub fn as_str(&self) -> &'static str {
247         match self {
248             Self::Little => "little",
249             Self::Big => "big",
250         }
251     }
252 }
253
254 impl fmt::Debug for Endian {
255     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256         f.write_str(self.as_str())
257     }
258 }
259
260 impl FromStr for Endian {
261     type Err = String;
262
263     fn from_str(s: &str) -> Result<Self, Self::Err> {
264         match s {
265             "little" => Ok(Self::Little),
266             "big" => Ok(Self::Big),
267             _ => Err(format!(r#"unknown endian: "{}""#, s)),
268         }
269     }
270 }
271
272 impl ToJson for Endian {
273     fn to_json(&self) -> Json {
274         self.as_str().to_json()
275     }
276 }
277
278 /// Size of a type in bytes.
279 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
280 #[derive(HashStable_Generic)]
281 pub struct Size {
282     raw: u64,
283 }
284
285 // This is debug-printed a lot in larger structs, don't waste too much space there
286 impl fmt::Debug for Size {
287     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288         write!(f, "Size({} bytes)", self.bytes())
289     }
290 }
291
292 impl Size {
293     pub const ZERO: Size = Size { raw: 0 };
294
295     /// Rounds `bits` up to the next-higher byte boundary, if `bits` is
296     /// not a multiple of 8.
297     pub fn from_bits(bits: impl TryInto<u64>) -> Size {
298         let bits = bits.try_into().ok().unwrap();
299         // Avoid potential overflow from `bits + 7`.
300         Size { raw: bits / 8 + ((bits % 8) + 7) / 8 }
301     }
302
303     #[inline]
304     pub fn from_bytes(bytes: impl TryInto<u64>) -> Size {
305         let bytes: u64 = bytes.try_into().ok().unwrap();
306         Size { raw: bytes }
307     }
308
309     #[inline]
310     pub fn bytes(self) -> u64 {
311         self.raw
312     }
313
314     #[inline]
315     pub fn bytes_usize(self) -> usize {
316         self.bytes().try_into().unwrap()
317     }
318
319     #[inline]
320     pub fn bits(self) -> u64 {
321         #[cold]
322         fn overflow(bytes: u64) -> ! {
323             panic!("Size::bits: {} bytes in bits doesn't fit in u64", bytes)
324         }
325
326         self.bytes().checked_mul(8).unwrap_or_else(|| overflow(self.bytes()))
327     }
328
329     #[inline]
330     pub fn bits_usize(self) -> usize {
331         self.bits().try_into().unwrap()
332     }
333
334     #[inline]
335     pub fn align_to(self, align: Align) -> Size {
336         let mask = align.bytes() - 1;
337         Size::from_bytes((self.bytes() + mask) & !mask)
338     }
339
340     #[inline]
341     pub fn is_aligned(self, align: Align) -> bool {
342         let mask = align.bytes() - 1;
343         self.bytes() & mask == 0
344     }
345
346     #[inline]
347     pub fn checked_add<C: HasDataLayout>(self, offset: Size, cx: &C) -> Option<Size> {
348         let dl = cx.data_layout();
349
350         let bytes = self.bytes().checked_add(offset.bytes())?;
351
352         if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
353     }
354
355     #[inline]
356     pub fn checked_mul<C: HasDataLayout>(self, count: u64, cx: &C) -> Option<Size> {
357         let dl = cx.data_layout();
358
359         let bytes = self.bytes().checked_mul(count)?;
360         if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
361     }
362
363     /// Truncates `value` to `self` bits and then sign-extends it to 128 bits
364     /// (i.e., if it is negative, fill with 1's on the left).
365     #[inline]
366     pub fn sign_extend(self, value: u128) -> u128 {
367         let size = self.bits();
368         if size == 0 {
369             // Truncated until nothing is left.
370             return 0;
371         }
372         // Sign-extend it.
373         let shift = 128 - size;
374         // Shift the unsigned value to the left, then shift back to the right as signed
375         // (essentially fills with sign bit on the left).
376         (((value << shift) as i128) >> shift) as u128
377     }
378
379     /// Truncates `value` to `self` bits.
380     #[inline]
381     pub fn truncate(self, value: u128) -> u128 {
382         let size = self.bits();
383         if size == 0 {
384             // Truncated until nothing is left.
385             return 0;
386         }
387         let shift = 128 - size;
388         // Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
389         (value << shift) >> shift
390     }
391
392     #[inline]
393     pub fn signed_int_min(&self) -> i128 {
394         self.sign_extend(1_u128 << (self.bits() - 1)) as i128
395     }
396
397     #[inline]
398     pub fn signed_int_max(&self) -> i128 {
399         i128::MAX >> (128 - self.bits())
400     }
401
402     #[inline]
403     pub fn unsigned_int_max(&self) -> u128 {
404         u128::MAX >> (128 - self.bits())
405     }
406 }
407
408 // Panicking addition, subtraction and multiplication for convenience.
409 // Avoid during layout computation, return `LayoutError` instead.
410
411 impl Add for Size {
412     type Output = Size;
413     #[inline]
414     fn add(self, other: Size) -> Size {
415         Size::from_bytes(self.bytes().checked_add(other.bytes()).unwrap_or_else(|| {
416             panic!("Size::add: {} + {} doesn't fit in u64", self.bytes(), other.bytes())
417         }))
418     }
419 }
420
421 impl Sub for Size {
422     type Output = Size;
423     #[inline]
424     fn sub(self, other: Size) -> Size {
425         Size::from_bytes(self.bytes().checked_sub(other.bytes()).unwrap_or_else(|| {
426             panic!("Size::sub: {} - {} would result in negative size", self.bytes(), other.bytes())
427         }))
428     }
429 }
430
431 impl Mul<Size> for u64 {
432     type Output = Size;
433     #[inline]
434     fn mul(self, size: Size) -> Size {
435         size * self
436     }
437 }
438
439 impl Mul<u64> for Size {
440     type Output = Size;
441     #[inline]
442     fn mul(self, count: u64) -> Size {
443         match self.bytes().checked_mul(count) {
444             Some(bytes) => Size::from_bytes(bytes),
445             None => panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count),
446         }
447     }
448 }
449
450 impl AddAssign for Size {
451     #[inline]
452     fn add_assign(&mut self, other: Size) {
453         *self = *self + other;
454     }
455 }
456
457 impl Step for Size {
458     #[inline]
459     fn steps_between(start: &Self, end: &Self) -> Option<usize> {
460         u64::steps_between(&start.bytes(), &end.bytes())
461     }
462
463     #[inline]
464     fn forward_checked(start: Self, count: usize) -> Option<Self> {
465         u64::forward_checked(start.bytes(), count).map(Self::from_bytes)
466     }
467
468     #[inline]
469     fn forward(start: Self, count: usize) -> Self {
470         Self::from_bytes(u64::forward(start.bytes(), count))
471     }
472
473     #[inline]
474     unsafe fn forward_unchecked(start: Self, count: usize) -> Self {
475         Self::from_bytes(u64::forward_unchecked(start.bytes(), count))
476     }
477
478     #[inline]
479     fn backward_checked(start: Self, count: usize) -> Option<Self> {
480         u64::backward_checked(start.bytes(), count).map(Self::from_bytes)
481     }
482
483     #[inline]
484     fn backward(start: Self, count: usize) -> Self {
485         Self::from_bytes(u64::backward(start.bytes(), count))
486     }
487
488     #[inline]
489     unsafe fn backward_unchecked(start: Self, count: usize) -> Self {
490         Self::from_bytes(u64::backward_unchecked(start.bytes(), count))
491     }
492 }
493
494 /// Alignment of a type in bytes (always a power of two).
495 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
496 #[derive(HashStable_Generic)]
497 pub struct Align {
498     pow2: u8,
499 }
500
501 // This is debug-printed a lot in larger structs, don't waste too much space there
502 impl fmt::Debug for Align {
503     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504         write!(f, "Align({} bytes)", self.bytes())
505     }
506 }
507
508 impl Align {
509     pub const ONE: Align = Align { pow2: 0 };
510
511     #[inline]
512     pub fn from_bits(bits: u64) -> Result<Align, String> {
513         Align::from_bytes(Size::from_bits(bits).bytes())
514     }
515
516     #[inline]
517     pub fn from_bytes(align: u64) -> Result<Align, String> {
518         // Treat an alignment of 0 bytes like 1-byte alignment.
519         if align == 0 {
520             return Ok(Align::ONE);
521         }
522
523         #[cold]
524         fn not_power_of_2(align: u64) -> String {
525             format!("`{}` is not a power of 2", align)
526         }
527
528         #[cold]
529         fn too_large(align: u64) -> String {
530             format!("`{}` is too large", align)
531         }
532
533         let mut bytes = align;
534         let mut pow2: u8 = 0;
535         while (bytes & 1) == 0 {
536             pow2 += 1;
537             bytes >>= 1;
538         }
539         if bytes != 1 {
540             return Err(not_power_of_2(align));
541         }
542         if pow2 > 29 {
543             return Err(too_large(align));
544         }
545
546         Ok(Align { pow2 })
547     }
548
549     #[inline]
550     pub fn bytes(self) -> u64 {
551         1 << self.pow2
552     }
553
554     #[inline]
555     pub fn bits(self) -> u64 {
556         self.bytes() * 8
557     }
558
559     /// Computes the best alignment possible for the given offset
560     /// (the largest power of two that the offset is a multiple of).
561     ///
562     /// N.B., for an offset of `0`, this happens to return `2^64`.
563     #[inline]
564     pub fn max_for_offset(offset: Size) -> Align {
565         Align { pow2: offset.bytes().trailing_zeros() as u8 }
566     }
567
568     /// Lower the alignment, if necessary, such that the given offset
569     /// is aligned to it (the offset is a multiple of the alignment).
570     #[inline]
571     pub fn restrict_for_offset(self, offset: Size) -> Align {
572         self.min(Align::max_for_offset(offset))
573     }
574 }
575
576 /// A pair of alignments, ABI-mandated and preferred.
577 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
578 #[derive(HashStable_Generic)]
579 pub struct AbiAndPrefAlign {
580     pub abi: Align,
581     pub pref: Align,
582 }
583
584 impl AbiAndPrefAlign {
585     #[inline]
586     pub fn new(align: Align) -> AbiAndPrefAlign {
587         AbiAndPrefAlign { abi: align, pref: align }
588     }
589
590     #[inline]
591     pub fn min(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
592         AbiAndPrefAlign { abi: self.abi.min(other.abi), pref: self.pref.min(other.pref) }
593     }
594
595     #[inline]
596     pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
597         AbiAndPrefAlign { abi: self.abi.max(other.abi), pref: self.pref.max(other.pref) }
598     }
599 }
600
601 /// Integers, also used for enum discriminants.
602 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, HashStable_Generic)]
603 pub enum Integer {
604     I8,
605     I16,
606     I32,
607     I64,
608     I128,
609 }
610
611 impl Integer {
612     #[inline]
613     pub fn size(self) -> Size {
614         match self {
615             I8 => Size::from_bytes(1),
616             I16 => Size::from_bytes(2),
617             I32 => Size::from_bytes(4),
618             I64 => Size::from_bytes(8),
619             I128 => Size::from_bytes(16),
620         }
621     }
622
623     pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
624         let dl = cx.data_layout();
625
626         match self {
627             I8 => dl.i8_align,
628             I16 => dl.i16_align,
629             I32 => dl.i32_align,
630             I64 => dl.i64_align,
631             I128 => dl.i128_align,
632         }
633     }
634
635     /// Finds the smallest Integer type which can represent the signed value.
636     #[inline]
637     pub fn fit_signed(x: i128) -> Integer {
638         match x {
639             -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8,
640             -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16,
641             -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32,
642             -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64,
643             _ => I128,
644         }
645     }
646
647     /// Finds the smallest Integer type which can represent the unsigned value.
648     #[inline]
649     pub fn fit_unsigned(x: u128) -> Integer {
650         match x {
651             0..=0x0000_0000_0000_00ff => I8,
652             0..=0x0000_0000_0000_ffff => I16,
653             0..=0x0000_0000_ffff_ffff => I32,
654             0..=0xffff_ffff_ffff_ffff => I64,
655             _ => I128,
656         }
657     }
658
659     /// Finds the smallest integer with the given alignment.
660     pub fn for_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Option<Integer> {
661         let dl = cx.data_layout();
662
663         for candidate in [I8, I16, I32, I64, I128] {
664             if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() {
665                 return Some(candidate);
666             }
667         }
668         None
669     }
670
671     /// Find the largest integer with the given alignment or less.
672     pub fn approximate_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Integer {
673         let dl = cx.data_layout();
674
675         // FIXME(eddyb) maybe include I128 in the future, when it works everywhere.
676         for candidate in [I64, I32, I16] {
677             if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() {
678                 return candidate;
679             }
680         }
681         I8
682     }
683
684     // FIXME(eddyb) consolidate this and other methods that find the appropriate
685     // `Integer` given some requirements.
686     #[inline]
687     fn from_size(size: Size) -> Result<Self, String> {
688         match size.bits() {
689             8 => Ok(Integer::I8),
690             16 => Ok(Integer::I16),
691             32 => Ok(Integer::I32),
692             64 => Ok(Integer::I64),
693             128 => Ok(Integer::I128),
694             _ => Err(format!("rust does not support integers with {} bits", size.bits())),
695         }
696     }
697 }
698
699 /// Fundamental unit of memory access and layout.
700 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
701 pub enum Primitive {
702     /// The `bool` is the signedness of the `Integer` type.
703     ///
704     /// One would think we would not care about such details this low down,
705     /// but some ABIs are described in terms of C types and ISAs where the
706     /// integer arithmetic is done on {sign,zero}-extended registers, e.g.
707     /// a negative integer passed by zero-extension will appear positive in
708     /// the callee, and most operations on it will produce the wrong values.
709     Int(Integer, bool),
710     F32,
711     F64,
712     Pointer,
713 }
714
715 impl Primitive {
716     pub fn size<C: HasDataLayout>(self, cx: &C) -> Size {
717         let dl = cx.data_layout();
718
719         match self {
720             Int(i, _) => i.size(),
721             F32 => Size::from_bits(32),
722             F64 => Size::from_bits(64),
723             Pointer => dl.pointer_size,
724         }
725     }
726
727     pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
728         let dl = cx.data_layout();
729
730         match self {
731             Int(i, _) => i.align(dl),
732             F32 => dl.f32_align,
733             F64 => dl.f64_align,
734             Pointer => dl.pointer_align,
735         }
736     }
737
738     // FIXME(eddyb) remove, it's trivial thanks to `matches!`.
739     #[inline]
740     pub fn is_float(self) -> bool {
741         matches!(self, F32 | F64)
742     }
743
744     // FIXME(eddyb) remove, it's completely unused.
745     #[inline]
746     pub fn is_int(self) -> bool {
747         matches!(self, Int(..))
748     }
749 }
750
751 /// Inclusive wrap-around range of valid values, that is, if
752 /// start > end, it represents `start..=MAX`,
753 /// followed by `0..=end`.
754 ///
755 /// That is, for an i8 primitive, a range of `254..=2` means following
756 /// sequence:
757 ///
758 ///    254 (-2), 255 (-1), 0, 1, 2
759 ///
760 /// This is intended specifically to mirror LLVM’s `!range` metadata semantics.
761 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
762 #[derive(HashStable_Generic)]
763 pub struct WrappingRange {
764     pub start: u128,
765     pub end: u128,
766 }
767
768 impl WrappingRange {
769     pub fn full(size: Size) -> Self {
770         Self { start: 0, end: size.unsigned_int_max() }
771     }
772
773     /// Returns `true` if `v` is contained in the range.
774     #[inline(always)]
775     pub fn contains(&self, v: u128) -> bool {
776         if self.start <= self.end {
777             self.start <= v && v <= self.end
778         } else {
779             self.start <= v || v <= self.end
780         }
781     }
782
783     /// Returns `self` with replaced `start`
784     #[inline(always)]
785     pub fn with_start(mut self, start: u128) -> Self {
786         self.start = start;
787         self
788     }
789
790     /// Returns `self` with replaced `end`
791     #[inline(always)]
792     pub fn with_end(mut self, end: u128) -> Self {
793         self.end = end;
794         self
795     }
796
797     /// Returns `true` if `size` completely fills the range.
798     #[inline]
799     pub fn is_full_for(&self, size: Size) -> bool {
800         let max_value = size.unsigned_int_max();
801         debug_assert!(self.start <= max_value && self.end <= max_value);
802         self.start == (self.end.wrapping_add(1) & max_value)
803     }
804 }
805
806 impl fmt::Debug for WrappingRange {
807     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
808         if self.start > self.end {
809             write!(fmt, "(..={}) | ({}..)", self.end, self.start)?;
810         } else {
811             write!(fmt, "{}..={}", self.start, self.end)?;
812         }
813         Ok(())
814     }
815 }
816
817 /// Information about one scalar component of a Rust type.
818 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
819 #[derive(HashStable_Generic)]
820 pub enum Scalar {
821     Initialized {
822         value: Primitive,
823
824         // FIXME(eddyb) always use the shortest range, e.g., by finding
825         // the largest space between two consecutive valid values and
826         // taking everything else as the (shortest) valid range.
827         valid_range: WrappingRange,
828     },
829     Union {
830         /// Even for unions, we need to use the correct registers for the kind of
831         /// values inside the union, so we keep the `Primitive` type around. We
832         /// also use it to compute the size of the scalar.
833         /// However, unions never have niches and even allow undef,
834         /// so there is no `valid_range`.
835         value: Primitive,
836     },
837 }
838
839 impl Scalar {
840     #[inline]
841     pub fn is_bool(&self) -> bool {
842         matches!(
843             self,
844             Scalar::Initialized {
845                 value: Int(I8, false),
846                 valid_range: WrappingRange { start: 0, end: 1 }
847             }
848         )
849     }
850
851     /// Get the primitive representation of this type, ignoring the valid range and whether the
852     /// value is allowed to be undefined (due to being a union).
853     pub fn primitive(&self) -> Primitive {
854         match *self {
855             Scalar::Initialized { value, .. } | Scalar::Union { value } => value,
856         }
857     }
858
859     pub fn align(self, cx: &impl HasDataLayout) -> AbiAndPrefAlign {
860         self.primitive().align(cx)
861     }
862
863     pub fn size(self, cx: &impl HasDataLayout) -> Size {
864         self.primitive().size(cx)
865     }
866
867     #[inline]
868     pub fn to_union(&self) -> Self {
869         Self::Union { value: self.primitive() }
870     }
871
872     #[inline]
873     pub fn valid_range(&self, cx: &impl HasDataLayout) -> WrappingRange {
874         match *self {
875             Scalar::Initialized { valid_range, .. } => valid_range,
876             Scalar::Union { value } => WrappingRange::full(value.size(cx)),
877         }
878     }
879
880     #[inline]
881     /// Allows the caller to mutate the valid range. This operation will panic if attempted on a union.
882     pub fn valid_range_mut(&mut self) -> &mut WrappingRange {
883         match self {
884             Scalar::Initialized { valid_range, .. } => valid_range,
885             Scalar::Union { .. } => panic!("cannot change the valid range of a union"),
886         }
887     }
888
889     /// Returns `true` if all possible numbers are valid, i.e `valid_range` covers the whole layout
890     #[inline]
891     pub fn is_always_valid<C: HasDataLayout>(&self, cx: &C) -> bool {
892         match *self {
893             Scalar::Initialized { valid_range, .. } => valid_range.is_full_for(self.size(cx)),
894             Scalar::Union { .. } => true,
895         }
896     }
897
898     /// Returns `true` if this type can be left uninit.
899     #[inline]
900     pub fn is_uninit_valid(&self) -> bool {
901         match *self {
902             Scalar::Initialized { .. } => false,
903             Scalar::Union { .. } => true,
904         }
905     }
906 }
907
908 /// Describes how the fields of a type are located in memory.
909 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
910 pub enum FieldsShape {
911     /// Scalar primitives and `!`, which never have fields.
912     Primitive,
913
914     /// All fields start at no offset. The `usize` is the field count.
915     Union(NonZeroUsize),
916
917     /// Array/vector-like placement, with all fields of identical types.
918     Array { stride: Size, count: u64 },
919
920     /// Struct-like placement, with precomputed offsets.
921     ///
922     /// Fields are guaranteed to not overlap, but note that gaps
923     /// before, between and after all the fields are NOT always
924     /// padding, and as such their contents may not be discarded.
925     /// For example, enum variants leave a gap at the start,
926     /// where the discriminant field in the enum layout goes.
927     Arbitrary {
928         /// Offsets for the first byte of each field,
929         /// ordered to match the source definition order.
930         /// This vector does not go in increasing order.
931         // FIXME(eddyb) use small vector optimization for the common case.
932         offsets: Vec<Size>,
933
934         /// Maps source order field indices to memory order indices,
935         /// depending on how the fields were reordered (if at all).
936         /// This is a permutation, with both the source order and the
937         /// memory order using the same (0..n) index ranges.
938         ///
939         /// Note that during computation of `memory_index`, sometimes
940         /// it is easier to operate on the inverse mapping (that is,
941         /// from memory order to source order), and that is usually
942         /// named `inverse_memory_index`.
943         ///
944         // FIXME(eddyb) build a better abstraction for permutations, if possible.
945         // FIXME(camlorn) also consider small vector  optimization here.
946         memory_index: Vec<u32>,
947     },
948 }
949
950 impl FieldsShape {
951     #[inline]
952     pub fn count(&self) -> usize {
953         match *self {
954             FieldsShape::Primitive => 0,
955             FieldsShape::Union(count) => count.get(),
956             FieldsShape::Array { count, .. } => count.try_into().unwrap(),
957             FieldsShape::Arbitrary { ref offsets, .. } => offsets.len(),
958         }
959     }
960
961     #[inline]
962     pub fn offset(&self, i: usize) -> Size {
963         match *self {
964             FieldsShape::Primitive => {
965                 unreachable!("FieldsShape::offset: `Primitive`s have no fields")
966             }
967             FieldsShape::Union(count) => {
968                 assert!(
969                     i < count.get(),
970                     "tried to access field {} of union with {} fields",
971                     i,
972                     count
973                 );
974                 Size::ZERO
975             }
976             FieldsShape::Array { stride, count } => {
977                 let i = u64::try_from(i).unwrap();
978                 assert!(i < count);
979                 stride * i
980             }
981             FieldsShape::Arbitrary { ref offsets, .. } => offsets[i],
982         }
983     }
984
985     #[inline]
986     pub fn memory_index(&self, i: usize) -> usize {
987         match *self {
988             FieldsShape::Primitive => {
989                 unreachable!("FieldsShape::memory_index: `Primitive`s have no fields")
990             }
991             FieldsShape::Union(_) | FieldsShape::Array { .. } => i,
992             FieldsShape::Arbitrary { ref memory_index, .. } => memory_index[i].try_into().unwrap(),
993         }
994     }
995
996     /// Gets source indices of the fields by increasing offsets.
997     #[inline]
998     pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator<Item = usize> + 'a {
999         let mut inverse_small = [0u8; 64];
1000         let mut inverse_big = vec![];
1001         let use_small = self.count() <= inverse_small.len();
1002
1003         // We have to write this logic twice in order to keep the array small.
1004         if let FieldsShape::Arbitrary { ref memory_index, .. } = *self {
1005             if use_small {
1006                 for i in 0..self.count() {
1007                     inverse_small[memory_index[i] as usize] = i as u8;
1008                 }
1009             } else {
1010                 inverse_big = vec![0; self.count()];
1011                 for i in 0..self.count() {
1012                     inverse_big[memory_index[i] as usize] = i as u32;
1013                 }
1014             }
1015         }
1016
1017         (0..self.count()).map(move |i| match *self {
1018             FieldsShape::Primitive | FieldsShape::Union(_) | FieldsShape::Array { .. } => i,
1019             FieldsShape::Arbitrary { .. } => {
1020                 if use_small {
1021                     inverse_small[i] as usize
1022                 } else {
1023                     inverse_big[i] as usize
1024                 }
1025             }
1026         })
1027     }
1028 }
1029
1030 /// An identifier that specifies the address space that some operation
1031 /// should operate on. Special address spaces have an effect on code generation,
1032 /// depending on the target and the address spaces it implements.
1033 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1034 pub struct AddressSpace(pub u32);
1035
1036 impl AddressSpace {
1037     /// The default address space, corresponding to data space.
1038     pub const DATA: Self = AddressSpace(0);
1039 }
1040
1041 /// Describes how values of the type are passed by target ABIs,
1042 /// in terms of categories of C types there are ABI rules for.
1043 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1044 pub enum Abi {
1045     Uninhabited,
1046     Scalar(Scalar),
1047     ScalarPair(Scalar, Scalar),
1048     Vector {
1049         element: Scalar,
1050         count: u64,
1051     },
1052     Aggregate {
1053         /// If true, the size is exact, otherwise it's only a lower bound.
1054         sized: bool,
1055     },
1056 }
1057
1058 impl Abi {
1059     /// Returns `true` if the layout corresponds to an unsized type.
1060     #[inline]
1061     pub fn is_unsized(&self) -> bool {
1062         match *self {
1063             Abi::Uninhabited | Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
1064             Abi::Aggregate { sized } => !sized,
1065         }
1066     }
1067
1068     /// Returns `true` if this is a single signed integer scalar
1069     #[inline]
1070     pub fn is_signed(&self) -> bool {
1071         match self {
1072             Abi::Scalar(scal) => match scal.primitive() {
1073                 Primitive::Int(_, signed) => signed,
1074                 _ => false,
1075             },
1076             _ => panic!("`is_signed` on non-scalar ABI {:?}", self),
1077         }
1078     }
1079
1080     /// Returns `true` if this is an uninhabited type
1081     #[inline]
1082     pub fn is_uninhabited(&self) -> bool {
1083         matches!(*self, Abi::Uninhabited)
1084     }
1085
1086     /// Returns `true` is this is a scalar type
1087     #[inline]
1088     pub fn is_scalar(&self) -> bool {
1089         matches!(*self, Abi::Scalar(_))
1090     }
1091 }
1092
1093 rustc_index::newtype_index! {
1094     pub struct VariantIdx {
1095         derive [HashStable_Generic]
1096     }
1097 }
1098
1099 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1100 pub enum Variants<'a> {
1101     /// Single enum variants, structs/tuples, unions, and all non-ADTs.
1102     Single { index: VariantIdx },
1103
1104     /// Enum-likes with more than one inhabited variant: each variant comes with
1105     /// a *discriminant* (usually the same as the variant index but the user can
1106     /// assign explicit discriminant values).  That discriminant is encoded
1107     /// as a *tag* on the machine.  The layout of each variant is
1108     /// a struct, and they all have space reserved for the tag.
1109     /// For enums, the tag is the sole field of the layout.
1110     Multiple {
1111         tag: Scalar,
1112         tag_encoding: TagEncoding,
1113         tag_field: usize,
1114         variants: IndexVec<VariantIdx, Layout<'a>>,
1115     },
1116 }
1117
1118 #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1119 pub enum TagEncoding {
1120     /// The tag directly stores the discriminant, but possibly with a smaller layout
1121     /// (so converting the tag to the discriminant can require sign extension).
1122     Direct,
1123
1124     /// Niche (values invalid for a type) encoding the discriminant:
1125     /// Discriminant and variant index coincide.
1126     /// The variant `dataful_variant` contains a niche at an arbitrary
1127     /// offset (field `tag_field` of the enum), which for a variant with
1128     /// discriminant `d` is set to
1129     /// `(d - niche_variants.start).wrapping_add(niche_start)`.
1130     ///
1131     /// For example, `Option<(usize, &T)>`  is represented such that
1132     /// `None` has a null pointer for the second tuple field, and
1133     /// `Some` is the identity function (with a non-null reference).
1134     Niche {
1135         dataful_variant: VariantIdx,
1136         niche_variants: RangeInclusive<VariantIdx>,
1137         niche_start: u128,
1138     },
1139 }
1140
1141 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
1142 pub struct Niche {
1143     pub offset: Size,
1144     pub value: Primitive,
1145     pub valid_range: WrappingRange,
1146 }
1147
1148 impl Niche {
1149     pub fn from_scalar<C: HasDataLayout>(cx: &C, offset: Size, scalar: Scalar) -> Option<Self> {
1150         let Scalar::Initialized { value, valid_range } = scalar else { return None };
1151         let niche = Niche { offset, value, valid_range };
1152         if niche.available(cx) > 0 { Some(niche) } else { None }
1153     }
1154
1155     pub fn available<C: HasDataLayout>(&self, cx: &C) -> u128 {
1156         let Self { value, valid_range: v, .. } = *self;
1157         let size = value.size(cx);
1158         assert!(size.bits() <= 128);
1159         let max_value = size.unsigned_int_max();
1160
1161         // Find out how many values are outside the valid range.
1162         let niche = v.end.wrapping_add(1)..v.start;
1163         niche.end.wrapping_sub(niche.start) & max_value
1164     }
1165
1166     pub fn reserve<C: HasDataLayout>(&self, cx: &C, count: u128) -> Option<(u128, Scalar)> {
1167         assert!(count > 0);
1168
1169         let Self { value, valid_range: v, .. } = *self;
1170         let size = value.size(cx);
1171         assert!(size.bits() <= 128);
1172         let max_value = size.unsigned_int_max();
1173
1174         let niche = v.end.wrapping_add(1)..v.start;
1175         let available = niche.end.wrapping_sub(niche.start) & max_value;
1176         if count > available {
1177             return None;
1178         }
1179
1180         // Extend the range of valid values being reserved by moving either `v.start` or `v.end` bound.
1181         // Given an eventual `Option<T>`, we try to maximize the chance for `None` to occupy the niche of zero.
1182         // This is accomplished by preferring enums with 2 variants(`count==1`) and always taking the shortest path to niche zero.
1183         // Having `None` in niche zero can enable some special optimizations.
1184         //
1185         // Bound selection criteria:
1186         // 1. Select closest to zero given wrapping semantics.
1187         // 2. Avoid moving past zero if possible.
1188         //
1189         // In practice this means that enums with `count > 1` are unlikely to claim niche zero, since they have to fit perfectly.
1190         // If niche zero is already reserved, the selection of bounds are of little interest.
1191         let move_start = |v: WrappingRange| {
1192             let start = v.start.wrapping_sub(count) & max_value;
1193             Some((start, Scalar::Initialized { value, valid_range: v.with_start(start) }))
1194         };
1195         let move_end = |v: WrappingRange| {
1196             let start = v.end.wrapping_add(1) & max_value;
1197             let end = v.end.wrapping_add(count) & max_value;
1198             Some((start, Scalar::Initialized { value, valid_range: v.with_end(end) }))
1199         };
1200         let distance_end_zero = max_value - v.end;
1201         if v.start > v.end {
1202             // zero is unavailable because wrapping occurs
1203             move_end(v)
1204         } else if v.start <= distance_end_zero {
1205             if count <= v.start {
1206                 move_start(v)
1207             } else {
1208                 // moved past zero, use other bound
1209                 move_end(v)
1210             }
1211         } else {
1212             let end = v.end.wrapping_add(count) & max_value;
1213             let overshot_zero = (1..=v.end).contains(&end);
1214             if overshot_zero {
1215                 // moved past zero, use other bound
1216                 move_start(v)
1217             } else {
1218                 move_end(v)
1219             }
1220         }
1221     }
1222 }
1223
1224 #[derive(PartialEq, Eq, Hash, HashStable_Generic)]
1225 pub struct LayoutS<'a> {
1226     /// Says where the fields are located within the layout.
1227     pub fields: FieldsShape,
1228
1229     /// Encodes information about multi-variant layouts.
1230     /// Even with `Multiple` variants, a layout still has its own fields! Those are then
1231     /// shared between all variants. One of them will be the discriminant,
1232     /// but e.g. generators can have more.
1233     ///
1234     /// To access all fields of this layout, both `fields` and the fields of the active variant
1235     /// must be taken into account.
1236     pub variants: Variants<'a>,
1237
1238     /// The `abi` defines how this data is passed between functions, and it defines
1239     /// value restrictions via `valid_range`.
1240     ///
1241     /// Note that this is entirely orthogonal to the recursive structure defined by
1242     /// `variants` and `fields`; for example, `ManuallyDrop<Result<isize, isize>>` has
1243     /// `Abi::ScalarPair`! So, even with non-`Aggregate` `abi`, `fields` and `variants`
1244     /// have to be taken into account to find all fields of this layout.
1245     pub abi: Abi,
1246
1247     /// The leaf scalar with the largest number of invalid values
1248     /// (i.e. outside of its `valid_range`), if it exists.
1249     pub largest_niche: Option<Niche>,
1250
1251     pub align: AbiAndPrefAlign,
1252     pub size: Size,
1253 }
1254
1255 impl<'a> LayoutS<'a> {
1256     pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
1257         let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar);
1258         let size = scalar.size(cx);
1259         let align = scalar.align(cx);
1260         LayoutS {
1261             variants: Variants::Single { index: VariantIdx::new(0) },
1262             fields: FieldsShape::Primitive,
1263             abi: Abi::Scalar(scalar),
1264             largest_niche,
1265             size,
1266             align,
1267         }
1268     }
1269 }
1270
1271 impl<'a> fmt::Debug for LayoutS<'a> {
1272     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1273         // This is how `Layout` used to print before it become
1274         // `Interned<LayoutS>`. We print it like this to avoid having to update
1275         // expected output in a lot of tests.
1276         f.debug_struct("Layout")
1277             .field("fields", &self.fields)
1278             .field("variants", &self.variants)
1279             .field("abi", &self.abi)
1280             .field("largest_niche", &self.largest_niche)
1281             .field("align", &self.align)
1282             .field("size", &self.size)
1283             .finish()
1284     }
1285 }
1286
1287 #[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)]
1288 #[rustc_pass_by_value]
1289 pub struct Layout<'a>(pub Interned<'a, LayoutS<'a>>);
1290
1291 impl<'a> fmt::Debug for Layout<'a> {
1292     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1293         // See comment on `<LayoutS as Debug>::fmt` above.
1294         self.0.0.fmt(f)
1295     }
1296 }
1297
1298 impl<'a> Layout<'a> {
1299     pub fn fields(self) -> &'a FieldsShape {
1300         &self.0.0.fields
1301     }
1302
1303     pub fn variants(self) -> &'a Variants<'a> {
1304         &self.0.0.variants
1305     }
1306
1307     pub fn abi(self) -> Abi {
1308         self.0.0.abi
1309     }
1310
1311     pub fn largest_niche(self) -> Option<Niche> {
1312         self.0.0.largest_niche
1313     }
1314
1315     pub fn align(self) -> AbiAndPrefAlign {
1316         self.0.0.align
1317     }
1318
1319     pub fn size(self) -> Size {
1320         self.0.0.size
1321     }
1322 }
1323
1324 /// The layout of a type, alongside the type itself.
1325 /// Provides various type traversal APIs (e.g., recursing into fields).
1326 ///
1327 /// Note that the layout is NOT guaranteed to always be identical
1328 /// to that obtained from `layout_of(ty)`, as we need to produce
1329 /// layouts for which Rust types do not exist, such as enum variants
1330 /// or synthetic fields of enums (i.e., discriminants) and fat pointers.
1331 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable_Generic)]
1332 pub struct TyAndLayout<'a, Ty> {
1333     pub ty: Ty,
1334     pub layout: Layout<'a>,
1335 }
1336
1337 impl<'a, Ty> Deref for TyAndLayout<'a, Ty> {
1338     type Target = &'a LayoutS<'a>;
1339     fn deref(&self) -> &&'a LayoutS<'a> {
1340         &self.layout.0.0
1341     }
1342 }
1343
1344 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1345 pub enum PointerKind {
1346     /// Most general case, we know no restrictions to tell LLVM.
1347     Shared,
1348
1349     /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
1350     Frozen,
1351
1352     /// `&mut T` which is `noalias` but not `readonly`.
1353     UniqueBorrowed,
1354
1355     /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
1356     UniqueOwned,
1357 }
1358
1359 #[derive(Copy, Clone, Debug)]
1360 pub struct PointeeInfo {
1361     pub size: Size,
1362     pub align: Align,
1363     pub safe: Option<PointerKind>,
1364     pub address_space: AddressSpace,
1365 }
1366
1367 /// Used in `might_permit_raw_init` to indicate the kind of initialisation
1368 /// that is checked to be valid
1369 #[derive(Copy, Clone, Debug)]
1370 pub enum InitKind {
1371     Zero,
1372     Uninit,
1373 }
1374
1375 /// Trait that needs to be implemented by the higher-level type representation
1376 /// (e.g. `rustc_middle::ty::Ty`), to provide `rustc_target::abi` functionality.
1377 pub trait TyAbiInterface<'a, C>: Sized {
1378     fn ty_and_layout_for_variant(
1379         this: TyAndLayout<'a, Self>,
1380         cx: &C,
1381         variant_index: VariantIdx,
1382     ) -> TyAndLayout<'a, Self>;
1383     fn ty_and_layout_field(this: TyAndLayout<'a, Self>, cx: &C, i: usize) -> TyAndLayout<'a, Self>;
1384     fn ty_and_layout_pointee_info_at(
1385         this: TyAndLayout<'a, Self>,
1386         cx: &C,
1387         offset: Size,
1388     ) -> Option<PointeeInfo>;
1389     fn is_adt(this: TyAndLayout<'a, Self>) -> bool;
1390     fn is_never(this: TyAndLayout<'a, Self>) -> bool;
1391     fn is_tuple(this: TyAndLayout<'a, Self>) -> bool;
1392     fn is_unit(this: TyAndLayout<'a, Self>) -> bool;
1393 }
1394
1395 impl<'a, Ty> TyAndLayout<'a, Ty> {
1396     pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
1397     where
1398         Ty: TyAbiInterface<'a, C>,
1399     {
1400         Ty::ty_and_layout_for_variant(self, cx, variant_index)
1401     }
1402
1403     pub fn field<C>(self, cx: &C, i: usize) -> Self
1404     where
1405         Ty: TyAbiInterface<'a, C>,
1406     {
1407         Ty::ty_and_layout_field(self, cx, i)
1408     }
1409
1410     pub fn pointee_info_at<C>(self, cx: &C, offset: Size) -> Option<PointeeInfo>
1411     where
1412         Ty: TyAbiInterface<'a, C>,
1413     {
1414         Ty::ty_and_layout_pointee_info_at(self, cx, offset)
1415     }
1416
1417     pub fn is_single_fp_element<C>(self, cx: &C) -> bool
1418     where
1419         Ty: TyAbiInterface<'a, C>,
1420         C: HasDataLayout,
1421     {
1422         match self.abi {
1423             Abi::Scalar(scalar) => scalar.primitive().is_float(),
1424             Abi::Aggregate { .. } => {
1425                 if self.fields.count() == 1 && self.fields.offset(0).bytes() == 0 {
1426                     self.field(cx, 0).is_single_fp_element(cx)
1427                 } else {
1428                     false
1429                 }
1430             }
1431             _ => false,
1432         }
1433     }
1434
1435     pub fn is_adt<C>(self) -> bool
1436     where
1437         Ty: TyAbiInterface<'a, C>,
1438     {
1439         Ty::is_adt(self)
1440     }
1441
1442     pub fn is_never<C>(self) -> bool
1443     where
1444         Ty: TyAbiInterface<'a, C>,
1445     {
1446         Ty::is_never(self)
1447     }
1448
1449     pub fn is_tuple<C>(self) -> bool
1450     where
1451         Ty: TyAbiInterface<'a, C>,
1452     {
1453         Ty::is_tuple(self)
1454     }
1455
1456     pub fn is_unit<C>(self) -> bool
1457     where
1458         Ty: TyAbiInterface<'a, C>,
1459     {
1460         Ty::is_unit(self)
1461     }
1462 }
1463
1464 impl<'a, Ty> TyAndLayout<'a, Ty> {
1465     /// Returns `true` if the layout corresponds to an unsized type.
1466     pub fn is_unsized(&self) -> bool {
1467         self.abi.is_unsized()
1468     }
1469
1470     /// Returns `true` if the type is a ZST and not unsized.
1471     pub fn is_zst(&self) -> bool {
1472         match self.abi {
1473             Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false,
1474             Abi::Uninhabited => self.size.bytes() == 0,
1475             Abi::Aggregate { sized } => sized && self.size.bytes() == 0,
1476         }
1477     }
1478
1479     /// Determines if this type permits "raw" initialization by just transmuting some
1480     /// memory into an instance of `T`.
1481     ///
1482     /// `init_kind` indicates if the memory is zero-initialized or left uninitialized.
1483     ///
1484     /// `strict` is an opt-in debugging flag added in #97323 that enables more checks.
1485     ///
1486     /// This is conservative: in doubt, it will answer `true`.
1487     ///
1488     /// FIXME: Once we removed all the conservatism, we could alternatively
1489     /// create an all-0/all-undef constant and run the const value validator to see if
1490     /// this is a valid value for the given type.
1491     pub fn might_permit_raw_init<C>(self, cx: &C, init_kind: InitKind, strict: bool) -> bool
1492     where
1493         Self: Copy,
1494         Ty: TyAbiInterface<'a, C>,
1495         C: HasDataLayout,
1496     {
1497         let scalar_allows_raw_init = move |s: Scalar| -> bool {
1498             match init_kind {
1499                 InitKind::Zero => {
1500                     // The range must contain 0.
1501                     s.valid_range(cx).contains(0)
1502                 }
1503                 InitKind::Uninit => {
1504                     if strict {
1505                         // The type must be allowed to be uninit (which means "is a union").
1506                         s.is_uninit_valid()
1507                     } else {
1508                         // The range must include all values.
1509                         s.is_always_valid(cx)
1510                     }
1511                 }
1512             }
1513         };
1514
1515         // Check the ABI.
1516         let valid = match self.abi {
1517             Abi::Uninhabited => false, // definitely UB
1518             Abi::Scalar(s) => scalar_allows_raw_init(s),
1519             Abi::ScalarPair(s1, s2) => scalar_allows_raw_init(s1) && scalar_allows_raw_init(s2),
1520             Abi::Vector { element: s, count } => count == 0 || scalar_allows_raw_init(s),
1521             Abi::Aggregate { .. } => true, // Fields are checked below.
1522         };
1523         if !valid {
1524             // This is definitely not okay.
1525             return false;
1526         }
1527
1528         // If we have not found an error yet, we need to recursively descend into fields.
1529         match &self.fields {
1530             FieldsShape::Primitive | FieldsShape::Union { .. } => {}
1531             FieldsShape::Array { count, .. } => {
1532                 // FIXME(#66151): For now, we are conservative and do not check arrays by default.
1533                 if strict
1534                     && *count > 0
1535                     && !self.field(cx, 0).might_permit_raw_init(cx, init_kind, strict)
1536                 {
1537                     // Found non empty array with a type that is unhappy about this kind of initialization
1538                     return false;
1539                 }
1540             }
1541             FieldsShape::Arbitrary { offsets, .. } => {
1542                 for idx in 0..offsets.len() {
1543                     if !self.field(cx, idx).might_permit_raw_init(cx, init_kind, strict) {
1544                         // We found a field that is unhappy with this kind of initialization.
1545                         return false;
1546                     }
1547                 }
1548             }
1549         }
1550
1551         // FIXME(#66151): For now, we are conservative and do not check `self.variants`.
1552         true
1553     }
1554 }