]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/type_of.rs
Auto merge of #84228 - SkiFire13:fix-84213, r=estebank
[rust.git] / compiler / rustc_codegen_llvm / src / type_of.rs
1 use crate::abi::FnAbi;
2 use crate::common::*;
3 use crate::type_::Type;
4 use rustc_codegen_ssa::traits::*;
5 use rustc_middle::bug;
6 use rustc_middle::ty::layout::{FnAbiExt, TyAndLayout};
7 use rustc_middle::ty::print::with_no_trimmed_paths;
8 use rustc_middle::ty::{self, Ty, TypeFoldable};
9 use rustc_target::abi::{Abi, AddressSpace, Align, FieldsShape};
10 use rustc_target::abi::{Int, Pointer, F32, F64};
11 use rustc_target::abi::{LayoutOf, PointeeInfo, Scalar, Size, TyAndLayoutMethods, Variants};
12 use tracing::debug;
13
14 use std::fmt::Write;
15
16 fn uncached_llvm_type<'a, 'tcx>(
17     cx: &CodegenCx<'a, 'tcx>,
18     layout: TyAndLayout<'tcx>,
19     defer: &mut Option<(&'a Type, TyAndLayout<'tcx>)>,
20 ) -> &'a Type {
21     match layout.abi {
22         Abi::Scalar(_) => bug!("handled elsewhere"),
23         Abi::Vector { ref element, count } => {
24             let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
25             return cx.type_vector(element, count);
26         }
27         Abi::ScalarPair(..) => {
28             return cx.type_struct(
29                 &[
30                     layout.scalar_pair_element_llvm_type(cx, 0, false),
31                     layout.scalar_pair_element_llvm_type(cx, 1, false),
32                 ],
33                 false,
34             );
35         }
36         Abi::Uninhabited | Abi::Aggregate { .. } => {}
37     }
38
39     let name = match layout.ty.kind() {
40         // FIXME(eddyb) producing readable type names for trait objects can result
41         // in problematically distinct types due to HRTB and subtyping (see #47638).
42         // ty::Dynamic(..) |
43         ty::Adt(..) | ty::Closure(..) | ty::Foreign(..) | ty::Generator(..) | ty::Str => {
44             let mut name = with_no_trimmed_paths(|| layout.ty.to_string());
45             if let (&ty::Adt(def, _), &Variants::Single { index }) =
46                 (layout.ty.kind(), &layout.variants)
47             {
48                 if def.is_enum() && !def.variants.is_empty() {
49                     write!(&mut name, "::{}", def.variants[index].ident).unwrap();
50                 }
51             }
52             if let (&ty::Generator(_, _, _), &Variants::Single { index }) =
53                 (layout.ty.kind(), &layout.variants)
54             {
55                 write!(&mut name, "::{}", ty::GeneratorSubsts::variant_name(index)).unwrap();
56             }
57             Some(name)
58         }
59         _ => None,
60     };
61
62     match layout.fields {
63         FieldsShape::Primitive | FieldsShape::Union(_) => {
64             let fill = cx.type_padding_filler(layout.size, layout.align.abi);
65             let packed = false;
66             match name {
67                 None => cx.type_struct(&[fill], packed),
68                 Some(ref name) => {
69                     let llty = cx.type_named_struct(name);
70                     cx.set_struct_body(llty, &[fill], packed);
71                     llty
72                 }
73             }
74         }
75         FieldsShape::Array { count, .. } => cx.type_array(layout.field(cx, 0).llvm_type(cx), count),
76         FieldsShape::Arbitrary { .. } => match name {
77             None => {
78                 let (llfields, packed) = struct_llfields(cx, layout);
79                 cx.type_struct(&llfields, packed)
80             }
81             Some(ref name) => {
82                 let llty = cx.type_named_struct(name);
83                 *defer = Some((llty, layout));
84                 llty
85             }
86         },
87     }
88 }
89
90 fn struct_llfields<'a, 'tcx>(
91     cx: &CodegenCx<'a, 'tcx>,
92     layout: TyAndLayout<'tcx>,
93 ) -> (Vec<&'a Type>, bool) {
94     debug!("struct_llfields: {:#?}", layout);
95     let field_count = layout.fields.count();
96
97     let mut packed = false;
98     let mut offset = Size::ZERO;
99     let mut prev_effective_align = layout.align.abi;
100     let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
101     for i in layout.fields.index_by_increasing_offset() {
102         let target_offset = layout.fields.offset(i as usize);
103         let field = layout.field(cx, i);
104         let effective_field_align =
105             layout.align.abi.min(field.align.abi).restrict_for_offset(target_offset);
106         packed |= effective_field_align < field.align.abi;
107
108         debug!(
109             "struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
110                 effective_field_align: {}",
111             i,
112             field,
113             offset,
114             target_offset,
115             effective_field_align.bytes()
116         );
117         assert!(target_offset >= offset);
118         let padding = target_offset - offset;
119         let padding_align = prev_effective_align.min(effective_field_align);
120         assert_eq!(offset.align_to(padding_align) + padding, target_offset);
121         result.push(cx.type_padding_filler(padding, padding_align));
122         debug!("    padding before: {:?}", padding);
123
124         result.push(field.llvm_type(cx));
125         offset = target_offset + field.size;
126         prev_effective_align = effective_field_align;
127     }
128     if !layout.is_unsized() && field_count > 0 {
129         if offset > layout.size {
130             bug!("layout: {:#?} stride: {:?} offset: {:?}", layout, layout.size, offset);
131         }
132         let padding = layout.size - offset;
133         let padding_align = prev_effective_align;
134         assert_eq!(offset.align_to(padding_align) + padding, layout.size);
135         debug!(
136             "struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
137             padding, offset, layout.size
138         );
139         result.push(cx.type_padding_filler(padding, padding_align));
140         assert_eq!(result.len(), 1 + field_count * 2);
141     } else {
142         debug!("struct_llfields: offset: {:?} stride: {:?}", offset, layout.size);
143     }
144
145     (result, packed)
146 }
147
148 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
149     pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
150         self.layout_of(ty).align.abi
151     }
152
153     pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
154         self.layout_of(ty).size
155     }
156
157     pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
158         let layout = self.layout_of(ty);
159         (layout.size, layout.align.abi)
160     }
161 }
162
163 pub trait LayoutLlvmExt<'tcx> {
164     fn is_llvm_immediate(&self) -> bool;
165     fn is_llvm_scalar_pair(&self) -> bool;
166     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
167     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
168     fn scalar_llvm_type_at<'a>(
169         &self,
170         cx: &CodegenCx<'a, 'tcx>,
171         scalar: &Scalar,
172         offset: Size,
173     ) -> &'a Type;
174     fn scalar_pair_element_llvm_type<'a>(
175         &self,
176         cx: &CodegenCx<'a, 'tcx>,
177         index: usize,
178         immediate: bool,
179     ) -> &'a Type;
180     fn llvm_field_index(&self, index: usize) -> u64;
181     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo>;
182 }
183
184 impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> {
185     fn is_llvm_immediate(&self) -> bool {
186         match self.abi {
187             Abi::Scalar(_) | Abi::Vector { .. } => true,
188             Abi::ScalarPair(..) => false,
189             Abi::Uninhabited | Abi::Aggregate { .. } => self.is_zst(),
190         }
191     }
192
193     fn is_llvm_scalar_pair(&self) -> bool {
194         match self.abi {
195             Abi::ScalarPair(..) => true,
196             Abi::Uninhabited | Abi::Scalar(_) | Abi::Vector { .. } | Abi::Aggregate { .. } => false,
197         }
198     }
199
200     /// Gets the LLVM type corresponding to a Rust type, i.e., `rustc_middle::ty::Ty`.
201     /// The pointee type of the pointer in `PlaceRef` is always this type.
202     /// For sized types, it is also the right LLVM type for an `alloca`
203     /// containing a value of that type, and most immediates (except `bool`).
204     /// Unsized types, however, are represented by a "minimal unit", e.g.
205     /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
206     /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
207     /// If the type is an unsized struct, the regular layout is generated,
208     /// with the inner-most trailing unsized field using the "minimal unit"
209     /// of that field's type - this is useful for taking the address of
210     /// that field and ensuring the struct has the right alignment.
211     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
212         if let Abi::Scalar(ref scalar) = self.abi {
213             // Use a different cache for scalars because pointers to DSTs
214             // can be either fat or thin (data pointers of fat pointers).
215             if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
216                 return llty;
217             }
218             let llty = match *self.ty.kind() {
219                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
220                     cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
221                 }
222                 ty::Adt(def, _) if def.is_box() => {
223                     cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
224                 }
225                 ty::FnPtr(sig) => cx.fn_ptr_backend_type(&FnAbi::of_fn_ptr(cx, sig, &[])),
226                 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO),
227             };
228             cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
229             return llty;
230         }
231
232         // Check the cache.
233         let variant_index = match self.variants {
234             Variants::Single { index } => Some(index),
235             _ => None,
236         };
237         if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
238             return llty;
239         }
240
241         debug!("llvm_type({:#?})", self);
242
243         assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
244
245         // Make sure lifetimes are erased, to avoid generating distinct LLVM
246         // types for Rust types that only differ in the choice of lifetimes.
247         let normal_ty = cx.tcx.erase_regions(self.ty);
248
249         let mut defer = None;
250         let llty = if self.ty != normal_ty {
251             let mut layout = cx.layout_of(normal_ty);
252             if let Some(v) = variant_index {
253                 layout = layout.for_variant(cx, v);
254             }
255             layout.llvm_type(cx)
256         } else {
257             uncached_llvm_type(cx, *self, &mut defer)
258         };
259         debug!("--> mapped {:#?} to llty={:?}", self, llty);
260
261         cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
262
263         if let Some((llty, layout)) = defer {
264             let (llfields, packed) = struct_llfields(cx, layout);
265             cx.set_struct_body(llty, &llfields, packed)
266         }
267
268         llty
269     }
270
271     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
272         if let Abi::Scalar(ref scalar) = self.abi {
273             if scalar.is_bool() {
274                 return cx.type_i1();
275             }
276         }
277         self.llvm_type(cx)
278     }
279
280     fn scalar_llvm_type_at<'a>(
281         &self,
282         cx: &CodegenCx<'a, 'tcx>,
283         scalar: &Scalar,
284         offset: Size,
285     ) -> &'a Type {
286         match scalar.value {
287             Int(i, _) => cx.type_from_integer(i),
288             F32 => cx.type_f32(),
289             F64 => cx.type_f64(),
290             Pointer => {
291                 // If we know the alignment, pick something better than i8.
292                 let (pointee, address_space) =
293                     if let Some(pointee) = self.pointee_info_at(cx, offset) {
294                         (cx.type_pointee_for_align(pointee.align), pointee.address_space)
295                     } else {
296                         (cx.type_i8(), AddressSpace::DATA)
297                     };
298                 cx.type_ptr_to_ext(pointee, address_space)
299             }
300         }
301     }
302
303     fn scalar_pair_element_llvm_type<'a>(
304         &self,
305         cx: &CodegenCx<'a, 'tcx>,
306         index: usize,
307         immediate: bool,
308     ) -> &'a Type {
309         // HACK(eddyb) special-case fat pointers until LLVM removes
310         // pointee types, to avoid bitcasting every `OperandRef::deref`.
311         match self.ty.kind() {
312             ty::Ref(..) | ty::RawPtr(_) => {
313                 return self.field(cx, index).llvm_type(cx);
314             }
315             ty::Adt(def, _) if def.is_box() => {
316                 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
317                 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
318             }
319             _ => {}
320         }
321
322         let (a, b) = match self.abi {
323             Abi::ScalarPair(ref a, ref b) => (a, b),
324             _ => bug!("TyAndLayout::scalar_pair_element_llty({:?}): not applicable", self),
325         };
326         let scalar = [a, b][index];
327
328         // Make sure to return the same type `immediate_llvm_type` would when
329         // dealing with an immediate pair.  This means that `(bool, bool)` is
330         // effectively represented as `{i8, i8}` in memory and two `i1`s as an
331         // immediate, just like `bool` is typically `i8` in memory and only `i1`
332         // when immediate.  We need to load/store `bool` as `i8` to avoid
333         // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
334         if immediate && scalar.is_bool() {
335             return cx.type_i1();
336         }
337
338         let offset =
339             if index == 0 { Size::ZERO } else { a.value.size(cx).align_to(b.value.align(cx).abi) };
340         self.scalar_llvm_type_at(cx, scalar, offset)
341     }
342
343     fn llvm_field_index(&self, index: usize) -> u64 {
344         match self.abi {
345             Abi::Scalar(_) | Abi::ScalarPair(..) => {
346                 bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self)
347             }
348             _ => {}
349         }
350         match self.fields {
351             FieldsShape::Primitive | FieldsShape::Union(_) => {
352                 bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self)
353             }
354
355             FieldsShape::Array { .. } => index as u64,
356
357             FieldsShape::Arbitrary { .. } => 1 + (self.fields.memory_index(index) as u64) * 2,
358         }
359     }
360
361     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo> {
362         if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
363             return pointee;
364         }
365
366         let result = Ty::pointee_info_at(*self, cx, offset);
367
368         cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);
369         result
370     }
371 }