]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/place.rs
Reduced line length to pass tidy
[rust.git] / src / librustc_codegen_llvm / mir / place.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use llvm::{self, LLVMConstInBoundsGEP};
12 use rustc::ty::{self, Ty};
13 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, Size, VariantIdx};
14 use rustc::mir;
15 use rustc::mir::tcx::PlaceTy;
16 use base;
17 use builder::Builder;
18 use common::{CodegenCx, C_undef, C_usize, C_u8, C_u32, C_uint, C_null, C_uint_big};
19 use consts;
20 use type_of::LayoutLlvmExt;
21 use type_::Type;
22 use value::Value;
23 use glue;
24 use mir::constant::const_alloc_to_llvm;
25
26 use super::{FunctionCx, LocalRef};
27 use super::operand::{OperandRef, OperandValue};
28
29 #[derive(Copy, Clone, Debug)]
30 pub struct PlaceRef<'tcx, V> {
31     /// Pointer to the contents of the place
32     pub llval: V,
33
34     /// This place's extra data if it is unsized, or null
35     pub llextra: Option<V>,
36
37     /// Monomorphized type of this place, including variant information
38     pub layout: TyLayout<'tcx>,
39
40     /// What alignment we know for this place
41     pub align: Align,
42 }
43
44 impl PlaceRef<'tcx, &'ll Value> {
45     pub fn new_sized(
46         llval: &'ll Value,
47         layout: TyLayout<'tcx>,
48         align: Align,
49     ) -> PlaceRef<'tcx, &'ll Value> {
50         assert!(!layout.is_unsized());
51         PlaceRef {
52             llval,
53             llextra: None,
54             layout,
55             align
56         }
57     }
58
59     pub fn from_const_alloc(
60         bx: &Builder<'a, 'll, 'tcx>,
61         layout: TyLayout<'tcx>,
62         alloc: &mir::interpret::Allocation,
63         offset: Size,
64     ) -> PlaceRef<'tcx, &'ll Value> {
65         let init = const_alloc_to_llvm(bx.cx, alloc);
66         let base_addr = consts::addr_of(bx.cx, init, layout.align, None);
67
68         let llval = unsafe { LLVMConstInBoundsGEP(
69             consts::bitcast(base_addr, Type::i8p(bx.cx)),
70             &C_usize(bx.cx, offset.bytes()),
71             1,
72         )};
73         let llval = consts::bitcast(llval, layout.llvm_type(bx.cx).ptr_to());
74         PlaceRef::new_sized(llval, layout, alloc.align)
75     }
76
77     pub fn alloca(bx: &Builder<'a, 'll, 'tcx>, layout: TyLayout<'tcx>, name: &str)
78                   -> PlaceRef<'tcx, &'ll Value> {
79         debug!("alloca({:?}: {:?})", name, layout);
80         assert!(!layout.is_unsized(), "tried to statically allocate unsized place");
81         let tmp = bx.alloca(layout.llvm_type(bx.cx), name, layout.align);
82         Self::new_sized(tmp, layout, layout.align)
83     }
84
85     /// Returns a place for an indirect reference to an unsized place.
86     pub fn alloca_unsized_indirect(
87         bx: &Builder<'a, 'll, 'tcx>,
88         layout: TyLayout<'tcx>,
89         name: &str,
90     ) -> PlaceRef<'tcx, &'ll Value> {
91         debug!("alloca_unsized_indirect({:?}: {:?})", name, layout);
92         assert!(layout.is_unsized(), "tried to allocate indirect place for sized values");
93         let ptr_ty = bx.cx.tcx.mk_mut_ptr(layout.ty);
94         let ptr_layout = bx.cx.layout_of(ptr_ty);
95         Self::alloca(bx, ptr_layout, name)
96     }
97
98     pub fn len(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Value {
99         if let layout::FieldPlacement::Array { count, .. } = self.layout.fields {
100             if self.layout.is_unsized() {
101                 assert_eq!(count, 0);
102                 self.llextra.unwrap()
103             } else {
104                 C_usize(cx, count)
105             }
106         } else {
107             bug!("unexpected layout `{:#?}` in PlaceRef::len", self.layout)
108         }
109     }
110
111     pub fn load(&self, bx: &Builder<'a, 'll, 'tcx>) -> OperandRef<'tcx, &'ll Value> {
112         debug!("PlaceRef::load: {:?}", self);
113
114         assert_eq!(self.llextra.is_some(), self.layout.is_unsized());
115
116         if self.layout.is_zst() {
117             return OperandRef::new_zst(bx.cx, self.layout);
118         }
119
120         let scalar_load_metadata = |load, scalar: &layout::Scalar| {
121             let vr = scalar.valid_range.clone();
122             match scalar.value {
123                 layout::Int(..) => {
124                     let range = scalar.valid_range_exclusive(bx.cx);
125                     if range.start != range.end {
126                         bx.range_metadata(load, range);
127                     }
128                 }
129                 layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
130                     bx.nonnull_metadata(load);
131                 }
132                 _ => {}
133             }
134         };
135
136         let val = if let Some(llextra) = self.llextra {
137             OperandValue::Ref(self.llval, Some(llextra), self.align)
138         } else if self.layout.is_llvm_immediate() {
139             let mut const_llval = None;
140             unsafe {
141                 if let Some(global) = llvm::LLVMIsAGlobalVariable(self.llval) {
142                     if llvm::LLVMIsGlobalConstant(global) == llvm::True {
143                         const_llval = llvm::LLVMGetInitializer(global);
144                     }
145                 }
146             }
147             let llval = const_llval.unwrap_or_else(|| {
148                 let load = bx.load(self.llval, self.align);
149                 if let layout::Abi::Scalar(ref scalar) = self.layout.abi {
150                     scalar_load_metadata(load, scalar);
151                 }
152                 load
153             });
154             OperandValue::Immediate(base::to_immediate(bx, llval, self.layout))
155         } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
156             let load = |i, scalar: &layout::Scalar| {
157                 let llptr = bx.struct_gep(self.llval, i as u64);
158                 let load = bx.load(llptr, self.align);
159                 scalar_load_metadata(load, scalar);
160                 if scalar.is_bool() {
161                     bx.trunc(load, Type::i1(bx.cx))
162                 } else {
163                     load
164                 }
165             };
166             OperandValue::Pair(load(0, a), load(1, b))
167         } else {
168             OperandValue::Ref(self.llval, None, self.align)
169         };
170
171         OperandRef { val, layout: self.layout }
172     }
173
174     /// Access a field, at a point when the value's case is known.
175     pub fn project_field(
176         self,
177         bx: &Builder<'a, 'll, 'tcx>,
178         ix: usize,
179     ) -> PlaceRef<'tcx, &'ll Value> {
180         let cx = bx.cx;
181         let field = self.layout.field(cx, ix);
182         let offset = self.layout.fields.offset(ix);
183         let effective_field_align = self.align.restrict_for_offset(offset);
184
185         let simple = || {
186             // Unions and newtypes only use an offset of 0.
187             let llval = if offset.bytes() == 0 {
188                 self.llval
189             } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
190                 // Offsets have to match either first or second field.
191                 assert_eq!(offset, a.value.size(cx).abi_align(b.value.align(cx)));
192                 bx.struct_gep(self.llval, 1)
193             } else {
194                 bx.struct_gep(self.llval, self.layout.llvm_field_index(ix))
195             };
196             PlaceRef {
197                 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
198                 llval: bx.pointercast(llval, field.llvm_type(cx).ptr_to()),
199                 llextra: if cx.type_has_metadata(field.ty) {
200                     self.llextra
201                 } else {
202                     None
203                 },
204                 layout: field,
205                 align: effective_field_align,
206             }
207         };
208
209         // Simple cases, which don't need DST adjustment:
210         //   * no metadata available - just log the case
211         //   * known alignment - sized types, [T], str or a foreign type
212         //   * packed struct - there is no alignment padding
213         match field.ty.sty {
214             _ if self.llextra.is_none() => {
215                 debug!("Unsized field `{}`, of `{:?}` has no metadata for adjustment",
216                     ix, self.llval);
217                 return simple();
218             }
219             _ if !field.is_unsized() => return simple(),
220             ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(),
221             ty::Adt(def, _) => {
222                 if def.repr.packed() {
223                     // FIXME(eddyb) generalize the adjustment when we
224                     // start supporting packing to larger alignments.
225                     assert_eq!(self.layout.align.abi(), 1);
226                     return simple();
227                 }
228             }
229             _ => {}
230         }
231
232         // We need to get the pointer manually now.
233         // We do this by casting to a *i8, then offsetting it by the appropriate amount.
234         // We do this instead of, say, simply adjusting the pointer from the result of a GEP
235         // because the field may have an arbitrary alignment in the LLVM representation
236         // anyway.
237         //
238         // To demonstrate:
239         //   struct Foo<T: ?Sized> {
240         //      x: u16,
241         //      y: T
242         //   }
243         //
244         // The type Foo<Foo<Trait>> is represented in LLVM as { u16, { u16, u8 }}, meaning that
245         // the `y` field has 16-bit alignment.
246
247         let meta = self.llextra;
248
249         let unaligned_offset = C_usize(cx, offset.bytes());
250
251         // Get the alignment of the field
252         let (_, unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta);
253
254         // Bump the unaligned offset up to the appropriate alignment using the
255         // following expression:
256         //
257         //   (unaligned offset + (align - 1)) & -align
258
259         // Calculate offset
260         let align_sub_1 = bx.sub(unsized_align, C_usize(cx, 1u64));
261         let offset = bx.and(bx.add(unaligned_offset, align_sub_1),
262         bx.neg(unsized_align));
263
264         debug!("struct_field_ptr: DST field offset: {:?}", offset);
265
266         // Cast and adjust pointer
267         let byte_ptr = bx.pointercast(self.llval, Type::i8p(cx));
268         let byte_ptr = bx.gep(byte_ptr, &[offset]);
269
270         // Finally, cast back to the type expected
271         let ll_fty = field.llvm_type(cx);
272         debug!("struct_field_ptr: Field type is {:?}", ll_fty);
273
274         PlaceRef {
275             llval: bx.pointercast(byte_ptr, ll_fty.ptr_to()),
276             llextra: self.llextra,
277             layout: field,
278             align: effective_field_align,
279         }
280     }
281
282     /// Obtain the actual discriminant of a value.
283     pub fn codegen_get_discr(self, bx: &Builder<'a, 'll, 'tcx>, cast_to: Ty<'tcx>) -> &'ll Value {
284         let cast_to = bx.cx.layout_of(cast_to).immediate_llvm_type(bx.cx);
285         if self.layout.abi.is_uninhabited() {
286             return C_undef(cast_to);
287         }
288         match self.layout.variants {
289             layout::Variants::Single { index } => {
290                 let discr_val = self.layout.ty.ty_adt_def().map_or(
291                     index.as_u32() as u128,
292                     |def| def.discriminant_for_variant(bx.cx.tcx, index).val);
293                 return C_uint_big(cast_to, discr_val);
294             }
295             layout::Variants::Tagged { .. } |
296             layout::Variants::NicheFilling { .. } => {},
297         }
298
299         let discr = self.project_field(bx, 0);
300         let lldiscr = discr.load(bx).immediate();
301         match self.layout.variants {
302             layout::Variants::Single { .. } => bug!(),
303             layout::Variants::Tagged { ref tag, .. } => {
304                 let signed = match tag.value {
305                     // We use `i1` for bytes that are always `0` or `1`,
306                     // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
307                     // let LLVM interpret the `i1` as signed, because
308                     // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
309                     layout::Int(_, signed) => !tag.is_bool() && signed,
310                     _ => false
311                 };
312                 bx.intcast(lldiscr, cast_to, signed)
313             }
314             layout::Variants::NicheFilling {
315                 dataful_variant,
316                 ref niche_variants,
317                 niche_start,
318                 ..
319             } => {
320                 let niche_llty = discr.layout.immediate_llvm_type(bx.cx);
321                 if niche_variants.start() == niche_variants.end() {
322                     // FIXME(eddyb) Check the actual primitive type here.
323                     let niche_llval = if niche_start == 0 {
324                         // HACK(eddyb) Using `C_null` as it works on all types.
325                         C_null(niche_llty)
326                     } else {
327                         C_uint_big(niche_llty, niche_start)
328                     };
329                     bx.select(bx.icmp(llvm::IntEQ, lldiscr, niche_llval),
330                         C_uint(cast_to, niche_variants.start().as_u32() as u64),
331                         C_uint(cast_to, dataful_variant.as_u32() as u64))
332                 } else {
333                     // Rebase from niche values to discriminant values.
334                     let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
335                     let lldiscr = bx.sub(lldiscr, C_uint_big(niche_llty, delta));
336                     let lldiscr_max = C_uint(niche_llty, niche_variants.end().as_u32() as u64);
337                     bx.select(bx.icmp(llvm::IntULE, lldiscr, lldiscr_max),
338                         bx.intcast(lldiscr, cast_to, false),
339                         C_uint(cast_to, dataful_variant.as_u32() as u64))
340                 }
341             }
342         }
343     }
344
345     /// Set the discriminant for a new value of the given case of the given
346     /// representation.
347     pub fn codegen_set_discr(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx) {
348         if self.layout.for_variant(bx.cx, variant_index).abi.is_uninhabited() {
349             return;
350         }
351         match self.layout.variants {
352             layout::Variants::Single { index } => {
353                 assert_eq!(index, variant_index);
354             }
355             layout::Variants::Tagged { .. } => {
356                 let ptr = self.project_field(bx, 0);
357                 let to = self.layout.ty.ty_adt_def().unwrap()
358                     .discriminant_for_variant(bx.tcx(), variant_index)
359                     .val;
360                 bx.store(
361                     C_uint_big(ptr.layout.llvm_type(bx.cx), to),
362                     ptr.llval,
363                     ptr.align);
364             }
365             layout::Variants::NicheFilling {
366                 dataful_variant,
367                 ref niche_variants,
368                 niche_start,
369                 ..
370             } => {
371                 if variant_index != dataful_variant {
372                     if bx.sess().target.target.arch == "arm" ||
373                        bx.sess().target.target.arch == "aarch64" {
374                         // Issue #34427: As workaround for LLVM bug on ARM,
375                         // use memset of 0 before assigning niche value.
376                         let llptr = bx.pointercast(self.llval, Type::i8(bx.cx).ptr_to());
377                         let fill_byte = C_u8(bx.cx, 0);
378                         let (size, align) = self.layout.size_and_align();
379                         let size = C_usize(bx.cx, size.bytes());
380                         let align = C_u32(bx.cx, align.abi() as u32);
381                         base::call_memset(bx, llptr, fill_byte, size, align, false);
382                     }
383
384                     let niche = self.project_field(bx, 0);
385                     let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
386                     let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
387                     let niche_value = (niche_value as u128)
388                         .wrapping_add(niche_start);
389                     // FIXME(eddyb) Check the actual primitive type here.
390                     let niche_llval = if niche_value == 0 {
391                         // HACK(eddyb) Using `C_null` as it works on all types.
392                         C_null(niche_llty)
393                     } else {
394                         C_uint_big(niche_llty, niche_value)
395                     };
396                     OperandValue::Immediate(niche_llval).store(bx, niche);
397                 }
398             }
399         }
400     }
401
402     pub fn project_index(&self, bx: &Builder<'a, 'll, 'tcx>, llindex: &'ll Value)
403                          -> PlaceRef<'tcx, &'ll Value> {
404         PlaceRef {
405             llval: bx.inbounds_gep(self.llval, &[C_usize(bx.cx, 0), llindex]),
406             llextra: None,
407             layout: self.layout.field(bx.cx, 0),
408             align: self.align
409         }
410     }
411
412     pub fn project_downcast(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx)
413                             -> PlaceRef<'tcx, &'ll Value> {
414         let mut downcast = *self;
415         downcast.layout = self.layout.for_variant(bx.cx, variant_index);
416
417         // Cast to the appropriate variant struct type.
418         let variant_ty = downcast.layout.llvm_type(bx.cx);
419         downcast.llval = bx.pointercast(downcast.llval, variant_ty.ptr_to());
420
421         downcast
422     }
423
424     pub fn storage_live(&self, bx: &Builder<'a, 'll, 'tcx>) {
425         bx.lifetime_start(self.llval, self.layout.size);
426     }
427
428     pub fn storage_dead(&self, bx: &Builder<'a, 'll, 'tcx>) {
429         bx.lifetime_end(self.llval, self.layout.size);
430     }
431 }
432
433 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
434     pub fn codegen_place(&mut self,
435                         bx: &Builder<'a, 'll, 'tcx>,
436                         place: &mir::Place<'tcx>)
437                         -> PlaceRef<'tcx, &'ll Value> {
438         debug!("codegen_place(place={:?})", place);
439
440         let cx = bx.cx;
441         let tcx = cx.tcx;
442
443         if let mir::Place::Local(index) = *place {
444             match self.locals[index] {
445                 LocalRef::Place(place) => {
446                     return place;
447                 }
448                 LocalRef::UnsizedPlace(place) => {
449                     return place.load(bx).deref(&cx);
450                 }
451                 LocalRef::Operand(..) => {
452                     bug!("using operand local {:?} as place", place);
453                 }
454             }
455         }
456
457         let result = match *place {
458             mir::Place::Local(_) => bug!(), // handled above
459             mir::Place::Promoted(box (index, ty)) => {
460                 let param_env = ty::ParamEnv::reveal_all();
461                 let cid = mir::interpret::GlobalId {
462                     instance: self.instance,
463                     promoted: Some(index),
464                 };
465                 let layout = cx.layout_of(self.monomorphize(&ty));
466                 match bx.tcx().const_eval(param_env.and(cid)) {
467                     Ok(val) => match val.val {
468                         mir::interpret::ConstValue::ByRef(_, alloc, offset) => {
469                             PlaceRef::from_const_alloc(bx, layout, alloc, offset)
470                         }
471                         _ => bug!("promoteds should have an allocation: {:?}", val),
472                     },
473                     Err(_) => {
474                         // this is unreachable as long as runtime
475                         // and compile-time agree on values
476                         // With floats that won't always be true
477                         // so we generate an abort
478                         let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
479                         bx.call(fnname, &[], None);
480                         let llval = C_undef(layout.llvm_type(bx.cx).ptr_to());
481                         PlaceRef::new_sized(llval, layout, layout.align)
482                     }
483                 }
484             }
485             mir::Place::Static(box mir::Static { def_id, ty }) => {
486                 let layout = cx.layout_of(self.monomorphize(&ty));
487                 PlaceRef::new_sized(consts::get_static(cx, def_id), layout, layout.align)
488             },
489             mir::Place::Projection(box mir::Projection {
490                 ref base,
491                 elem: mir::ProjectionElem::Deref
492             }) => {
493                 // Load the pointer from its location.
494                 self.codegen_consume(bx, base).deref(bx.cx)
495             }
496             mir::Place::Projection(ref projection) => {
497                 let cg_base = self.codegen_place(bx, &projection.base);
498
499                 match projection.elem {
500                     mir::ProjectionElem::Deref => bug!(),
501                     mir::ProjectionElem::Field(ref field, _) => {
502                         cg_base.project_field(bx, field.index())
503                     }
504                     mir::ProjectionElem::Index(index) => {
505                         let index = &mir::Operand::Copy(mir::Place::Local(index));
506                         let index = self.codegen_operand(bx, index);
507                         let llindex = index.immediate();
508                         cg_base.project_index(bx, llindex)
509                     }
510                     mir::ProjectionElem::ConstantIndex { offset,
511                                                          from_end: false,
512                                                          min_length: _ } => {
513                         let lloffset = C_usize(bx.cx, offset as u64);
514                         cg_base.project_index(bx, lloffset)
515                     }
516                     mir::ProjectionElem::ConstantIndex { offset,
517                                                          from_end: true,
518                                                          min_length: _ } => {
519                         let lloffset = C_usize(bx.cx, offset as u64);
520                         let lllen = cg_base.len(bx.cx);
521                         let llindex = bx.sub(lllen, lloffset);
522                         cg_base.project_index(bx, llindex)
523                     }
524                     mir::ProjectionElem::Subslice { from, to } => {
525                         let mut subslice = cg_base.project_index(bx,
526                             C_usize(bx.cx, from as u64));
527                         let projected_ty = PlaceTy::Ty { ty: cg_base.layout.ty }
528                             .projection_ty(tcx, &projection.elem)
529                             .to_ty(bx.tcx());
530                         subslice.layout = bx.cx.layout_of(self.monomorphize(&projected_ty));
531
532                         if subslice.layout.is_unsized() {
533                             subslice.llextra = Some(bx.sub(cg_base.llextra.unwrap(),
534                                 C_usize(bx.cx, (from as u64) + (to as u64))));
535                         }
536
537                         // Cast the place pointer type to the new
538                         // array or slice type (*[%_; new_len]).
539                         subslice.llval = bx.pointercast(subslice.llval,
540                             subslice.layout.llvm_type(bx.cx).ptr_to());
541
542                         subslice
543                     }
544                     mir::ProjectionElem::Downcast(_, v) => {
545                         cg_base.project_downcast(bx, v)
546                     }
547                 }
548             }
549         };
550         debug!("codegen_place(place={:?}) => {:?}", place, result);
551         result
552     }
553
554     pub fn monomorphized_place_ty(&self, place: &mir::Place<'tcx>) -> Ty<'tcx> {
555         let tcx = self.cx.tcx;
556         let place_ty = place.ty(self.mir, tcx);
557         self.monomorphize(&place_ty.to_ty(tcx))
558     }
559 }