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::*;
12 fn uncached_llvm_type<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
13 layout: TyLayout<'tcx>,
14 defer: &mut Option<(&'a Type, TyLayout<'tcx>)>)
17 layout::Abi::Scalar(_) => bug!("handled elsewhere"),
18 layout::Abi::Vector { ref element, count } => {
19 // LLVM has a separate type for 64-bit SIMD vectors on X86 called
20 // `x86_mmx` which is needed for some SIMD operations. As a bit of a
21 // hack (all SIMD definitions are super unstable anyway) we
22 // recognize any one-element SIMD vector as "this should be an
23 // x86_mmx" type. In general there shouldn't be a need for other
24 // one-element SIMD vectors, so it's assumed this won't clash with
26 let use_x86_mmx = count == 1 && layout.size.bits() == 64 &&
27 (cx.sess().target.target.arch == "x86" ||
28 cx.sess().target.target.arch == "x86_64");
30 return cx.type_x86_mmx()
32 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
33 return cx.type_vector(element, count);
36 layout::Abi::ScalarPair(..) => {
37 return cx.type_struct( &[
38 layout.scalar_pair_element_llvm_type(cx, 0, false),
39 layout.scalar_pair_element_llvm_type(cx, 1, false),
42 layout::Abi::Uninhabited |
43 layout::Abi::Aggregate { .. } => {}
46 let name = match layout.ty.kind {
50 // FIXME(eddyb) producing readable type names for trait objects can result
51 // in problematically distinct types due to HRTB and subtyping (see #47638).
55 let mut name = String::with_capacity(32);
56 let printer = DefPathBasedNames::new(cx.tcx, true, true);
57 printer.push_type_name(layout.ty, &mut name, false);
58 if let (&ty::Adt(def, _), &layout::Variants::Single { index })
59 = (&layout.ty.kind, &layout.variants)
61 if def.is_enum() && !def.variants.is_empty() {
62 write!(&mut name, "::{}", def.variants[index].ident).unwrap();
65 if let (&ty::Generator(_, substs, _), &layout::Variants::Single { index })
66 = (&layout.ty.kind, &layout.variants)
68 write!(&mut name, "::{}", substs.as_generator().variant_name(index)).unwrap();
76 layout::FieldPlacement::Union(_) => {
77 let fill = cx.type_padding_filler(layout.size, layout.align.abi);
81 cx.type_struct(&[fill], packed)
84 let llty = cx.type_named_struct(name);
85 cx.set_struct_body(llty, &[fill], packed);
90 layout::FieldPlacement::Array { count, .. } => {
91 cx.type_array(layout.field(cx, 0).llvm_type(cx), count)
93 layout::FieldPlacement::Arbitrary { .. } => {
96 let (llfields, packed) = struct_llfields(cx, layout);
97 cx.type_struct( &llfields, packed)
100 let llty = cx.type_named_struct( name);
101 *defer = Some((llty, layout));
109 fn struct_llfields<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
110 layout: TyLayout<'tcx>)
111 -> (Vec<&'a Type>, bool) {
112 debug!("struct_llfields: {:#?}", layout);
113 let field_count = layout.fields.count();
115 let mut packed = false;
116 let mut offset = Size::ZERO;
117 let mut prev_effective_align = layout.align.abi;
118 let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
119 for i in layout.fields.index_by_increasing_offset() {
120 let target_offset = layout.fields.offset(i as usize);
121 let field = layout.field(cx, i);
122 let effective_field_align = layout.align.abi
123 .min(field.align.abi)
124 .restrict_for_offset(target_offset);
125 packed |= effective_field_align < field.align.abi;
127 debug!("struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
128 effective_field_align: {}",
129 i, field, offset, target_offset, effective_field_align.bytes());
130 assert!(target_offset >= offset);
131 let padding = target_offset - offset;
132 let padding_align = prev_effective_align.min(effective_field_align);
133 assert_eq!(offset.align_to(padding_align) + padding, target_offset);
134 result.push(cx.type_padding_filler( padding, padding_align));
135 debug!(" padding before: {:?}", padding);
137 result.push(field.llvm_type(cx));
138 offset = target_offset + field.size;
139 prev_effective_align = effective_field_align;
141 if !layout.is_unsized() && field_count > 0 {
142 if offset > layout.size {
143 bug!("layout: {:#?} stride: {:?} offset: {:?}",
144 layout, layout.size, offset);
146 let padding = layout.size - offset;
147 let padding_align = prev_effective_align;
148 assert_eq!(offset.align_to(padding_align) + padding, layout.size);
149 debug!("struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
150 padding, offset, layout.size);
151 result.push(cx.type_padding_filler(padding, padding_align));
152 assert_eq!(result.len(), 1 + field_count * 2);
154 debug!("struct_llfields: offset: {:?} stride: {:?}",
155 offset, layout.size);
161 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
162 pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
163 self.layout_of(ty).align.abi
166 pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
167 self.layout_of(ty).size
170 pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
171 let layout = self.layout_of(ty);
172 (layout.size, layout.align.abi)
176 pub trait LayoutLlvmExt<'tcx> {
177 fn is_llvm_immediate(&self) -> bool;
178 fn is_llvm_scalar_pair(&self) -> bool;
179 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
180 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
181 fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
182 scalar: &layout::Scalar, offset: Size) -> &'a Type;
183 fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
184 index: usize, immediate: bool) -> &'a Type;
185 fn llvm_field_index(&self, index: usize) -> u64;
186 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
187 -> Option<PointeeInfo>;
190 impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> {
191 fn is_llvm_immediate(&self) -> bool {
193 layout::Abi::Scalar(_) |
194 layout::Abi::Vector { .. } => true,
195 layout::Abi::ScalarPair(..) => false,
196 layout::Abi::Uninhabited |
197 layout::Abi::Aggregate { .. } => self.is_zst()
201 fn is_llvm_scalar_pair(&self) -> bool {
203 layout::Abi::ScalarPair(..) => true,
204 layout::Abi::Uninhabited |
205 layout::Abi::Scalar(_) |
206 layout::Abi::Vector { .. } |
207 layout::Abi::Aggregate { .. } => false
211 /// Gets the LLVM type corresponding to a Rust type, i.e., `rustc::ty::Ty`.
212 /// The pointee type of the pointer in `PlaceRef` is always this type.
213 /// For sized types, it is also the right LLVM type for an `alloca`
214 /// containing a value of that type, and most immediates (except `bool`).
215 /// Unsized types, however, are represented by a "minimal unit", e.g.
216 /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
217 /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
218 /// If the type is an unsized struct, the regular layout is generated,
219 /// with the inner-most trailing unsized field using the "minimal unit"
220 /// of that field's type - this is useful for taking the address of
221 /// that field and ensuring the struct has the right alignment.
222 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
223 if let layout::Abi::Scalar(ref scalar) = self.abi {
224 // Use a different cache for scalars because pointers to DSTs
225 // can be either fat or thin (data pointers of fat pointers).
226 if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
229 let llty = match self.ty.kind {
231 ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
232 cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
234 ty::Adt(def, _) if def.is_box() => {
235 cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
238 let sig = cx.tcx.normalize_erasing_late_bound_regions(
239 ty::ParamEnv::reveal_all(),
242 cx.fn_ptr_backend_type(&FnAbi::new(cx, sig, &[]))
244 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO)
246 cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
252 let variant_index = match self.variants {
253 layout::Variants::Single { index } => Some(index),
256 if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
260 debug!("llvm_type({:#?})", self);
262 assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
264 // Make sure lifetimes are erased, to avoid generating distinct LLVM
265 // types for Rust types that only differ in the choice of lifetimes.
266 let normal_ty = cx.tcx.erase_regions(&self.ty);
268 let mut defer = None;
269 let llty = if self.ty != normal_ty {
270 let mut layout = cx.layout_of(normal_ty);
271 if let Some(v) = variant_index {
272 layout = layout.for_variant(cx, v);
276 uncached_llvm_type(cx, *self, &mut defer)
278 debug!("--> mapped {:#?} to llty={:?}", self, llty);
280 cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
282 if let Some((llty, layout)) = defer {
283 let (llfields, packed) = struct_llfields(cx, layout);
284 cx.set_struct_body(llty, &llfields, packed)
290 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
291 if let layout::Abi::Scalar(ref scalar) = self.abi {
292 if scalar.is_bool() {
299 fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
300 scalar: &layout::Scalar, offset: Size) -> &'a Type {
302 layout::Int(i, _) => cx.type_from_integer( i),
303 layout::F32 => cx.type_f32(),
304 layout::F64 => cx.type_f64(),
306 // If we know the alignment, pick something better than i8.
307 let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) {
308 cx.type_pointee_for_align(pointee.align)
312 cx.type_ptr_to(pointee)
317 fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
318 index: usize, immediate: bool) -> &'a Type {
319 // HACK(eddyb) special-case fat pointers until LLVM removes
320 // pointee types, to avoid bitcasting every `OperandRef::deref`.
324 return self.field(cx, index).llvm_type(cx);
326 ty::Adt(def, _) if def.is_box() => {
327 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
328 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
333 let (a, b) = match self.abi {
334 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
335 _ => bug!("TyLayout::scalar_pair_element_llty({:?}): not applicable", self)
337 let scalar = [a, b][index];
339 // Make sure to return the same type `immediate_llvm_type` would when
340 // dealing with an immediate pair. This means that `(bool, bool)` is
341 // effectively represented as `{i8, i8}` in memory and two `i1`s as an
342 // immediate, just like `bool` is typically `i8` in memory and only `i1`
343 // when immediate. We need to load/store `bool` as `i8` to avoid
344 // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
345 if immediate && scalar.is_bool() {
349 let offset = if index == 0 {
352 a.value.size(cx).align_to(b.value.align(cx).abi)
354 self.scalar_llvm_type_at(cx, scalar, offset)
357 fn llvm_field_index(&self, index: usize) -> u64 {
359 layout::Abi::Scalar(_) |
360 layout::Abi::ScalarPair(..) => {
361 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
366 layout::FieldPlacement::Union(_) => {
367 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
370 layout::FieldPlacement::Array { .. } => {
374 layout::FieldPlacement::Arbitrary { .. } => {
375 1 + (self.fields.memory_index(index) as u64) * 2
380 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
381 -> Option<PointeeInfo> {
382 if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
386 let result = Ty::pointee_info_at(*self, cx, offset);
388 cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);