]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/operand.rs
Auto merge of #41282 - arielb1:missing-impl-item, r=petrochenkov
[rust.git] / src / librustc_trans / mir / operand.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::ValueRef;
12 use rustc::ty::{self, Ty};
13 use rustc::ty::layout::{Layout, LayoutTyper};
14 use rustc::mir;
15 use rustc::mir::tcx::LvalueTy;
16 use rustc_data_structures::indexed_vec::Idx;
17
18 use base;
19 use common::{self, CrateContext, C_null};
20 use builder::Builder;
21 use value::Value;
22 use type_of;
23 use type_::Type;
24
25 use std::fmt;
26 use std::ptr;
27
28 use super::{MirContext, LocalRef};
29 use super::lvalue::{Alignment, LvalueRef};
30
31 /// The representation of a Rust value. The enum variant is in fact
32 /// uniquely determined by the value's type, but is kept as a
33 /// safety check.
34 #[derive(Copy, Clone)]
35 pub enum OperandValue {
36     /// A reference to the actual operand. The data is guaranteed
37     /// to be valid for the operand's lifetime.
38     Ref(ValueRef, Alignment),
39     /// A single LLVM value.
40     Immediate(ValueRef),
41     /// A pair of immediate LLVM values. Used by fat pointers too.
42     Pair(ValueRef, ValueRef)
43 }
44
45 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
46 /// its type.
47 ///
48 /// NOTE: unless you know a value's type exactly, you should not
49 /// generate LLVM opcodes acting on it and instead act via methods,
50 /// to avoid nasty edge cases. In particular, using `Builder.store`
51 /// directly is sure to cause problems -- use `MirContext.store_operand`
52 /// instead.
53 #[derive(Copy, Clone)]
54 pub struct OperandRef<'tcx> {
55     // The value.
56     pub val: OperandValue,
57
58     // The type of value being returned.
59     pub ty: Ty<'tcx>
60 }
61
62 impl<'tcx> fmt::Debug for OperandRef<'tcx> {
63     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64         match self.val {
65             OperandValue::Ref(r, align) => {
66                 write!(f, "OperandRef(Ref({:?}, {:?}) @ {:?})",
67                        Value(r), align, self.ty)
68             }
69             OperandValue::Immediate(i) => {
70                 write!(f, "OperandRef(Immediate({:?}) @ {:?})",
71                        Value(i), self.ty)
72             }
73             OperandValue::Pair(a, b) => {
74                 write!(f, "OperandRef(Pair({:?}, {:?}) @ {:?})",
75                        Value(a), Value(b), self.ty)
76             }
77         }
78     }
79 }
80
81 impl<'a, 'tcx> OperandRef<'tcx> {
82     pub fn new_zst(ccx: &CrateContext<'a, 'tcx>,
83                    ty: Ty<'tcx>) -> OperandRef<'tcx> {
84         assert!(common::type_is_zero_size(ccx, ty));
85         let llty = type_of::type_of(ccx, ty);
86         let val = if common::type_is_imm_pair(ccx, ty) {
87             let fields = llty.field_types();
88             OperandValue::Pair(C_null(fields[0]), C_null(fields[1]))
89         } else {
90             OperandValue::Immediate(C_null(llty))
91         };
92         OperandRef {
93             val: val,
94             ty: ty
95         }
96     }
97
98     /// Asserts that this operand refers to a scalar and returns
99     /// a reference to its value.
100     pub fn immediate(self) -> ValueRef {
101         match self.val {
102             OperandValue::Immediate(s) => s,
103             _ => bug!("not immediate: {:?}", self)
104         }
105     }
106
107     pub fn deref(self) -> LvalueRef<'tcx> {
108         let projected_ty = self.ty.builtin_deref(true, ty::NoPreference)
109             .unwrap().ty;
110         let (llptr, llextra) = match self.val {
111             OperandValue::Immediate(llptr) => (llptr, ptr::null_mut()),
112             OperandValue::Pair(llptr, llextra) => (llptr, llextra),
113             OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
114         };
115         LvalueRef {
116             llval: llptr,
117             llextra: llextra,
118             ty: LvalueTy::from_ty(projected_ty),
119             alignment: Alignment::AbiAligned,
120         }
121     }
122
123     /// If this operand is a Pair, we return an
124     /// Immediate aggregate with the two values.
125     pub fn pack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> {
126         if let OperandValue::Pair(a, b) = self.val {
127             // Reconstruct the immediate aggregate.
128             let llty = type_of::type_of(bcx.ccx, self.ty);
129             let mut llpair = common::C_undef(llty);
130             let elems = [a, b];
131             for i in 0..2 {
132                 let mut elem = elems[i];
133                 // Extend boolean i1's to i8.
134                 if common::val_ty(elem) == Type::i1(bcx.ccx) {
135                     elem = bcx.zext(elem, Type::i8(bcx.ccx));
136                 }
137                 llpair = bcx.insert_value(llpair, elem, i);
138             }
139             self.val = OperandValue::Immediate(llpair);
140         }
141         self
142     }
143
144     /// If this operand is a pair in an Immediate,
145     /// we return a Pair with the two halves.
146     pub fn unpack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> {
147         if let OperandValue::Immediate(llval) = self.val {
148             // Deconstruct the immediate aggregate.
149             if common::type_is_imm_pair(bcx.ccx, self.ty) {
150                 debug!("Operand::unpack_if_pair: unpacking {:?}", self);
151
152                 let mut a = bcx.extract_value(llval, 0);
153                 let mut b = bcx.extract_value(llval, 1);
154
155                 let pair_fields = common::type_pair_fields(bcx.ccx, self.ty);
156                 if let Some([a_ty, b_ty]) = pair_fields {
157                     if a_ty.is_bool() {
158                         a = bcx.trunc(a, Type::i1(bcx.ccx));
159                     }
160                     if b_ty.is_bool() {
161                         b = bcx.trunc(b, Type::i1(bcx.ccx));
162                     }
163                 }
164
165                 self.val = OperandValue::Pair(a, b);
166             }
167         }
168         self
169     }
170 }
171
172 impl<'a, 'tcx> MirContext<'a, 'tcx> {
173     pub fn trans_load(&mut self,
174                       bcx: &Builder<'a, 'tcx>,
175                       llval: ValueRef,
176                       align: Alignment,
177                       ty: Ty<'tcx>)
178                       -> OperandRef<'tcx>
179     {
180         debug!("trans_load: {:?} @ {:?}", Value(llval), ty);
181
182         let val = if common::type_is_fat_ptr(bcx.ccx, ty) {
183             let (lldata, llextra) = base::load_fat_ptr(bcx, llval, align, ty);
184             OperandValue::Pair(lldata, llextra)
185         } else if common::type_is_imm_pair(bcx.ccx, ty) {
186             let f_align = match *bcx.ccx.layout_of(ty) {
187                 Layout::Univariant { ref variant, .. } =>
188                     Alignment::from_packed(variant.packed) | align,
189                 _ => align
190             };
191             let [a_ty, b_ty] = common::type_pair_fields(bcx.ccx, ty).unwrap();
192             let a_ptr = bcx.struct_gep(llval, 0);
193             let b_ptr = bcx.struct_gep(llval, 1);
194
195             OperandValue::Pair(
196                 base::load_ty(bcx, a_ptr, f_align, a_ty),
197                 base::load_ty(bcx, b_ptr, f_align, b_ty)
198             )
199         } else if common::type_is_immediate(bcx.ccx, ty) {
200             OperandValue::Immediate(base::load_ty(bcx, llval, align, ty))
201         } else {
202             OperandValue::Ref(llval, align)
203         };
204
205         OperandRef { val: val, ty: ty }
206     }
207
208     pub fn trans_consume(&mut self,
209                          bcx: &Builder<'a, 'tcx>,
210                          lvalue: &mir::Lvalue<'tcx>)
211                          -> OperandRef<'tcx>
212     {
213         debug!("trans_consume(lvalue={:?})", lvalue);
214
215         // watch out for locals that do not have an
216         // alloca; they are handled somewhat differently
217         if let mir::Lvalue::Local(index) = *lvalue {
218             match self.locals[index] {
219                 LocalRef::Operand(Some(o)) => {
220                     return o;
221                 }
222                 LocalRef::Operand(None) => {
223                     bug!("use of {:?} before def", lvalue);
224                 }
225                 LocalRef::Lvalue(..) => {
226                     // use path below
227                 }
228             }
229         }
230
231         // Moves out of pair fields are trivial.
232         if let &mir::Lvalue::Projection(ref proj) = lvalue {
233             if let mir::Lvalue::Local(index) = proj.base {
234                 if let LocalRef::Operand(Some(o)) = self.locals[index] {
235                     match (o.val, &proj.elem) {
236                         (OperandValue::Pair(a, b),
237                          &mir::ProjectionElem::Field(ref f, ty)) => {
238                             let llval = [a, b][f.index()];
239                             let op = OperandRef {
240                                 val: OperandValue::Immediate(llval),
241                                 ty: self.monomorphize(&ty)
242                             };
243
244                             // Handle nested pairs.
245                             return op.unpack_if_pair(bcx);
246                         }
247                         _ => {}
248                     }
249                 }
250             }
251         }
252
253         // for most lvalues, to consume them we just load them
254         // out from their home
255         let tr_lvalue = self.trans_lvalue(bcx, lvalue);
256         let ty = tr_lvalue.ty.to_ty(bcx.tcx());
257         self.trans_load(bcx, tr_lvalue.llval, tr_lvalue.alignment, ty)
258     }
259
260     pub fn trans_operand(&mut self,
261                          bcx: &Builder<'a, 'tcx>,
262                          operand: &mir::Operand<'tcx>)
263                          -> OperandRef<'tcx>
264     {
265         debug!("trans_operand(operand={:?})", operand);
266
267         match *operand {
268             mir::Operand::Consume(ref lvalue) => {
269                 self.trans_consume(bcx, lvalue)
270             }
271
272             mir::Operand::Constant(ref constant) => {
273                 let val = self.trans_constant(&bcx, constant);
274                 let operand = val.to_operand(bcx.ccx);
275                 if let OperandValue::Ref(ptr, align) = operand.val {
276                     // If this is a OperandValue::Ref to an immediate constant, load it.
277                     self.trans_load(bcx, ptr, align, operand.ty)
278                 } else {
279                     operand
280                 }
281             }
282         }
283     }
284
285     pub fn store_operand(&mut self,
286                          bcx: &Builder<'a, 'tcx>,
287                          lldest: ValueRef,
288                          align: Option<u32>,
289                          operand: OperandRef<'tcx>) {
290         debug!("store_operand: operand={:?}, align={:?}", operand, align);
291         // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
292         // value is through `undef`, and store itself is useless.
293         if common::type_is_zero_size(bcx.ccx, operand.ty) {
294             return;
295         }
296         match operand.val {
297             OperandValue::Ref(r, Alignment::Packed) =>
298                 base::memcpy_ty(bcx, lldest, r, operand.ty, Some(1)),
299             OperandValue::Ref(r, Alignment::AbiAligned) =>
300                 base::memcpy_ty(bcx, lldest, r, operand.ty, align),
301             OperandValue::Immediate(s) => {
302                 bcx.store(base::from_immediate(bcx, s), lldest, align);
303             }
304             OperandValue::Pair(a, b) => {
305                 let f_align = match *bcx.ccx.layout_of(operand.ty) {
306                     Layout::Univariant { ref variant, .. } if variant.packed => {
307                         Some(1)
308                     }
309                     _ => align
310                 };
311
312                 let a = base::from_immediate(bcx, a);
313                 let b = base::from_immediate(bcx, b);
314                 bcx.store(a, bcx.struct_gep(lldest, 0), f_align);
315                 bcx.store(b, bcx.struct_gep(lldest, 1), f_align);
316             }
317         }
318     }
319 }