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