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