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