]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/place.rs
Traitified IntrinsicCallMethods
[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, MemFlags};
18 use common::{CodegenCx, IntPredicate};
19 use type_of::LayoutLlvmExt;
20 use value::Value;
21 use glue;
22 use mir::constant::const_alloc_to_llvm;
23
24 use interfaces::*;
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 = bx.cx().static_addr_of(init, layout.align, None);
67
68         let llval = unsafe { LLVMConstInBoundsGEP(
69             bx.cx().static_bitcast(base_addr, bx.cx().type_i8p()),
70             &bx.cx().const_usize(offset.bytes()),
71             1,
72         )};
73         let llval = bx.cx().static_bitcast(llval, bx.cx().type_ptr_to(layout.llvm_type(bx.cx())));
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                 cx.const_usize(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, bx.cx().type_i1())
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, cx.type_ptr_to(field.llvm_type(cx))),
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 = cx.const_usize(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, cx.const_usize(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, cx.type_i8p());
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, bx.cx().type_ptr_to(ll_fty)),
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(
284         self,
285         bx: &Builder<'a, 'll, 'tcx>,
286         cast_to: Ty<'tcx>
287     ) -> &'ll Value {
288         let cast_to = bx.cx().layout_of(cast_to).immediate_llvm_type(bx.cx());
289         if self.layout.abi.is_uninhabited() {
290             return bx.cx().const_undef(cast_to);
291         }
292         match self.layout.variants {
293             layout::Variants::Single { index } => {
294                 let discr_val = self.layout.ty.ty_adt_def().map_or(
295                     index.as_u32() as u128,
296                     |def| def.discriminant_for_variant(bx.cx().tcx, index).val);
297                 return bx.cx().const_uint_big(cast_to, discr_val);
298             }
299             layout::Variants::Tagged { .. } |
300             layout::Variants::NicheFilling { .. } => {},
301         }
302
303         let discr = self.project_field(bx, 0);
304         let lldiscr = discr.load(bx).immediate();
305         match self.layout.variants {
306             layout::Variants::Single { .. } => bug!(),
307             layout::Variants::Tagged { ref tag, .. } => {
308                 let signed = match tag.value {
309                     // We use `i1` for bytes that are always `0` or `1`,
310                     // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
311                     // let LLVM interpret the `i1` as signed, because
312                     // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
313                     layout::Int(_, signed) => !tag.is_bool() && signed,
314                     _ => false
315                 };
316                 bx.intcast(lldiscr, cast_to, signed)
317             }
318             layout::Variants::NicheFilling {
319                 dataful_variant,
320                 ref niche_variants,
321                 niche_start,
322                 ..
323             } => {
324                 let niche_llty = discr.layout.immediate_llvm_type(bx.cx());
325                 if niche_variants.start() == niche_variants.end() {
326                     // FIXME(eddyb) Check the actual primitive type here.
327                     let niche_llval = if niche_start == 0 {
328                         // HACK(eddyb) Using `c_null` as it works on all types.
329                         bx.cx().const_null(niche_llty)
330                     } else {
331                         bx.cx().const_uint_big(niche_llty, niche_start)
332                     };
333                     bx.select(bx.icmp(IntPredicate::IntEQ, lldiscr, niche_llval),
334                         bx.cx().const_uint(cast_to, niche_variants.start().as_u32() as u64),
335                         bx.cx().const_uint(cast_to, dataful_variant.as_u32() as u64))
336                 } else {
337                     // Rebase from niche values to discriminant values.
338                     let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
339                     let lldiscr = bx.sub(lldiscr, bx.cx().const_uint_big(niche_llty, delta));
340                     let lldiscr_max =
341                         bx.cx().const_uint(niche_llty, niche_variants.end().as_u32() as u64);
342                     bx.select(bx.icmp(IntPredicate::IntULE, lldiscr, lldiscr_max),
343                         bx.intcast(lldiscr, cast_to, false),
344                         bx.cx().const_uint(cast_to, dataful_variant.as_u32() as u64))
345                 }
346             }
347         }
348     }
349
350     /// Set the discriminant for a new value of the given case of the given
351     /// representation.
352     pub fn codegen_set_discr(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx) {
353         if self.layout.for_variant(bx.cx(), variant_index).abi.is_uninhabited() {
354             return;
355         }
356         match self.layout.variants {
357             layout::Variants::Single { index } => {
358                 assert_eq!(index, variant_index);
359             }
360             layout::Variants::Tagged { .. } => {
361                 let ptr = self.project_field(bx, 0);
362                 let to = self.layout.ty.ty_adt_def().unwrap()
363                     .discriminant_for_variant(bx.tcx(), variant_index)
364                     .val;
365                 bx.store(
366                     bx.cx().const_uint_big(ptr.layout.llvm_type(bx.cx()), to),
367                     ptr.llval,
368                     ptr.align);
369             }
370             layout::Variants::NicheFilling {
371                 dataful_variant,
372                 ref niche_variants,
373                 niche_start,
374                 ..
375             } => {
376                 if variant_index != dataful_variant {
377                     if bx.sess().target.target.arch == "arm" ||
378                        bx.sess().target.target.arch == "aarch64" {
379                         // Issue #34427: As workaround for LLVM bug on ARM,
380                         // use memset of 0 before assigning niche value.
381                         let fill_byte = bx.cx().const_u8(0);
382                         let (size, align) = self.layout.size_and_align();
383                         let size = bx.cx().const_usize(size.bytes());
384                         bx.memset(self.llval, fill_byte, size, align, MemFlags::empty());
385                     }
386
387                     let niche = self.project_field(bx, 0);
388                     let niche_llty = niche.layout.immediate_llvm_type(bx.cx());
389                     let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
390                     let niche_value = (niche_value as u128)
391                         .wrapping_add(niche_start);
392                     // FIXME(eddyb) Check the actual primitive type here.
393                     let niche_llval = if niche_value == 0 {
394                         // HACK(eddyb) Using `c_null` as it works on all types.
395                         bx.cx().const_null(niche_llty)
396                     } else {
397                         bx.cx().const_uint_big(niche_llty, niche_value)
398                     };
399                     OperandValue::Immediate(niche_llval).store(bx, niche);
400                 }
401             }
402         }
403     }
404
405     pub fn project_index(&self, bx: &Builder<'a, 'll, 'tcx>, llindex: &'ll Value)
406                          -> PlaceRef<'tcx, &'ll Value> {
407         PlaceRef {
408             llval: bx.inbounds_gep(self.llval, &[bx.cx().const_usize(0), llindex]),
409             llextra: None,
410             layout: self.layout.field(bx.cx(), 0),
411             align: self.align
412         }
413     }
414
415     pub fn project_downcast(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx)
416                             -> PlaceRef<'tcx, &'ll Value> {
417         let mut downcast = *self;
418         downcast.layout = self.layout.for_variant(bx.cx(), variant_index);
419
420         // Cast to the appropriate variant struct type.
421         let variant_ty = downcast.layout.llvm_type(bx.cx());
422         downcast.llval = bx.pointercast(downcast.llval, bx.cx().type_ptr_to(variant_ty));
423
424         downcast
425     }
426
427     pub fn storage_live(&self, bx: &Builder<'a, 'll, 'tcx>) {
428         bx.lifetime_start(self.llval, self.layout.size);
429     }
430
431     pub fn storage_dead(&self, bx: &Builder<'a, 'll, 'tcx>) {
432         bx.lifetime_end(self.llval, self.layout.size);
433     }
434 }
435
436 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
437     pub fn codegen_place(&mut self,
438                         bx: &Builder<'a, 'll, 'tcx>,
439                         place: &mir::Place<'tcx>)
440                         -> PlaceRef<'tcx, &'ll Value> {
441         debug!("codegen_place(place={:?})", place);
442
443         let cx = bx.cx();
444         let tcx = cx.tcx;
445
446         if let mir::Place::Local(index) = *place {
447             match self.locals[index] {
448                 LocalRef::Place(place) => {
449                     return place;
450                 }
451                 LocalRef::UnsizedPlace(place) => {
452                     return place.load(bx).deref(&cx);
453                 }
454                 LocalRef::Operand(..) => {
455                     bug!("using operand local {:?} as place", place);
456                 }
457             }
458         }
459
460         let result = match *place {
461             mir::Place::Local(_) => bug!(), // handled above
462             mir::Place::Promoted(box (index, ty)) => {
463                 let param_env = ty::ParamEnv::reveal_all();
464                 let cid = mir::interpret::GlobalId {
465                     instance: self.instance,
466                     promoted: Some(index),
467                 };
468                 let layout = cx.layout_of(self.monomorphize(&ty));
469                 match bx.tcx().const_eval(param_env.and(cid)) {
470                     Ok(val) => match val.val {
471                         mir::interpret::ConstValue::ByRef(_, alloc, offset) => {
472                             PlaceRef::from_const_alloc(bx, layout, alloc, offset)
473                         }
474                         _ => bug!("promoteds should have an allocation: {:?}", val),
475                     },
476                     Err(_) => {
477                         // this is unreachable as long as runtime
478                         // and compile-time agree on values
479                         // With floats that won't always be true
480                         // so we generate an abort
481                         let fnname = bx.cx().get_intrinsic(&("llvm.trap"));
482                         bx.call(fnname, &[], None);
483                         let llval = bx.cx().const_undef(
484                             bx.cx().type_ptr_to(layout.llvm_type(bx.cx()))
485                         );
486                         PlaceRef::new_sized(llval, layout, layout.align)
487                     }
488                 }
489             }
490             mir::Place::Static(box mir::Static { def_id, ty }) => {
491                 let layout = cx.layout_of(self.monomorphize(&ty));
492                 PlaceRef::new_sized(cx.get_static(def_id), layout, layout.align)
493             },
494             mir::Place::Projection(box mir::Projection {
495                 ref base,
496                 elem: mir::ProjectionElem::Deref
497             }) => {
498                 // Load the pointer from its location.
499                 self.codegen_consume(bx, base).deref(bx.cx())
500             }
501             mir::Place::Projection(ref projection) => {
502                 let cg_base = self.codegen_place(bx, &projection.base);
503
504                 match projection.elem {
505                     mir::ProjectionElem::Deref => bug!(),
506                     mir::ProjectionElem::Field(ref field, _) => {
507                         cg_base.project_field(bx, field.index())
508                     }
509                     mir::ProjectionElem::Index(index) => {
510                         let index = &mir::Operand::Copy(mir::Place::Local(index));
511                         let index = self.codegen_operand(bx, index);
512                         let llindex = index.immediate();
513                         cg_base.project_index(bx, llindex)
514                     }
515                     mir::ProjectionElem::ConstantIndex { offset,
516                                                          from_end: false,
517                                                          min_length: _ } => {
518                         let lloffset = bx.cx().const_usize(offset as u64);
519                         cg_base.project_index(bx, lloffset)
520                     }
521                     mir::ProjectionElem::ConstantIndex { offset,
522                                                          from_end: true,
523                                                          min_length: _ } => {
524                         let lloffset = bx.cx().const_usize(offset as u64);
525                         let lllen = cg_base.len(bx.cx());
526                         let llindex = bx.sub(lllen, lloffset);
527                         cg_base.project_index(bx, llindex)
528                     }
529                     mir::ProjectionElem::Subslice { from, to } => {
530                         let mut subslice = cg_base.project_index(bx,
531                             bx.cx().const_usize(from as u64));
532                         let projected_ty = PlaceTy::Ty { ty: cg_base.layout.ty }
533                             .projection_ty(tcx, &projection.elem)
534                             .to_ty(bx.tcx());
535                         subslice.layout = bx.cx().layout_of(self.monomorphize(&projected_ty));
536
537                         if subslice.layout.is_unsized() {
538                             subslice.llextra = Some(bx.sub(cg_base.llextra.unwrap(),
539                                 bx.cx().const_usize((from as u64) + (to as u64))));
540                         }
541
542                         // Cast the place pointer type to the new
543                         // array or slice type (*[%_; new_len]).
544                         subslice.llval = bx.pointercast(subslice.llval,
545                             bx.cx().type_ptr_to(subslice.layout.llvm_type(bx.cx())));
546
547                         subslice
548                     }
549                     mir::ProjectionElem::Downcast(_, v) => {
550                         cg_base.project_downcast(bx, v)
551                     }
552                 }
553             }
554         };
555         debug!("codegen_place(place={:?}) => {:?}", place, result);
556         result
557     }
558
559     pub fn monomorphized_place_ty(&self, place: &mir::Place<'tcx>) -> Ty<'tcx> {
560         let tcx = self.cx.tcx;
561         let place_ty = place.ty(self.mir, tcx);
562         self.monomorphize(&place_ty.to_ty(tcx))
563     }
564 }