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