]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/type_of.rs
Rollup merge of #60513 - chrisvittal:remove-borrowck-compare, r=matthewjasper
[rust.git] / src / librustc_codegen_llvm / type_of.rs
1 use crate::abi::{FnType, FnTypeExt};
2 use crate::common::*;
3 use crate::type_::Type;
4 use rustc::hir;
5 use rustc::ty::{self, Ty, TypeFoldable};
6 use rustc::ty::layout::{self, Align, LayoutOf, Size, TyLayout};
7 use rustc_target::abi::FloatTy;
8 use rustc_mir::monomorphize::item::DefPathBasedNames;
9 use rustc_codegen_ssa::traits::*;
10
11 use std::fmt::Write;
12
13 fn uncached_llvm_type<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
14                                 layout: TyLayout<'tcx>,
15                                 defer: &mut Option<(&'a Type, TyLayout<'tcx>)>)
16                                 -> &'a Type {
17     match layout.abi {
18         layout::Abi::Scalar(_) => bug!("handled elsewhere"),
19         layout::Abi::Vector { ref element, count } => {
20             // LLVM has a separate type for 64-bit SIMD vectors on X86 called
21             // `x86_mmx` which is needed for some SIMD operations. As a bit of a
22             // hack (all SIMD definitions are super unstable anyway) we
23             // recognize any one-element SIMD vector as "this should be an
24             // x86_mmx" type. In general there shouldn't be a need for other
25             // one-element SIMD vectors, so it's assumed this won't clash with
26             // much else.
27             let use_x86_mmx = count == 1 && layout.size.bits() == 64 &&
28                 (cx.sess().target.target.arch == "x86" ||
29                  cx.sess().target.target.arch == "x86_64");
30             if use_x86_mmx {
31                 return cx.type_x86_mmx()
32             } else {
33                 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
34                 return cx.type_vector(element, count);
35             }
36         }
37         layout::Abi::ScalarPair(..) => {
38             return cx.type_struct( &[
39                 layout.scalar_pair_element_llvm_type(cx, 0, false),
40                 layout.scalar_pair_element_llvm_type(cx, 1, false),
41             ], false);
42         }
43         layout::Abi::Uninhabited |
44         layout::Abi::Aggregate { .. } => {}
45     }
46
47     let name = match layout.ty.sty {
48         ty::Closure(..) |
49         ty::Generator(..) |
50         ty::Adt(..) |
51         // FIXME(eddyb) producing readable type names for trait objects can result
52         // in problematically distinct types due to HRTB and subtyping (see #47638).
53         // ty::Dynamic(..) |
54         ty::Foreign(..) |
55         ty::Str => {
56             let mut name = String::with_capacity(32);
57             let printer = DefPathBasedNames::new(cx.tcx, true, true);
58             printer.push_type_name(layout.ty, &mut name, false);
59             if let (&ty::Adt(def, _), &layout::Variants::Single { index })
60                  = (&layout.ty.sty, &layout.variants)
61             {
62                 if def.is_enum() && !def.variants.is_empty() {
63                     write!(&mut name, "::{}", def.variants[index].ident).unwrap();
64                 }
65             }
66             if let (&ty::Generator(_, substs, _), &layout::Variants::Single { index })
67                  = (&layout.ty.sty, &layout.variants)
68             {
69                 write!(&mut name, "::{}", substs.variant_name(index)).unwrap();
70             }
71             Some(name)
72         }
73         _ => None
74     };
75
76     match layout.fields {
77         layout::FieldPlacement::Union(_) => {
78             let fill = cx.type_padding_filler(layout.size, layout.align.abi);
79             let packed = false;
80             match name {
81                 None => {
82                     cx.type_struct(&[fill], packed)
83                 }
84                 Some(ref name) => {
85                     let llty = cx.type_named_struct(name);
86                     cx.set_struct_body(llty, &[fill], packed);
87                     llty
88                 }
89             }
90         }
91         layout::FieldPlacement::Array { count, .. } => {
92             cx.type_array(layout.field(cx, 0).llvm_type(cx), count)
93         }
94         layout::FieldPlacement::Arbitrary { .. } => {
95             match name {
96                 None => {
97                     let (llfields, packed) = struct_llfields(cx, layout);
98                     cx.type_struct( &llfields, packed)
99                 }
100                 Some(ref name) => {
101                     let llty = cx.type_named_struct( name);
102                     *defer = Some((llty, layout));
103                     llty
104                 }
105             }
106         }
107     }
108 }
109
110 fn struct_llfields<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
111                              layout: TyLayout<'tcx>)
112                              -> (Vec<&'a Type>, bool) {
113     debug!("struct_llfields: {:#?}", layout);
114     let field_count = layout.fields.count();
115
116     let mut packed = false;
117     let mut offset = Size::ZERO;
118     let mut prev_effective_align = layout.align.abi;
119     let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
120     for i in layout.fields.index_by_increasing_offset() {
121         let target_offset = layout.fields.offset(i as usize);
122         let field = layout.field(cx, i);
123         let effective_field_align = layout.align.abi
124             .min(field.align.abi)
125             .restrict_for_offset(target_offset);
126         packed |= effective_field_align < field.align.abi;
127
128         debug!("struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
129                 effective_field_align: {}",
130                i, field, offset, target_offset, effective_field_align.bytes());
131         assert!(target_offset >= offset);
132         let padding = target_offset - offset;
133         let padding_align = prev_effective_align.min(effective_field_align);
134         assert_eq!(offset.align_to(padding_align) + padding, target_offset);
135         result.push(cx.type_padding_filler( padding, padding_align));
136         debug!("    padding before: {:?}", padding);
137
138         result.push(field.llvm_type(cx));
139         offset = target_offset + field.size;
140         prev_effective_align = effective_field_align;
141     }
142     if !layout.is_unsized() && field_count > 0 {
143         if offset > layout.size {
144             bug!("layout: {:#?} stride: {:?} offset: {:?}",
145                  layout, layout.size, offset);
146         }
147         let padding = layout.size - offset;
148         let padding_align = prev_effective_align;
149         assert_eq!(offset.align_to(padding_align) + padding, layout.size);
150         debug!("struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
151                padding, offset, layout.size);
152         result.push(cx.type_padding_filler(padding, padding_align));
153         assert_eq!(result.len(), 1 + field_count * 2);
154     } else {
155         debug!("struct_llfields: offset: {:?} stride: {:?}",
156                offset, layout.size);
157     }
158
159     (result, packed)
160 }
161
162 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
163     pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
164         self.layout_of(ty).align.abi
165     }
166
167     pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
168         self.layout_of(ty).size
169     }
170
171     pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
172         let layout = self.layout_of(ty);
173         (layout.size, layout.align.abi)
174     }
175 }
176
177 #[derive(Copy, Clone, PartialEq, Eq)]
178 pub enum PointerKind {
179     /// Most general case, we know no restrictions to tell LLVM.
180     Shared,
181
182     /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
183     Frozen,
184
185     /// `&mut T`, when we know `noalias` is safe for LLVM.
186     UniqueBorrowed,
187
188     /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
189     UniqueOwned
190 }
191
192 #[derive(Copy, Clone)]
193 pub struct PointeeInfo {
194     pub size: Size,
195     pub align: Align,
196     pub safe: Option<PointerKind>,
197 }
198
199 pub trait LayoutLlvmExt<'tcx> {
200     fn is_llvm_immediate(&self) -> bool;
201     fn is_llvm_scalar_pair<'a>(&self) -> bool;
202     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
203     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
204     fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
205                                scalar: &layout::Scalar, offset: Size) -> &'a Type;
206     fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
207                                          index: usize, immediate: bool) -> &'a Type;
208     fn llvm_field_index(&self, index: usize) -> u64;
209     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
210                            -> Option<PointeeInfo>;
211 }
212
213 impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> {
214     fn is_llvm_immediate(&self) -> bool {
215         match self.abi {
216             layout::Abi::Scalar(_) |
217             layout::Abi::Vector { .. } => true,
218             layout::Abi::ScalarPair(..) => false,
219             layout::Abi::Uninhabited |
220             layout::Abi::Aggregate { .. } => self.is_zst()
221         }
222     }
223
224     fn is_llvm_scalar_pair<'a>(&self) -> bool {
225         match self.abi {
226             layout::Abi::ScalarPair(..) => true,
227             layout::Abi::Uninhabited |
228             layout::Abi::Scalar(_) |
229             layout::Abi::Vector { .. } |
230             layout::Abi::Aggregate { .. } => false
231         }
232     }
233
234     /// Gets the LLVM type corresponding to a Rust type, i.e., `rustc::ty::Ty`.
235     /// The pointee type of the pointer in `PlaceRef` is always this type.
236     /// For sized types, it is also the right LLVM type for an `alloca`
237     /// containing a value of that type, and most immediates (except `bool`).
238     /// Unsized types, however, are represented by a "minimal unit", e.g.
239     /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
240     /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
241     /// If the type is an unsized struct, the regular layout is generated,
242     /// with the inner-most trailing unsized field using the "minimal unit"
243     /// of that field's type - this is useful for taking the address of
244     /// that field and ensuring the struct has the right alignment.
245     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
246         if let layout::Abi::Scalar(ref scalar) = self.abi {
247             // Use a different cache for scalars because pointers to DSTs
248             // can be either fat or thin (data pointers of fat pointers).
249             if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
250                 return llty;
251             }
252             let llty = match self.ty.sty {
253                 ty::Ref(_, ty, _) |
254                 ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
255                     cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
256                 }
257                 ty::Adt(def, _) if def.is_box() => {
258                     cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
259                 }
260                 ty::FnPtr(sig) => {
261                     let sig = cx.tcx.normalize_erasing_late_bound_regions(
262                         ty::ParamEnv::reveal_all(),
263                         &sig,
264                     );
265                     cx.fn_ptr_backend_type(&FnType::new(cx, sig, &[]))
266                 }
267                 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO)
268             };
269             cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
270             return llty;
271         }
272
273
274         // Check the cache.
275         let variant_index = match self.variants {
276             layout::Variants::Single { index } => Some(index),
277             _ => None
278         };
279         if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
280             return llty;
281         }
282
283         debug!("llvm_type({:#?})", self);
284
285         assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
286
287         // Make sure lifetimes are erased, to avoid generating distinct LLVM
288         // types for Rust types that only differ in the choice of lifetimes.
289         let normal_ty = cx.tcx.erase_regions(&self.ty);
290
291         let mut defer = None;
292         let llty = if self.ty != normal_ty {
293             let mut layout = cx.layout_of(normal_ty);
294             if let Some(v) = variant_index {
295                 layout = layout.for_variant(cx, v);
296             }
297             layout.llvm_type(cx)
298         } else {
299             uncached_llvm_type(cx, *self, &mut defer)
300         };
301         debug!("--> mapped {:#?} to llty={:?}", self, llty);
302
303         cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
304
305         if let Some((llty, layout)) = defer {
306             let (llfields, packed) = struct_llfields(cx, layout);
307             cx.set_struct_body(llty, &llfields, packed)
308         }
309
310         llty
311     }
312
313     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
314         if let layout::Abi::Scalar(ref scalar) = self.abi {
315             if scalar.is_bool() {
316                 return cx.type_i1();
317             }
318         }
319         self.llvm_type(cx)
320     }
321
322     fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
323                                scalar: &layout::Scalar, offset: Size) -> &'a Type {
324         match scalar.value {
325             layout::Int(i, _) => cx.type_from_integer( i),
326             layout::Float(FloatTy::F32) => cx.type_f32(),
327             layout::Float(FloatTy::F64) => cx.type_f64(),
328             layout::Pointer => {
329                 // If we know the alignment, pick something better than i8.
330                 let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) {
331                     cx.type_pointee_for_align(pointee.align)
332                 } else {
333                     cx.type_i8()
334                 };
335                 cx.type_ptr_to(pointee)
336             }
337         }
338     }
339
340     fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
341                                          index: usize, immediate: bool) -> &'a Type {
342         // HACK(eddyb) special-case fat pointers until LLVM removes
343         // pointee types, to avoid bitcasting every `OperandRef::deref`.
344         match self.ty.sty {
345             ty::Ref(..) |
346             ty::RawPtr(_) => {
347                 return self.field(cx, index).llvm_type(cx);
348             }
349             ty::Adt(def, _) if def.is_box() => {
350                 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
351                 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
352             }
353             _ => {}
354         }
355
356         let (a, b) = match self.abi {
357             layout::Abi::ScalarPair(ref a, ref b) => (a, b),
358             _ => bug!("TyLayout::scalar_pair_element_llty({:?}): not applicable", self)
359         };
360         let scalar = [a, b][index];
361
362         // Make sure to return the same type `immediate_llvm_type` would when
363         // dealing with an immediate pair.  This means that `(bool, bool)` is
364         // effectively represented as `{i8, i8}` in memory and two `i1`s as an
365         // immediate, just like `bool` is typically `i8` in memory and only `i1`
366         // when immediate.  We need to load/store `bool` as `i8` to avoid
367         // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
368         if immediate && scalar.is_bool() {
369             return cx.type_i1();
370         }
371
372         let offset = if index == 0 {
373             Size::ZERO
374         } else {
375             a.value.size(cx).align_to(b.value.align(cx).abi)
376         };
377         self.scalar_llvm_type_at(cx, scalar, offset)
378     }
379
380     fn llvm_field_index(&self, index: usize) -> u64 {
381         match self.abi {
382             layout::Abi::Scalar(_) |
383             layout::Abi::ScalarPair(..) => {
384                 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
385             }
386             _ => {}
387         }
388         match self.fields {
389             layout::FieldPlacement::Union(_) => {
390                 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
391             }
392
393             layout::FieldPlacement::Array { .. } => {
394                 index as u64
395             }
396
397             layout::FieldPlacement::Arbitrary { .. } => {
398                 1 + (self.fields.memory_index(index) as u64) * 2
399             }
400         }
401     }
402
403     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
404                            -> Option<PointeeInfo> {
405         if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
406             return pointee;
407         }
408
409         let mut result = None;
410         match self.ty.sty {
411             ty::RawPtr(mt) if offset.bytes() == 0 => {
412                 let (size, align) = cx.size_and_align_of(mt.ty);
413                 result = Some(PointeeInfo {
414                     size,
415                     align,
416                     safe: None
417                 });
418             }
419
420             ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
421                 let (size, align) = cx.size_and_align_of(ty);
422
423                 let kind = match mt {
424                     hir::MutImmutable => if cx.type_is_freeze(ty) {
425                         PointerKind::Frozen
426                     } else {
427                         PointerKind::Shared
428                     },
429                     hir::MutMutable => {
430                         // Previously we would only emit noalias annotations for LLVM >= 6 or in
431                         // panic=abort mode. That was deemed right, as prior versions had many bugs
432                         // in conjunction with unwinding, but later versions didn’t seem to have
433                         // said issues. See issue #31681.
434                         //
435                         // Alas, later on we encountered a case where noalias would generate wrong
436                         // code altogether even with recent versions of LLVM in *safe* code with no
437                         // unwinding involved. See #54462.
438                         //
439                         // For now, do not enable mutable_noalias by default at all, while the
440                         // issue is being figured out.
441                         let mutable_noalias = cx.tcx.sess.opts.debugging_opts.mutable_noalias
442                             .unwrap_or(false);
443                         if mutable_noalias {
444                             PointerKind::UniqueBorrowed
445                         } else {
446                             PointerKind::Shared
447                         }
448                     }
449                 };
450
451                 result = Some(PointeeInfo {
452                     size,
453                     align,
454                     safe: Some(kind)
455                 });
456             }
457
458             _ => {
459                 let mut data_variant = match self.variants {
460                     // Within the discriminant field, only the niche itself is
461                     // always initialized, so we only check for a pointer at its
462                     // offset.
463                     //
464                     // If the niche is a pointer, it's either valid (according
465                     // to its type), or null (which the niche field's scalar
466                     // validity range encodes).  This allows using
467                     // `dereferenceable_or_null` for e.g., `Option<&T>`, and
468                     // this will continue to work as long as we don't start
469                     // using more niches than just null (e.g., the first page of
470                     // the address space, or unaligned pointers).
471                     layout::Variants::Multiple {
472                         discr_kind: layout::DiscriminantKind::Niche {
473                             dataful_variant,
474                             ..
475                         },
476                         discr_index,
477                         ..
478                     } if self.fields.offset(discr_index) == offset =>
479                         Some(self.for_variant(cx, dataful_variant)),
480                     _ => Some(*self),
481                 };
482
483                 if let Some(variant) = data_variant {
484                     // We're not interested in any unions.
485                     if let layout::FieldPlacement::Union(_) = variant.fields {
486                         data_variant = None;
487                     }
488                 }
489
490                 if let Some(variant) = data_variant {
491                     let ptr_end = offset + layout::Pointer.size(cx);
492                     for i in 0..variant.fields.count() {
493                         let field_start = variant.fields.offset(i);
494                         if field_start <= offset {
495                             let field = variant.field(cx, i);
496                             if ptr_end <= field_start + field.size {
497                                 // We found the right field, look inside it.
498                                 result = field.pointee_info_at(cx, offset - field_start);
499                                 break;
500                             }
501                         }
502                     }
503                 }
504
505                 // FIXME(eddyb) This should be for `ptr::Unique<T>`, not `Box<T>`.
506                 if let Some(ref mut pointee) = result {
507                     if let ty::Adt(def, _) = self.ty.sty {
508                         if def.is_box() && offset.bytes() == 0 {
509                             pointee.safe = Some(PointerKind::UniqueOwned);
510                         }
511                     }
512                 }
513             }
514         }
515
516         cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);
517         result
518     }
519 }