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.
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.
11 use abi::{FnType, FnTypeExt};
15 use rustc::ty::{self, Ty, TypeFoldable};
16 use rustc::ty::layout::{self, Align, LayoutOf, Size, TyLayout};
17 use rustc_target::spec::PanicStrategy;
18 use rustc_target::abi::FloatTy;
19 use rustc_mir::monomorphize::item::DefPathBasedNames;
24 fn uncached_llvm_type<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
25 layout: TyLayout<'tcx>,
26 defer: &mut Option<(&'a Type, TyLayout<'tcx>)>)
29 layout::Abi::Scalar(_) => bug!("handled elsewhere"),
30 layout::Abi::Vector { ref element, count } => {
31 // LLVM has a separate type for 64-bit SIMD vectors on X86 called
32 // `x86_mmx` which is needed for some SIMD operations. As a bit of a
33 // hack (all SIMD definitions are super unstable anyway) we
34 // recognize any one-element SIMD vector as "this should be an
35 // x86_mmx" type. In general there shouldn't be a need for other
36 // one-element SIMD vectors, so it's assumed this won't clash with
38 let use_x86_mmx = count == 1 && layout.size.bits() == 64 &&
39 (cx.sess().target.target.arch == "x86" ||
40 cx.sess().target.target.arch == "x86_64");
42 return Type::x86_mmx(cx)
44 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
45 return Type::vector(element, count);
48 layout::Abi::ScalarPair(..) => {
49 return Type::struct_(cx, &[
50 layout.scalar_pair_element_llvm_type(cx, 0, false),
51 layout.scalar_pair_element_llvm_type(cx, 1, false),
54 layout::Abi::Uninhabited |
55 layout::Abi::Aggregate { .. } => {}
58 let name = match layout.ty.sty {
62 // FIXME(eddyb) producing readable type names for trait objects can result
63 // in problematically distinct types due to HRTB and subtyping (see #47638).
64 // ty::TyDynamic(..) |
67 let mut name = String::with_capacity(32);
68 let printer = DefPathBasedNames::new(cx.tcx, true, true);
69 printer.push_type_name(layout.ty, &mut name);
70 match (&layout.ty.sty, &layout.variants) {
71 (&ty::TyAdt(def, _), &layout::Variants::Single { index }) => {
72 if def.is_enum() && !def.variants.is_empty() {
73 write!(&mut name, "::{}", def.variants[index].name).unwrap();
84 layout::FieldPlacement::Union(_) => {
85 let fill = Type::padding_filler(cx, layout.size, layout.align);
89 Type::struct_(cx, &[fill], packed)
92 let mut llty = Type::named_struct(cx, name);
93 llty.set_struct_body(&[fill], packed);
98 layout::FieldPlacement::Array { count, .. } => {
99 Type::array(layout.field(cx, 0).llvm_type(cx), count)
101 layout::FieldPlacement::Arbitrary { .. } => {
104 let (llfields, packed) = struct_llfields(cx, layout);
105 Type::struct_(cx, &llfields, packed)
108 let llty = Type::named_struct(cx, name);
109 *defer = Some((llty, layout));
117 fn struct_llfields<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
118 layout: TyLayout<'tcx>)
119 -> (Vec<&'a Type>, bool) {
120 debug!("struct_llfields: {:#?}", layout);
121 let field_count = layout.fields.count();
123 let mut packed = false;
124 let mut offset = Size::ZERO;
125 let mut prev_align = layout.align;
126 let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
127 for i in layout.fields.index_by_increasing_offset() {
128 let field = layout.field(cx, i);
129 packed |= layout.align.abi() < field.align.abi();
131 let target_offset = layout.fields.offset(i as usize);
132 debug!("struct_llfields: {}: {:?} offset: {:?} target_offset: {:?}",
133 i, field, offset, target_offset);
134 assert!(target_offset >= offset);
135 let padding = target_offset - offset;
136 let padding_align = layout.align.min(prev_align).min(field.align);
137 assert_eq!(offset.abi_align(padding_align) + padding, target_offset);
138 result.push(Type::padding_filler(cx, padding, padding_align));
139 debug!(" padding before: {:?}", padding);
141 result.push(field.llvm_type(cx));
142 offset = target_offset + field.size;
143 prev_align = field.align;
145 if !layout.is_unsized() && field_count > 0 {
146 if offset > layout.size {
147 bug!("layout: {:#?} stride: {:?} offset: {:?}",
148 layout, layout.size, offset);
150 let padding = layout.size - offset;
151 let padding_align = layout.align.min(prev_align);
152 assert_eq!(offset.abi_align(padding_align) + padding, layout.size);
153 debug!("struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
154 padding, offset, layout.size);
155 result.push(Type::padding_filler(cx, padding, padding_align));
156 assert!(result.len() == 1 + field_count * 2);
158 debug!("struct_llfields: offset: {:?} stride: {:?}",
159 offset, layout.size);
165 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
166 pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
167 self.layout_of(ty).align
170 pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
171 self.layout_of(ty).size
174 pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
175 self.layout_of(ty).size_and_align()
179 #[derive(Copy, Clone, PartialEq, Eq)]
180 pub enum PointerKind {
181 /// Most general case, we know no restrictions to tell LLVM.
184 /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
187 /// `&mut T`, when we know `noalias` is safe for LLVM.
190 /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
194 #[derive(Copy, Clone)]
195 pub struct PointeeInfo {
198 pub safe: Option<PointerKind>,
201 pub trait LayoutLlvmExt<'tcx> {
202 fn is_llvm_immediate(&self) -> bool;
203 fn is_llvm_scalar_pair<'a>(&self) -> bool;
204 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
205 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
206 fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
207 scalar: &layout::Scalar, offset: Size) -> &'a Type;
208 fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
209 index: usize, immediate: bool) -> &'a Type;
210 fn llvm_field_index(&self, index: usize) -> u64;
211 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
212 -> Option<PointeeInfo>;
215 impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> {
216 fn is_llvm_immediate(&self) -> bool {
218 layout::Abi::Scalar(_) |
219 layout::Abi::Vector { .. } => true,
220 layout::Abi::ScalarPair(..) => false,
221 layout::Abi::Uninhabited |
222 layout::Abi::Aggregate { .. } => self.is_zst()
226 fn is_llvm_scalar_pair<'a>(&self) -> bool {
228 layout::Abi::ScalarPair(..) => true,
229 layout::Abi::Uninhabited |
230 layout::Abi::Scalar(_) |
231 layout::Abi::Vector { .. } |
232 layout::Abi::Aggregate { .. } => false
236 /// Get the LLVM type corresponding to a Rust type, i.e. `rustc::ty::Ty`.
237 /// The pointee type of the pointer in `PlaceRef` is always this type.
238 /// For sized types, it is also the right LLVM type for an `alloca`
239 /// containing a value of that type, and most immediates (except `bool`).
240 /// Unsized types, however, are represented by a "minimal unit", e.g.
241 /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
242 /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
243 /// If the type is an unsized struct, the regular layout is generated,
244 /// with the inner-most trailing unsized field using the "minimal unit"
245 /// of that field's type - this is useful for taking the address of
246 /// that field and ensuring the struct has the right alignment.
247 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
248 if let layout::Abi::Scalar(ref scalar) = self.abi {
249 // Use a different cache for scalars because pointers to DSTs
250 // can be either fat or thin (data pointers of fat pointers).
251 if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
254 let llty = match self.ty.sty {
255 ty::TyRef(_, ty, _) |
256 ty::TyRawPtr(ty::TypeAndMut { ty, .. }) => {
257 cx.layout_of(ty).llvm_type(cx).ptr_to()
259 ty::TyAdt(def, _) if def.is_box() => {
260 cx.layout_of(self.ty.boxed_ty()).llvm_type(cx).ptr_to()
262 ty::TyFnPtr(sig) => {
263 let sig = cx.tcx.normalize_erasing_late_bound_regions(
264 ty::ParamEnv::reveal_all(),
267 FnType::new(cx, sig, &[]).llvm_type(cx).ptr_to()
269 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO)
271 cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
277 let variant_index = match self.variants {
278 layout::Variants::Single { index } => Some(index),
281 if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
285 debug!("llvm_type({:#?})", self);
287 assert!(!self.ty.has_escaping_regions(), "{:?} has escaping regions", self.ty);
289 // Make sure lifetimes are erased, to avoid generating distinct LLVM
290 // types for Rust types that only differ in the choice of lifetimes.
291 let normal_ty = cx.tcx.erase_regions(&self.ty);
293 let mut defer = None;
294 let llty = if self.ty != normal_ty {
295 let mut layout = cx.layout_of(normal_ty);
296 if let Some(v) = variant_index {
297 layout = layout.for_variant(cx, v);
301 uncached_llvm_type(cx, *self, &mut defer)
303 debug!("--> mapped {:#?} to llty={:?}", self, llty);
305 cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
307 if let Some((llty, layout)) = defer {
308 let (llfields, packed) = struct_llfields(cx, layout);
309 llty.set_struct_body(&llfields, packed)
315 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
316 if let layout::Abi::Scalar(ref scalar) = self.abi {
317 if scalar.is_bool() {
324 fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
325 scalar: &layout::Scalar, offset: Size) -> &'a Type {
327 layout::Int(i, _) => Type::from_integer(cx, i),
328 layout::Float(FloatTy::F32) => Type::f32(cx),
329 layout::Float(FloatTy::F64) => Type::f64(cx),
331 // If we know the alignment, pick something better than i8.
332 let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) {
333 Type::pointee_for_abi_align(cx, pointee.align)
342 fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
343 index: usize, immediate: bool) -> &'a Type {
344 // HACK(eddyb) special-case fat pointers until LLVM removes
345 // pointee types, to avoid bitcasting every `OperandRef::deref`.
349 return self.field(cx, index).llvm_type(cx);
351 ty::TyAdt(def, _) if def.is_box() => {
352 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
353 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
358 let (a, b) = match self.abi {
359 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
360 _ => bug!("TyLayout::scalar_pair_element_llty({:?}): not applicable", self)
362 let scalar = [a, b][index];
364 // Make sure to return the same type `immediate_llvm_type` would when
365 // dealing with an immediate pair. This means that `(bool, bool)` is
366 // effectively represented as `{i8, i8}` in memory and two `i1`s as an
367 // immediate, just like `bool` is typically `i8` in memory and only `i1`
368 // when immediate. We need to load/store `bool` as `i8` to avoid
369 // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
370 if immediate && scalar.is_bool() {
374 let offset = if index == 0 {
377 a.value.size(cx).abi_align(b.value.align(cx))
379 self.scalar_llvm_type_at(cx, scalar, offset)
382 fn llvm_field_index(&self, index: usize) -> u64 {
384 layout::Abi::Scalar(_) |
385 layout::Abi::ScalarPair(..) => {
386 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
391 layout::FieldPlacement::Union(_) => {
392 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
395 layout::FieldPlacement::Array { .. } => {
399 layout::FieldPlacement::Arbitrary { .. } => {
400 1 + (self.fields.memory_index(index) as u64) * 2
405 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
406 -> Option<PointeeInfo> {
407 if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
411 let mut result = None;
413 ty::TyRawPtr(mt) if offset.bytes() == 0 => {
414 let (size, align) = cx.size_and_align_of(mt.ty);
415 result = Some(PointeeInfo {
422 ty::TyRef(_, ty, mt) if offset.bytes() == 0 => {
423 let (size, align) = cx.size_and_align_of(ty);
425 let kind = match mt {
426 hir::MutImmutable => if cx.type_is_freeze(ty) {
432 // Only emit noalias annotations for LLVM >= 6 or in panic=abort
433 // mode, as prior versions had many bugs in conjunction with
434 // unwinding. See also issue #31681.
435 let mutable_noalias = cx.tcx.sess.opts.debugging_opts.mutable_noalias
436 .unwrap_or(unsafe { llvm::LLVMRustVersionMajor() >= 6 }
437 || cx.tcx.sess.panic_strategy() == PanicStrategy::Abort);
439 PointerKind::UniqueBorrowed
446 result = Some(PointeeInfo {
454 let mut data_variant = match self.variants {
455 layout::Variants::NicheFilling { dataful_variant, .. } => {
456 // Only the niche itself is always initialized,
457 // so only check for a pointer at its offset.
459 // If the niche is a pointer, it's either valid
460 // (according to its type), or null (which the
461 // niche field's scalar validity range encodes).
462 // This allows using `dereferenceable_or_null`
463 // for e.g. `Option<&T>`, and this will continue
464 // to work as long as we don't start using more
465 // niches than just null (e.g. the first page
466 // of the address space, or unaligned pointers).
467 if self.fields.offset(0) == offset {
468 Some(self.for_variant(cx, dataful_variant))
476 if let Some(variant) = data_variant {
477 // We're not interested in any unions.
478 if let layout::FieldPlacement::Union(_) = variant.fields {
483 if let Some(variant) = data_variant {
484 let ptr_end = offset + layout::Pointer.size(cx);
485 for i in 0..variant.fields.count() {
486 let field_start = variant.fields.offset(i);
487 if field_start <= offset {
488 let field = variant.field(cx, i);
489 if ptr_end <= field_start + field.size {
490 // We found the right field, look inside it.
491 result = field.pointee_info_at(cx, offset - field_start);
498 // FIXME(eddyb) This should be for `ptr::Unique<T>`, not `Box<T>`.
499 if let Some(ref mut pointee) = result {
500 if let ty::TyAdt(def, _) = self.ty.sty {
501 if def.is_box() && offset.bytes() == 0 {
502 pointee.safe = Some(PointerKind::UniqueOwned);
509 cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);