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