]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/operand.rs
Auto merge of #42504 - michaelwoerister:hash-dep-nodes-prep, r=nikomatsakis
[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 layout = ccx.layout_of(ty);
89             let (ix0, ix1) = if let Layout::Univariant { ref variant, .. } = *layout {
90                 (adt::struct_llfields_index(variant, 0),
91                 adt::struct_llfields_index(variant, 1))
92             } else {
93                 (0, 1)
94             };
95             let fields = llty.field_types();
96             OperandValue::Pair(C_null(fields[ix0]), C_null(fields[ix1]))
97         } else {
98             OperandValue::Immediate(C_null(llty))
99         };
100         OperandRef {
101             val: val,
102             ty: ty
103         }
104     }
105
106     /// Asserts that this operand refers to a scalar and returns
107     /// a reference to its value.
108     pub fn immediate(self) -> ValueRef {
109         match self.val {
110             OperandValue::Immediate(s) => s,
111             _ => bug!("not immediate: {:?}", self)
112         }
113     }
114
115     pub fn deref(self) -> LvalueRef<'tcx> {
116         let projected_ty = self.ty.builtin_deref(true, ty::NoPreference)
117             .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
118         let (llptr, llextra) = match self.val {
119             OperandValue::Immediate(llptr) => (llptr, ptr::null_mut()),
120             OperandValue::Pair(llptr, llextra) => (llptr, llextra),
121             OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
122         };
123         LvalueRef {
124             llval: llptr,
125             llextra: llextra,
126             ty: LvalueTy::from_ty(projected_ty),
127             alignment: Alignment::AbiAligned,
128         }
129     }
130
131     /// If this operand is a Pair, we return an
132     /// Immediate aggregate with the two values.
133     pub fn pack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> {
134         if let OperandValue::Pair(a, b) = self.val {
135             // Reconstruct the immediate aggregate.
136             let llty = type_of::type_of(bcx.ccx, self.ty);
137             let mut llpair = common::C_undef(llty);
138             let elems = [a, b];
139             for i in 0..2 {
140                 let mut elem = elems[i];
141                 // Extend boolean i1's to i8.
142                 if common::val_ty(elem) == Type::i1(bcx.ccx) {
143                     elem = bcx.zext(elem, Type::i8(bcx.ccx));
144                 }
145                 let layout = bcx.ccx.layout_of(self.ty);
146                 let i = if let Layout::Univariant { ref variant, .. } = *layout {
147                     adt::struct_llfields_index(variant, i)
148                 } else {
149                     i
150                 };
151                 llpair = bcx.insert_value(llpair, elem, i);
152             }
153             self.val = OperandValue::Immediate(llpair);
154         }
155         self
156     }
157
158     /// If this operand is a pair in an Immediate,
159     /// we return a Pair with the two halves.
160     pub fn unpack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> {
161         if let OperandValue::Immediate(llval) = self.val {
162             // Deconstruct the immediate aggregate.
163             if common::type_is_imm_pair(bcx.ccx, self.ty) {
164                 debug!("Operand::unpack_if_pair: unpacking {:?}", self);
165
166                 let layout = bcx.ccx.layout_of(self.ty);
167                 let (ix0, ix1) = if let Layout::Univariant { ref variant, .. } = *layout {
168                     (adt::struct_llfields_index(variant, 0),
169                     adt::struct_llfields_index(variant, 1))
170                 } else {
171                     (0, 1)
172                 };
173
174                 let mut a = bcx.extract_value(llval, ix0);
175                 let mut b = bcx.extract_value(llval, ix1);
176
177                 let pair_fields = common::type_pair_fields(bcx.ccx, self.ty);
178                 if let Some([a_ty, b_ty]) = pair_fields {
179                     if a_ty.is_bool() {
180                         a = bcx.trunc(a, Type::i1(bcx.ccx));
181                     }
182                     if b_ty.is_bool() {
183                         b = bcx.trunc(b, Type::i1(bcx.ccx));
184                     }
185                 }
186
187                 self.val = OperandValue::Pair(a, b);
188             }
189         }
190         self
191     }
192 }
193
194 impl<'a, 'tcx> MirContext<'a, 'tcx> {
195     pub fn trans_load(&mut self,
196                       bcx: &Builder<'a, 'tcx>,
197                       llval: ValueRef,
198                       align: Alignment,
199                       ty: Ty<'tcx>)
200                       -> OperandRef<'tcx>
201     {
202         debug!("trans_load: {:?} @ {:?}", Value(llval), ty);
203
204         let val = if common::type_is_fat_ptr(bcx.ccx, ty) {
205             let (lldata, llextra) = base::load_fat_ptr(bcx, llval, align, ty);
206             OperandValue::Pair(lldata, llextra)
207         } else if common::type_is_imm_pair(bcx.ccx, ty) {
208             let (ix0, ix1, f_align) = match *bcx.ccx.layout_of(ty) {
209                 Layout::Univariant { ref variant, .. } => {
210                     (adt::struct_llfields_index(variant, 0),
211                     adt::struct_llfields_index(variant, 1),
212                     Alignment::from_packed(variant.packed) | align)
213                 },
214                 _ => (0, 1, align)
215             };
216             let [a_ty, b_ty] = common::type_pair_fields(bcx.ccx, ty).unwrap();
217             let a_ptr = bcx.struct_gep(llval, ix0);
218             let b_ptr = bcx.struct_gep(llval, ix1);
219
220             OperandValue::Pair(
221                 base::load_ty(bcx, a_ptr, f_align, a_ty),
222                 base::load_ty(bcx, b_ptr, f_align, b_ty)
223             )
224         } else if common::type_is_immediate(bcx.ccx, ty) {
225             OperandValue::Immediate(base::load_ty(bcx, llval, align, ty))
226         } else {
227             OperandValue::Ref(llval, align)
228         };
229
230         OperandRef { val: val, ty: ty }
231     }
232
233     pub fn trans_consume(&mut self,
234                          bcx: &Builder<'a, 'tcx>,
235                          lvalue: &mir::Lvalue<'tcx>)
236                          -> OperandRef<'tcx>
237     {
238         debug!("trans_consume(lvalue={:?})", lvalue);
239
240         // watch out for locals that do not have an
241         // alloca; they are handled somewhat differently
242         if let mir::Lvalue::Local(index) = *lvalue {
243             match self.locals[index] {
244                 LocalRef::Operand(Some(o)) => {
245                     return o;
246                 }
247                 LocalRef::Operand(None) => {
248                     bug!("use of {:?} before def", lvalue);
249                 }
250                 LocalRef::Lvalue(..) => {
251                     // use path below
252                 }
253             }
254         }
255
256         // Moves out of pair fields are trivial.
257         if let &mir::Lvalue::Projection(ref proj) = lvalue {
258             if let mir::Lvalue::Local(index) = proj.base {
259                 if let LocalRef::Operand(Some(o)) = self.locals[index] {
260                     match (o.val, &proj.elem) {
261                         (OperandValue::Pair(a, b),
262                          &mir::ProjectionElem::Field(ref f, ty)) => {
263                             let llval = [a, b][f.index()];
264                             let op = OperandRef {
265                                 val: OperandValue::Immediate(llval),
266                                 ty: self.monomorphize(&ty)
267                             };
268
269                             // Handle nested pairs.
270                             return op.unpack_if_pair(bcx);
271                         }
272                         _ => {}
273                     }
274                 }
275             }
276         }
277
278         // for most lvalues, to consume them we just load them
279         // out from their home
280         let tr_lvalue = self.trans_lvalue(bcx, lvalue);
281         let ty = tr_lvalue.ty.to_ty(bcx.tcx());
282         self.trans_load(bcx, tr_lvalue.llval, tr_lvalue.alignment, ty)
283     }
284
285     pub fn trans_operand(&mut self,
286                          bcx: &Builder<'a, 'tcx>,
287                          operand: &mir::Operand<'tcx>)
288                          -> OperandRef<'tcx>
289     {
290         debug!("trans_operand(operand={:?})", operand);
291
292         match *operand {
293             mir::Operand::Consume(ref lvalue) => {
294                 self.trans_consume(bcx, lvalue)
295             }
296
297             mir::Operand::Constant(ref constant) => {
298                 let val = self.trans_constant(&bcx, constant);
299                 let operand = val.to_operand(bcx.ccx);
300                 if let OperandValue::Ref(ptr, align) = operand.val {
301                     // If this is a OperandValue::Ref to an immediate constant, load it.
302                     self.trans_load(bcx, ptr, align, operand.ty)
303                 } else {
304                     operand
305                 }
306             }
307         }
308     }
309
310     pub fn store_operand(&mut self,
311                          bcx: &Builder<'a, 'tcx>,
312                          lldest: ValueRef,
313                          align: Option<u32>,
314                          operand: OperandRef<'tcx>) {
315         debug!("store_operand: operand={:?}, align={:?}", operand, align);
316         // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
317         // value is through `undef`, and store itself is useless.
318         if common::type_is_zero_size(bcx.ccx, operand.ty) {
319             return;
320         }
321         match operand.val {
322             OperandValue::Ref(r, Alignment::Packed) =>
323                 base::memcpy_ty(bcx, lldest, r, operand.ty, Some(1)),
324             OperandValue::Ref(r, Alignment::AbiAligned) =>
325                 base::memcpy_ty(bcx, lldest, r, operand.ty, align),
326             OperandValue::Immediate(s) => {
327                 bcx.store(base::from_immediate(bcx, s), lldest, align);
328             }
329             OperandValue::Pair(a, b) => {
330                 let (ix0, ix1, f_align) = match *bcx.ccx.layout_of(operand.ty) {
331                     Layout::Univariant { ref variant, .. } => {
332                         (adt::struct_llfields_index(variant, 0),
333                         adt::struct_llfields_index(variant, 1),
334                         if variant.packed { Some(1) } else { None })
335                     }
336                     _ => (0, 1, align)
337                 };
338
339                 let a = base::from_immediate(bcx, a);
340                 let b = base::from_immediate(bcx, b);
341
342                 // See comment above about zero-sized values.
343                 let (a_zst, b_zst) = common::type_pair_fields(bcx.ccx, operand.ty)
344                     .map_or((false, false), |[a_ty, b_ty]| {
345                         (common::type_is_zero_size(bcx.ccx, a_ty),
346                          common::type_is_zero_size(bcx.ccx, b_ty))
347                     });
348
349                 if !a_zst {
350                     bcx.store(a, bcx.struct_gep(lldest, ix0), f_align);
351                 }
352                 if !b_zst {
353                     bcx.store(b, bcx.struct_gep(lldest, ix1), f_align);
354                 }
355             }
356         }
357     }
358 }