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