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