1 use crate::abi::{FnAbi};
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::*;
14 fn uncached_llvm_type<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
15 layout: TyLayout<'tcx>,
16 defer: &mut Option<(&'a Type, TyLayout<'tcx>)>)
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
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");
32 return cx.type_x86_mmx()
34 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
35 return cx.type_vector(element, count);
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),
44 layout::Abi::Uninhabited |
45 layout::Abi::Aggregate { .. } => {}
48 let name = match layout.ty.kind {
52 // FIXME(eddyb) producing readable type names for trait objects can result
53 // in problematically distinct types due to HRTB and subtyping (see #47638).
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)
63 if def.is_enum() && !def.variants.is_empty() {
64 write!(&mut name, "::{}", def.variants[index].ident).unwrap();
67 if let (&ty::Generator(_, substs, _), &layout::Variants::Single { index })
68 = (&layout.ty.kind, &layout.variants)
70 write!(&mut name, "::{}", substs.as_generator().variant_name(index)).unwrap();
78 layout::FieldPlacement::Union(_) => {
79 let fill = cx.type_padding_filler(layout.size, layout.align.abi);
83 cx.type_struct(&[fill], packed)
86 let llty = cx.type_named_struct(name);
87 cx.set_struct_body(llty, &[fill], packed);
92 layout::FieldPlacement::Array { count, .. } => {
93 cx.type_array(layout.field(cx, 0).llvm_type(cx), count)
95 layout::FieldPlacement::Arbitrary { .. } => {
98 let (llfields, packed) = struct_llfields(cx, layout);
99 cx.type_struct( &llfields, packed)
102 let llty = cx.type_named_struct( name);
103 *defer = Some((llty, layout));
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();
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;
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);
139 result.push(field.llvm_type(cx));
140 offset = target_offset + field.size;
141 prev_effective_align = effective_field_align;
143 if !layout.is_unsized() && field_count > 0 {
144 if offset > layout.size {
145 bug!("layout: {:#?} stride: {:?} offset: {:?}",
146 layout, layout.size, offset);
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);
156 debug!("struct_llfields: offset: {:?} stride: {:?}",
157 offset, layout.size);
163 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
164 pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
165 self.layout_of(ty).align.abi
168 pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
169 self.layout_of(ty).size
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)
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>;
192 impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> {
193 fn is_llvm_immediate(&self) -> bool {
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()
203 fn is_llvm_scalar_pair(&self) -> bool {
205 layout::Abi::ScalarPair(..) => true,
206 layout::Abi::Uninhabited |
207 layout::Abi::Scalar(_) |
208 layout::Abi::Vector { .. } |
209 layout::Abi::Aggregate { .. } => false
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) {
231 let llty = match self.ty.kind {
233 ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
234 cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
236 ty::Adt(def, _) if def.is_box() => {
237 cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
240 cx.fn_ptr_backend_type(&FnAbi::of_fn_ptr(cx, sig, &[]))
242 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO)
244 cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
250 let variant_index = match self.variants {
251 layout::Variants::Single { index } => Some(index),
254 if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
258 debug!("llvm_type({:#?})", self);
260 assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
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);
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);
274 uncached_llvm_type(cx, *self, &mut defer)
276 debug!("--> mapped {:#?} to llty={:?}", self, llty);
278 cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
280 if let Some((llty, layout)) = defer {
281 let (llfields, packed) = struct_llfields(cx, layout);
282 cx.set_struct_body(llty, &llfields, packed)
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() {
297 fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
298 scalar: &layout::Scalar, offset: Size) -> &'a Type {
300 layout::Int(i, _) => cx.type_from_integer( i),
301 layout::F32 => cx.type_f32(),
302 layout::F64 => cx.type_f64(),
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)
310 cx.type_ptr_to(pointee)
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`.
322 return self.field(cx, index).llvm_type(cx);
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);
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)
335 let scalar = [a, b][index];
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() {
347 let offset = if index == 0 {
350 a.value.size(cx).align_to(b.value.align(cx).abi)
352 self.scalar_llvm_type_at(cx, scalar, offset)
355 fn llvm_field_index(&self, index: usize) -> u64 {
357 layout::Abi::Scalar(_) |
358 layout::Abi::ScalarPair(..) => {
359 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
364 layout::FieldPlacement::Union(_) => {
365 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
368 layout::FieldPlacement::Array { .. } => {
372 layout::FieldPlacement::Arbitrary { .. } => {
373 1 + (self.fields.memory_index(index) as u64) * 2
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)) {
384 let result = Ty::pointee_info_at(*self, cx, offset);
386 cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);