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