]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/type_of.rs
Rollup merge of #101738 - dpaoliello:linkname, r=petrochenkov
[rust.git] / compiler / rustc_codegen_llvm / src / type_of.rs
1 use crate::common::*;
2 use crate::context::TypeLowering;
3 use crate::llvm_util::get_version;
4 use crate::type_::Type;
5 use rustc_codegen_ssa::traits::*;
6 use rustc_middle::bug;
7 use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout};
8 use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
9 use rustc_middle::ty::{self, Ty, TypeVisitable};
10 use rustc_target::abi::{Abi, AddressSpace, Align, FieldsShape};
11 use rustc_target::abi::{Int, Pointer, F32, F64};
12 use rustc_target::abi::{PointeeInfo, Scalar, Size, TyAbiInterface, Variants};
13 use smallvec::{smallvec, SmallVec};
14
15 use std::fmt::Write;
16
17 fn uncached_llvm_type<'a, 'tcx>(
18     cx: &CodegenCx<'a, 'tcx>,
19     layout: TyAndLayout<'tcx>,
20     defer: &mut Option<(&'a Type, TyAndLayout<'tcx>)>,
21     field_remapping: &mut Option<SmallVec<[u32; 4]>>,
22 ) -> &'a Type {
23     match layout.abi {
24         Abi::Scalar(_) => bug!("handled elsewhere"),
25         Abi::Vector { element, count } => {
26             let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
27             return cx.type_vector(element, count);
28         }
29         Abi::ScalarPair(..) => {
30             return cx.type_struct(
31                 &[
32                     layout.scalar_pair_element_llvm_type(cx, 0, false),
33                     layout.scalar_pair_element_llvm_type(cx, 1, false),
34                 ],
35                 false,
36             );
37         }
38         Abi::Uninhabited | Abi::Aggregate { .. } => {}
39     }
40
41     let name = match layout.ty.kind() {
42         // FIXME(eddyb) producing readable type names for trait objects can result
43         // in problematically distinct types due to HRTB and subtyping (see #47638).
44         // ty::Dynamic(..) |
45         ty::Adt(..) | ty::Closure(..) | ty::Foreign(..) | ty::Generator(..) | ty::Str
46             // For performance reasons we use names only when emitting LLVM IR. Unless we are on
47             // LLVM < 14, where the use of unnamed types resulted in various issues, e.g., #76213,
48             // #79564, and #79246.
49             if get_version() < (14, 0, 0) || !cx.sess().fewer_names() =>
50         {
51             let mut name = with_no_visible_paths!(with_no_trimmed_paths!(layout.ty.to_string()));
52             if let (&ty::Adt(def, _), &Variants::Single { index }) =
53                 (layout.ty.kind(), &layout.variants)
54             {
55                 if def.is_enum() && !def.variants().is_empty() {
56                     write!(&mut name, "::{}", def.variant(index).name).unwrap();
57                 }
58             }
59             if let (&ty::Generator(_, _, _), &Variants::Single { index }) =
60                 (layout.ty.kind(), &layout.variants)
61             {
62                 write!(&mut name, "::{}", ty::GeneratorSubsts::variant_name(index)).unwrap();
63             }
64             Some(name)
65         }
66         // Use identified structure types for ADT. Due to pointee types in LLVM IR their definition
67         // might be recursive. Other cases are non-recursive and we can use literal structure types.
68         ty::Adt(..) => Some(String::new()),
69         _ => None,
70     };
71
72     match layout.fields {
73         FieldsShape::Primitive | FieldsShape::Union(_) => {
74             let fill = cx.type_padding_filler(layout.size, layout.align.abi);
75             let packed = false;
76             match name {
77                 None => cx.type_struct(&[fill], packed),
78                 Some(ref name) => {
79                     let llty = cx.type_named_struct(name);
80                     cx.set_struct_body(llty, &[fill], packed);
81                     llty
82                 }
83             }
84         }
85         FieldsShape::Array { count, .. } => cx.type_array(layout.field(cx, 0).llvm_type(cx), count),
86         FieldsShape::Arbitrary { .. } => match name {
87             None => {
88                 let (llfields, packed, new_field_remapping) = struct_llfields(cx, layout);
89                 *field_remapping = new_field_remapping;
90                 cx.type_struct(&llfields, packed)
91             }
92             Some(ref name) => {
93                 let llty = cx.type_named_struct(name);
94                 *defer = Some((llty, layout));
95                 llty
96             }
97         },
98     }
99 }
100
101 fn struct_llfields<'a, 'tcx>(
102     cx: &CodegenCx<'a, 'tcx>,
103     layout: TyAndLayout<'tcx>,
104 ) -> (Vec<&'a Type>, bool, Option<SmallVec<[u32; 4]>>) {
105     debug!("struct_llfields: {:#?}", layout);
106     let field_count = layout.fields.count();
107
108     let mut packed = false;
109     let mut offset = Size::ZERO;
110     let mut prev_effective_align = layout.align.abi;
111     let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
112     let mut field_remapping = smallvec![0; field_count];
113     for i in layout.fields.index_by_increasing_offset() {
114         let target_offset = layout.fields.offset(i as usize);
115         let field = layout.field(cx, i);
116         let effective_field_align =
117             layout.align.abi.min(field.align.abi).restrict_for_offset(target_offset);
118         packed |= effective_field_align < field.align.abi;
119
120         debug!(
121             "struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
122                 effective_field_align: {}",
123             i,
124             field,
125             offset,
126             target_offset,
127             effective_field_align.bytes()
128         );
129         assert!(target_offset >= offset);
130         let padding = target_offset - offset;
131         if padding != Size::ZERO {
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);
136         }
137         field_remapping[i] = result.len() as u32;
138         result.push(field.llvm_type(cx));
139         offset = target_offset + field.size;
140         prev_effective_align = effective_field_align;
141     }
142     let padding_used = result.len() > field_count;
143     if !layout.is_unsized() && field_count > 0 {
144         if offset > layout.size {
145             bug!("layout: {:#?} stride: {:?} offset: {:?}", layout, layout.size, offset);
146         }
147         let padding = layout.size - offset;
148         if padding != Size::ZERO {
149             let padding_align = prev_effective_align;
150             assert_eq!(offset.align_to(padding_align) + padding, layout.size);
151             debug!(
152                 "struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
153                 padding, offset, layout.size
154             );
155             result.push(cx.type_padding_filler(padding, padding_align));
156         }
157     } else {
158         debug!("struct_llfields: offset: {:?} stride: {:?}", offset, layout.size);
159     }
160     let field_remapping = if padding_used { Some(field_remapping) } else { None };
161     (result, packed, field_remapping)
162 }
163
164 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
165     pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
166         self.layout_of(ty).align.abi
167     }
168
169     pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
170         self.layout_of(ty).size
171     }
172
173     pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
174         let layout = self.layout_of(ty);
175         (layout.size, layout.align.abi)
176     }
177 }
178
179 pub trait LayoutLlvmExt<'tcx> {
180     fn is_llvm_immediate(&self) -> bool;
181     fn is_llvm_scalar_pair(&self) -> bool;
182     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
183     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
184     fn scalar_llvm_type_at<'a>(
185         &self,
186         cx: &CodegenCx<'a, 'tcx>,
187         scalar: Scalar,
188         offset: Size,
189     ) -> &'a Type;
190     fn scalar_pair_element_llvm_type<'a>(
191         &self,
192         cx: &CodegenCx<'a, 'tcx>,
193         index: usize,
194         immediate: bool,
195     ) -> &'a Type;
196     fn llvm_field_index<'a>(&self, cx: &CodegenCx<'a, 'tcx>, index: usize) -> u64;
197     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo>;
198 }
199
200 impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> {
201     fn is_llvm_immediate(&self) -> bool {
202         match self.abi {
203             Abi::Scalar(_) | Abi::Vector { .. } => true,
204             Abi::ScalarPair(..) => false,
205             Abi::Uninhabited | Abi::Aggregate { .. } => self.is_zst(),
206         }
207     }
208
209     fn is_llvm_scalar_pair(&self) -> bool {
210         match self.abi {
211             Abi::ScalarPair(..) => true,
212             Abi::Uninhabited | Abi::Scalar(_) | Abi::Vector { .. } | Abi::Aggregate { .. } => false,
213         }
214     }
215
216     /// Gets the LLVM type corresponding to a Rust type, i.e., `rustc_middle::ty::Ty`.
217     /// The pointee type of the pointer in `PlaceRef` is always this type.
218     /// For sized types, it is also the right LLVM type for an `alloca`
219     /// containing a value of that type, and most immediates (except `bool`).
220     /// Unsized types, however, are represented by a "minimal unit", e.g.
221     /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
222     /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
223     /// If the type is an unsized struct, the regular layout is generated,
224     /// with the inner-most trailing unsized field using the "minimal unit"
225     /// of that field's type - this is useful for taking the address of
226     /// that field and ensuring the struct has the right alignment.
227     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
228         if let Abi::Scalar(scalar) = self.abi {
229             // Use a different cache for scalars because pointers to DSTs
230             // can be either fat or thin (data pointers of fat pointers).
231             if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
232                 return llty;
233             }
234             let llty = match *self.ty.kind() {
235                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
236                     cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
237                 }
238                 ty::Adt(def, _) if def.is_box() => {
239                     cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
240                 }
241                 ty::FnPtr(sig) => {
242                     cx.fn_ptr_backend_type(cx.fn_abi_of_fn_ptr(sig, ty::List::empty()))
243                 }
244                 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO),
245             };
246             cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
247             return llty;
248         }
249
250         // Check the cache.
251         let variant_index = match self.variants {
252             Variants::Single { index } => Some(index),
253             _ => None,
254         };
255         if let Some(llty) = cx.type_lowering.borrow().get(&(self.ty, variant_index)) {
256             return llty.lltype;
257         }
258
259         debug!("llvm_type({:#?})", self);
260
261         assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
262
263         // Make sure lifetimes are erased, to avoid generating distinct LLVM
264         // types for Rust types that only differ in the choice of lifetimes.
265         let normal_ty = cx.tcx.erase_regions(self.ty);
266
267         let mut defer = None;
268         let mut field_remapping = 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);
273             }
274             layout.llvm_type(cx)
275         } else {
276             uncached_llvm_type(cx, *self, &mut defer, &mut field_remapping)
277         };
278         debug!("--> mapped {:#?} to llty={:?}", self, llty);
279
280         cx.type_lowering
281             .borrow_mut()
282             .insert((self.ty, variant_index), TypeLowering { lltype: llty, field_remapping });
283
284         if let Some((llty, layout)) = defer {
285             let (llfields, packed, new_field_remapping) = struct_llfields(cx, layout);
286             cx.set_struct_body(llty, &llfields, packed);
287             cx.type_lowering
288                 .borrow_mut()
289                 .get_mut(&(self.ty, variant_index))
290                 .unwrap()
291                 .field_remapping = new_field_remapping;
292         }
293         llty
294     }
295
296     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
297         if let Abi::Scalar(scalar) = self.abi {
298             if scalar.is_bool() {
299                 return cx.type_i1();
300             }
301         }
302         self.llvm_type(cx)
303     }
304
305     fn scalar_llvm_type_at<'a>(
306         &self,
307         cx: &CodegenCx<'a, 'tcx>,
308         scalar: Scalar,
309         offset: Size,
310     ) -> &'a Type {
311         match scalar.primitive() {
312             Int(i, _) => cx.type_from_integer(i),
313             F32 => cx.type_f32(),
314             F64 => cx.type_f64(),
315             Pointer => {
316                 // If we know the alignment, pick something better than i8.
317                 let (pointee, address_space) =
318                     if let Some(pointee) = self.pointee_info_at(cx, offset) {
319                         (cx.type_pointee_for_align(pointee.align), pointee.address_space)
320                     } else {
321                         (cx.type_i8(), AddressSpace::DATA)
322                     };
323                 cx.type_ptr_to_ext(pointee, address_space)
324             }
325         }
326     }
327
328     fn scalar_pair_element_llvm_type<'a>(
329         &self,
330         cx: &CodegenCx<'a, 'tcx>,
331         index: usize,
332         immediate: bool,
333     ) -> &'a Type {
334         // HACK(eddyb) special-case fat pointers until LLVM removes
335         // pointee types, to avoid bitcasting every `OperandRef::deref`.
336         match self.ty.kind() {
337             ty::Ref(..) | ty::RawPtr(_) => {
338                 return self.field(cx, index).llvm_type(cx);
339             }
340             // only wide pointer boxes are handled as pointers
341             // thin pointer boxes with scalar allocators are handled by the general logic below
342             ty::Adt(def, substs) if def.is_box() && cx.layout_of(substs.type_at(1)).is_zst() => {
343                 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
344                 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
345             }
346             _ => {}
347         }
348
349         let Abi::ScalarPair(a, b) = self.abi else {
350             bug!("TyAndLayout::scalar_pair_element_llty({:?}): not applicable", self);
351         };
352         let scalar = [a, b][index];
353
354         // Make sure to return the same type `immediate_llvm_type` would when
355         // dealing with an immediate pair.  This means that `(bool, bool)` is
356         // effectively represented as `{i8, i8}` in memory and two `i1`s as an
357         // immediate, just like `bool` is typically `i8` in memory and only `i1`
358         // when immediate.  We need to load/store `bool` as `i8` to avoid
359         // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
360         if immediate && scalar.is_bool() {
361             return cx.type_i1();
362         }
363
364         let offset = if index == 0 { Size::ZERO } else { a.size(cx).align_to(b.align(cx).abi) };
365         self.scalar_llvm_type_at(cx, scalar, offset)
366     }
367
368     fn llvm_field_index<'a>(&self, cx: &CodegenCx<'a, 'tcx>, index: usize) -> u64 {
369         match self.abi {
370             Abi::Scalar(_) | Abi::ScalarPair(..) => {
371                 bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self)
372             }
373             _ => {}
374         }
375         match self.fields {
376             FieldsShape::Primitive | FieldsShape::Union(_) => {
377                 bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self)
378             }
379
380             FieldsShape::Array { .. } => index as u64,
381
382             FieldsShape::Arbitrary { .. } => {
383                 let variant_index = match self.variants {
384                     Variants::Single { index } => Some(index),
385                     _ => None,
386                 };
387
388                 // Look up llvm field if indexes do not match memory order due to padding. If
389                 // `field_remapping` is `None` no padding was used and the llvm field index
390                 // matches the memory index.
391                 match cx.type_lowering.borrow().get(&(self.ty, variant_index)) {
392                     Some(TypeLowering { field_remapping: Some(ref remap), .. }) => {
393                         remap[index] as u64
394                     }
395                     Some(_) => self.fields.memory_index(index) as u64,
396                     None => {
397                         bug!("TyAndLayout::llvm_field_index({:?}): type info not found", self)
398                     }
399                 }
400             }
401         }
402     }
403
404     // FIXME(eddyb) this having the same name as `TyAndLayout::pointee_info_at`
405     // (the inherent method, which is lacking this caching logic) can result in
406     // the uncached version being called - not wrong, but potentially inefficient.
407     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo> {
408         if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
409             return pointee;
410         }
411
412         let result = Ty::ty_and_layout_pointee_info_at(*self, cx, offset);
413
414         cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);
415         result
416     }
417 }