]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/place.rs
Auto merge of #101173 - jyn514:simplify-macro-arguments, r=cjgillot
[rust.git] / compiler / rustc_codegen_ssa / src / mir / place.rs
1 use super::operand::OperandValue;
2 use super::{FunctionCx, LocalRef};
3
4 use crate::common::IntPredicate;
5 use crate::glue;
6 use crate::traits::*;
7
8 use rustc_middle::mir;
9 use rustc_middle::mir::tcx::PlaceTy;
10 use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout};
11 use rustc_middle::ty::{self, Ty};
12 use rustc_target::abi::{Abi, Align, FieldsShape, Int, TagEncoding};
13 use rustc_target::abi::{VariantIdx, Variants};
14
15 #[derive(Copy, Clone, Debug)]
16 pub struct PlaceRef<'tcx, V> {
17     /// A pointer to the contents of the place.
18     pub llval: V,
19
20     /// This place's extra data if it is unsized, or `None` if null.
21     pub llextra: Option<V>,
22
23     /// The monomorphized type of this place, including variant information.
24     pub layout: TyAndLayout<'tcx>,
25
26     /// The alignment we know for this place.
27     pub align: Align,
28 }
29
30 impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> {
31     pub fn new_sized(llval: V, layout: TyAndLayout<'tcx>) -> PlaceRef<'tcx, V> {
32         assert!(!layout.is_unsized());
33         PlaceRef { llval, llextra: None, layout, align: layout.align.abi }
34     }
35
36     pub fn new_sized_aligned(
37         llval: V,
38         layout: TyAndLayout<'tcx>,
39         align: Align,
40     ) -> PlaceRef<'tcx, V> {
41         assert!(!layout.is_unsized());
42         PlaceRef { llval, llextra: None, layout, align }
43     }
44
45     // FIXME(eddyb) pass something else for the name so no work is done
46     // unless LLVM IR names are turned on (e.g. for `--emit=llvm-ir`).
47     pub fn alloca<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
48         bx: &mut Bx,
49         layout: TyAndLayout<'tcx>,
50     ) -> Self {
51         assert!(!layout.is_unsized(), "tried to statically allocate unsized place");
52         let tmp = bx.alloca(bx.cx().backend_type(layout), layout.align.abi);
53         Self::new_sized(tmp, layout)
54     }
55
56     /// Returns a place for an indirect reference to an unsized place.
57     // FIXME(eddyb) pass something else for the name so no work is done
58     // unless LLVM IR names are turned on (e.g. for `--emit=llvm-ir`).
59     pub fn alloca_unsized_indirect<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
60         bx: &mut Bx,
61         layout: TyAndLayout<'tcx>,
62     ) -> Self {
63         assert!(layout.is_unsized(), "tried to allocate indirect place for sized values");
64         let ptr_ty = bx.cx().tcx().mk_mut_ptr(layout.ty);
65         let ptr_layout = bx.cx().layout_of(ptr_ty);
66         Self::alloca(bx, ptr_layout)
67     }
68
69     pub fn len<Cx: ConstMethods<'tcx, Value = V>>(&self, cx: &Cx) -> V {
70         if let FieldsShape::Array { count, .. } = self.layout.fields {
71             if self.layout.is_unsized() {
72                 assert_eq!(count, 0);
73                 self.llextra.unwrap()
74             } else {
75                 cx.const_usize(count)
76             }
77         } else {
78             bug!("unexpected layout `{:#?}` in PlaceRef::len", self.layout)
79         }
80     }
81 }
82
83 impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> {
84     /// Access a field, at a point when the value's case is known.
85     pub fn project_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
86         self,
87         bx: &mut Bx,
88         ix: usize,
89     ) -> Self {
90         let field = self.layout.field(bx.cx(), ix);
91         let offset = self.layout.fields.offset(ix);
92         let effective_field_align = self.align.restrict_for_offset(offset);
93
94         let mut simple = || {
95             let llval = match self.layout.abi {
96                 _ if offset.bytes() == 0 => {
97                     // Unions and newtypes only use an offset of 0.
98                     // Also handles the first field of Scalar, ScalarPair, and Vector layouts.
99                     self.llval
100                 }
101                 Abi::ScalarPair(a, b)
102                     if offset == a.size(bx.cx()).align_to(b.align(bx.cx()).abi) =>
103                 {
104                     // Offset matches second field.
105                     let ty = bx.backend_type(self.layout);
106                     bx.struct_gep(ty, self.llval, 1)
107                 }
108                 Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } if field.is_zst() => {
109                     // ZST fields are not included in Scalar, ScalarPair, and Vector layouts, so manually offset the pointer.
110                     let byte_ptr = bx.pointercast(self.llval, bx.cx().type_i8p());
111                     bx.gep(bx.cx().type_i8(), byte_ptr, &[bx.const_usize(offset.bytes())])
112                 }
113                 Abi::Scalar(_) | Abi::ScalarPair(..) => {
114                     // All fields of Scalar and ScalarPair layouts must have been handled by this point.
115                     // Vector layouts have additional fields for each element of the vector, so don't panic in that case.
116                     bug!(
117                         "offset of non-ZST field `{:?}` does not match layout `{:#?}`",
118                         field,
119                         self.layout
120                     );
121                 }
122                 _ => {
123                     let ty = bx.backend_type(self.layout);
124                     bx.struct_gep(ty, self.llval, bx.cx().backend_field_index(self.layout, ix))
125                 }
126             };
127             PlaceRef {
128                 // HACK(eddyb): have to bitcast pointers until LLVM removes pointee types.
129                 llval: bx.pointercast(llval, bx.cx().type_ptr_to(bx.cx().backend_type(field))),
130                 llextra: if bx.cx().type_has_metadata(field.ty) { self.llextra } else { None },
131                 layout: field,
132                 align: effective_field_align,
133             }
134         };
135
136         // Simple cases, which don't need DST adjustment:
137         //   * no metadata available - just log the case
138         //   * known alignment - sized types, `[T]`, `str` or a foreign type
139         //   * packed struct - there is no alignment padding
140         match field.ty.kind() {
141             _ if self.llextra.is_none() => {
142                 debug!(
143                     "unsized field `{}`, of `{:?}` has no metadata for adjustment",
144                     ix, self.llval
145                 );
146                 return simple();
147             }
148             _ if !field.is_unsized() => return simple(),
149             ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(),
150             ty::Adt(def, _) => {
151                 if def.repr().packed() {
152                     // FIXME(eddyb) generalize the adjustment when we
153                     // start supporting packing to larger alignments.
154                     assert_eq!(self.layout.align.abi.bytes(), 1);
155                     return simple();
156                 }
157             }
158             _ => {}
159         }
160
161         // We need to get the pointer manually now.
162         // We do this by casting to a `*i8`, then offsetting it by the appropriate amount.
163         // We do this instead of, say, simply adjusting the pointer from the result of a GEP
164         // because the field may have an arbitrary alignment in the LLVM representation
165         // anyway.
166         //
167         // To demonstrate:
168         //
169         //     struct Foo<T: ?Sized> {
170         //         x: u16,
171         //         y: T
172         //     }
173         //
174         // The type `Foo<Foo<Trait>>` is represented in LLVM as `{ u16, { u16, u8 }}`, meaning that
175         // the `y` field has 16-bit alignment.
176
177         let meta = self.llextra;
178
179         let unaligned_offset = bx.cx().const_usize(offset.bytes());
180
181         // Get the alignment of the field
182         let (_, unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta);
183
184         // Bump the unaligned offset up to the appropriate alignment
185         let offset = round_up_const_value_to_alignment(bx, unaligned_offset, unsized_align);
186
187         debug!("struct_field_ptr: DST field offset: {:?}", offset);
188
189         // Cast and adjust pointer.
190         let byte_ptr = bx.pointercast(self.llval, bx.cx().type_i8p());
191         let byte_ptr = bx.gep(bx.cx().type_i8(), byte_ptr, &[offset]);
192
193         // Finally, cast back to the type expected.
194         let ll_fty = bx.cx().backend_type(field);
195         debug!("struct_field_ptr: Field type is {:?}", ll_fty);
196
197         PlaceRef {
198             llval: bx.pointercast(byte_ptr, bx.cx().type_ptr_to(ll_fty)),
199             llextra: self.llextra,
200             layout: field,
201             align: effective_field_align,
202         }
203     }
204
205     /// Obtain the actual discriminant of a value.
206     #[instrument(level = "trace", skip(bx))]
207     pub fn codegen_get_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
208         self,
209         bx: &mut Bx,
210         cast_to: Ty<'tcx>,
211     ) -> V {
212         let cast_to = bx.cx().immediate_backend_type(bx.cx().layout_of(cast_to));
213         if self.layout.abi.is_uninhabited() {
214             return bx.cx().const_undef(cast_to);
215         }
216         let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants {
217             Variants::Single { index } => {
218                 let discr_val = self
219                     .layout
220                     .ty
221                     .discriminant_for_variant(bx.cx().tcx(), index)
222                     .map_or(index.as_u32() as u128, |discr| discr.val);
223                 return bx.cx().const_uint_big(cast_to, discr_val);
224             }
225             Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => {
226                 (tag, tag_encoding, tag_field)
227             }
228         };
229
230         // Read the tag/niche-encoded discriminant from memory.
231         let tag = self.project_field(bx, tag_field);
232         let tag = bx.load_operand(tag);
233
234         // Decode the discriminant (specifically if it's niche-encoded).
235         match *tag_encoding {
236             TagEncoding::Direct => {
237                 let signed = match tag_scalar.primitive() {
238                     // We use `i1` for bytes that are always `0` or `1`,
239                     // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
240                     // let LLVM interpret the `i1` as signed, because
241                     // then `i1 1` (i.e., `E::B`) is effectively `i8 -1`.
242                     Int(_, signed) => !tag_scalar.is_bool() && signed,
243                     _ => false,
244                 };
245                 bx.intcast(tag.immediate(), cast_to, signed)
246             }
247             TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => {
248                 // Rebase from niche values to discriminants, and check
249                 // whether the result is in range for the niche variants.
250                 let niche_llty = bx.cx().immediate_backend_type(tag.layout);
251                 let tag = tag.immediate();
252
253                 // We first compute the "relative discriminant" (wrt `niche_variants`),
254                 // that is, if `n = niche_variants.end() - niche_variants.start()`,
255                 // we remap `niche_start..=niche_start + n` (which may wrap around)
256                 // to (non-wrap-around) `0..=n`, to be able to check whether the
257                 // discriminant corresponds to a niche variant with one comparison.
258                 // We also can't go directly to the (variant index) discriminant
259                 // and check that it is in the range `niche_variants`, because
260                 // that might not fit in the same type, on top of needing an extra
261                 // comparison (see also the comment on `let niche_discr`).
262                 let relative_discr = if niche_start == 0 {
263                     // Avoid subtracting `0`, which wouldn't work for pointers.
264                     // FIXME(eddyb) check the actual primitive type here.
265                     tag
266                 } else {
267                     bx.sub(tag, bx.cx().const_uint_big(niche_llty, niche_start))
268                 };
269                 let relative_max = niche_variants.end().as_u32() - niche_variants.start().as_u32();
270                 let is_niche = if relative_max == 0 {
271                     // Avoid calling `const_uint`, which wouldn't work for pointers.
272                     // Also use canonical == 0 instead of non-canonical u<= 0.
273                     // FIXME(eddyb) check the actual primitive type here.
274                     bx.icmp(IntPredicate::IntEQ, relative_discr, bx.cx().const_null(niche_llty))
275                 } else {
276                     let relative_max = bx.cx().const_uint(niche_llty, relative_max as u64);
277                     bx.icmp(IntPredicate::IntULE, relative_discr, relative_max)
278                 };
279
280                 // NOTE(eddyb) this addition needs to be performed on the final
281                 // type, in case the niche itself can't represent all variant
282                 // indices (e.g. `u8` niche with more than `256` variants,
283                 // but enough uninhabited variants so that the remaining variants
284                 // fit in the niche).
285                 // In other words, `niche_variants.end - niche_variants.start`
286                 // is representable in the niche, but `niche_variants.end`
287                 // might not be, in extreme cases.
288                 let niche_discr = {
289                     let relative_discr = if relative_max == 0 {
290                         // HACK(eddyb) since we have only one niche, we know which
291                         // one it is, and we can avoid having a dynamic value here.
292                         bx.cx().const_uint(cast_to, 0)
293                     } else {
294                         bx.intcast(relative_discr, cast_to, false)
295                     };
296                     bx.add(
297                         relative_discr,
298                         bx.cx().const_uint(cast_to, niche_variants.start().as_u32() as u64),
299                     )
300                 };
301
302                 bx.select(
303                     is_niche,
304                     niche_discr,
305                     bx.cx().const_uint(cast_to, untagged_variant.as_u32() as u64),
306                 )
307             }
308         }
309     }
310
311     /// Sets the discriminant for a new value of the given case of the given
312     /// representation.
313     pub fn codegen_set_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
314         &self,
315         bx: &mut Bx,
316         variant_index: VariantIdx,
317     ) {
318         if self.layout.for_variant(bx.cx(), variant_index).abi.is_uninhabited() {
319             // We play it safe by using a well-defined `abort`, but we could go for immediate UB
320             // if that turns out to be helpful.
321             bx.abort();
322             return;
323         }
324         match self.layout.variants {
325             Variants::Single { index } => {
326                 assert_eq!(index, variant_index);
327             }
328             Variants::Multiple { tag_encoding: TagEncoding::Direct, tag_field, .. } => {
329                 let ptr = self.project_field(bx, tag_field);
330                 let to =
331                     self.layout.ty.discriminant_for_variant(bx.tcx(), variant_index).unwrap().val;
332                 bx.store(
333                     bx.cx().const_uint_big(bx.cx().backend_type(ptr.layout), to),
334                     ptr.llval,
335                     ptr.align,
336                 );
337             }
338             Variants::Multiple {
339                 tag_encoding:
340                     TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start },
341                 tag_field,
342                 ..
343             } => {
344                 if variant_index != untagged_variant {
345                     let niche = self.project_field(bx, tag_field);
346                     let niche_llty = bx.cx().immediate_backend_type(niche.layout);
347                     let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
348                     let niche_value = (niche_value as u128).wrapping_add(niche_start);
349                     // FIXME(eddyb): check the actual primitive type here.
350                     let niche_llval = if niche_value == 0 {
351                         // HACK(eddyb): using `c_null` as it works on all types.
352                         bx.cx().const_null(niche_llty)
353                     } else {
354                         bx.cx().const_uint_big(niche_llty, niche_value)
355                     };
356                     OperandValue::Immediate(niche_llval).store(bx, niche);
357                 }
358             }
359         }
360     }
361
362     pub fn project_index<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
363         &self,
364         bx: &mut Bx,
365         llindex: V,
366     ) -> Self {
367         // Statically compute the offset if we can, otherwise just use the element size,
368         // as this will yield the lowest alignment.
369         let layout = self.layout.field(bx, 0);
370         let offset = if let Some(llindex) = bx.const_to_opt_uint(llindex) {
371             layout.size.checked_mul(llindex, bx).unwrap_or(layout.size)
372         } else {
373             layout.size
374         };
375
376         PlaceRef {
377             llval: bx.inbounds_gep(
378                 bx.cx().backend_type(self.layout),
379                 self.llval,
380                 &[bx.cx().const_usize(0), llindex],
381             ),
382             llextra: None,
383             layout,
384             align: self.align.restrict_for_offset(offset),
385         }
386     }
387
388     pub fn project_downcast<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
389         &self,
390         bx: &mut Bx,
391         variant_index: VariantIdx,
392     ) -> Self {
393         let mut downcast = *self;
394         downcast.layout = self.layout.for_variant(bx.cx(), variant_index);
395
396         // Cast to the appropriate variant struct type.
397         let variant_ty = bx.cx().backend_type(downcast.layout);
398         downcast.llval = bx.pointercast(downcast.llval, bx.cx().type_ptr_to(variant_ty));
399
400         downcast
401     }
402
403     pub fn storage_live<Bx: BuilderMethods<'a, 'tcx, Value = V>>(&self, bx: &mut Bx) {
404         bx.lifetime_start(self.llval, self.layout.size);
405     }
406
407     pub fn storage_dead<Bx: BuilderMethods<'a, 'tcx, Value = V>>(&self, bx: &mut Bx) {
408         bx.lifetime_end(self.llval, self.layout.size);
409     }
410 }
411
412 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
413     #[instrument(level = "trace", skip(self, bx))]
414     pub fn codegen_place(
415         &mut self,
416         bx: &mut Bx,
417         place_ref: mir::PlaceRef<'tcx>,
418     ) -> PlaceRef<'tcx, Bx::Value> {
419         let cx = self.cx;
420         let tcx = self.cx.tcx();
421
422         let mut base = 0;
423         let mut cg_base = match self.locals[place_ref.local] {
424             LocalRef::Place(place) => place,
425             LocalRef::UnsizedPlace(place) => bx.load_operand(place).deref(cx),
426             LocalRef::Operand(..) => {
427                 if place_ref.has_deref() {
428                     base = 1;
429                     let cg_base = self.codegen_consume(
430                         bx,
431                         mir::PlaceRef { projection: &place_ref.projection[..0], ..place_ref },
432                     );
433                     cg_base.deref(bx.cx())
434                 } else {
435                     bug!("using operand local {:?} as place", place_ref);
436                 }
437             }
438         };
439         for elem in place_ref.projection[base..].iter() {
440             cg_base = match *elem {
441                 mir::ProjectionElem::Deref => bx.load_operand(cg_base).deref(bx.cx()),
442                 mir::ProjectionElem::Field(ref field, _) => {
443                     cg_base.project_field(bx, field.index())
444                 }
445                 mir::ProjectionElem::Index(index) => {
446                     let index = &mir::Operand::Copy(mir::Place::from(index));
447                     let index = self.codegen_operand(bx, index);
448                     let llindex = index.immediate();
449                     cg_base.project_index(bx, llindex)
450                 }
451                 mir::ProjectionElem::ConstantIndex { offset, from_end: false, min_length: _ } => {
452                     let lloffset = bx.cx().const_usize(offset as u64);
453                     cg_base.project_index(bx, lloffset)
454                 }
455                 mir::ProjectionElem::ConstantIndex { offset, from_end: true, min_length: _ } => {
456                     let lloffset = bx.cx().const_usize(offset as u64);
457                     let lllen = cg_base.len(bx.cx());
458                     let llindex = bx.sub(lllen, lloffset);
459                     cg_base.project_index(bx, llindex)
460                 }
461                 mir::ProjectionElem::Subslice { from, to, from_end } => {
462                     let mut subslice = cg_base.project_index(bx, bx.cx().const_usize(from as u64));
463                     let projected_ty =
464                         PlaceTy::from_ty(cg_base.layout.ty).projection_ty(tcx, *elem).ty;
465                     subslice.layout = bx.cx().layout_of(self.monomorphize(projected_ty));
466
467                     if subslice.layout.is_unsized() {
468                         assert!(from_end, "slice subslices should be `from_end`");
469                         subslice.llextra = Some(bx.sub(
470                             cg_base.llextra.unwrap(),
471                             bx.cx().const_usize((from as u64) + (to as u64)),
472                         ));
473                     }
474
475                     // Cast the place pointer type to the new
476                     // array or slice type (`*[%_; new_len]`).
477                     subslice.llval = bx.pointercast(
478                         subslice.llval,
479                         bx.cx().type_ptr_to(bx.cx().backend_type(subslice.layout)),
480                     );
481
482                     subslice
483                 }
484                 mir::ProjectionElem::Downcast(_, v) => cg_base.project_downcast(bx, v),
485             };
486         }
487         debug!("codegen_place(place={:?}) => {:?}", place_ref, cg_base);
488         cg_base
489     }
490
491     pub fn monomorphized_place_ty(&self, place_ref: mir::PlaceRef<'tcx>) -> Ty<'tcx> {
492         let tcx = self.cx.tcx();
493         let place_ty = place_ref.ty(self.mir, tcx);
494         self.monomorphize(place_ty.ty)
495     }
496 }
497
498 fn round_up_const_value_to_alignment<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
499     bx: &mut Bx,
500     value: Bx::Value,
501     align: Bx::Value,
502 ) -> Bx::Value {
503     // In pseudo code:
504     //
505     //     if value & (align - 1) == 0 {
506     //         value
507     //     } else {
508     //         (value & !(align - 1)) + align
509     //     }
510     //
511     // Usually this is written without branches as
512     //
513     //     (value + align - 1) & !(align - 1)
514     //
515     // But this formula cannot take advantage of constant `value`. E.g. if `value` is known
516     // at compile time to be `1`, this expression should be optimized to `align`. However,
517     // optimization only holds if `align` is a power of two. Since the optimizer doesn't know
518     // that `align` is a power of two, it cannot perform this optimization.
519     //
520     // Instead we use
521     //
522     //     value + (-value & (align - 1))
523     //
524     // Since `align` is used only once, the expression can be optimized. For `value = 0`
525     // its optimized to `0` even in debug mode.
526     //
527     // NB: The previous version of this code used
528     //
529     //     (value + align - 1) & -align
530     //
531     // Even though `-align == !(align - 1)`, LLVM failed to optimize this even for
532     // `value = 0`. Bug report: https://bugs.llvm.org/show_bug.cgi?id=48559
533     let one = bx.const_usize(1);
534     let align_minus_1 = bx.sub(align, one);
535     let neg_value = bx.neg(value);
536     let offset = bx.and(neg_value, align_minus_1);
537     bx.add(value, offset)
538 }