]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/operand.rs
78c83f200a517da5db04f9c48005422bd1483943
[rust.git] / src / librustc_codegen_llvm / 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::mir::interpret::ConstEvalErr;
13 use rustc::mir;
14 use rustc::mir::interpret::ConstValue;
15 use rustc::ty;
16 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
17 use rustc_data_structures::indexed_vec::Idx;
18 use rustc_data_structures::sync::Lrc;
19
20 use base;
21 use common::{CodegenCx, C_undef, C_usize};
22 use builder::{Builder, MemFlags};
23 use value::Value;
24 use type_of::LayoutLlvmExt;
25
26 use std::fmt;
27
28 use super::{FunctionCx, LocalRef};
29 use super::constant::scalar_to_llvm;
30 use super::place::PlaceRef;
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, Align),
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 impl fmt::Debug for OperandValue {
47     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48         match *self {
49             OperandValue::Ref(r, align) => {
50                 write!(f, "Ref({:?}, {:?})", Value(r), align)
51             }
52             OperandValue::Immediate(i) => {
53                 write!(f, "Immediate({:?})", Value(i))
54             }
55             OperandValue::Pair(a, b) => {
56                 write!(f, "Pair({:?}, {:?})", Value(a), Value(b))
57             }
58         }
59     }
60 }
61
62 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
63 /// its type.
64 ///
65 /// NOTE: unless you know a value's type exactly, you should not
66 /// generate LLVM opcodes acting on it and instead act via methods,
67 /// to avoid nasty edge cases. In particular, using `Builder::store`
68 /// directly is sure to cause problems -- use `OperandRef::store`
69 /// instead.
70 #[derive(Copy, Clone)]
71 pub struct OperandRef<'tcx> {
72     // The value.
73     pub val: OperandValue,
74
75     // The layout of value, based on its Rust type.
76     pub layout: TyLayout<'tcx>,
77 }
78
79 impl<'tcx> fmt::Debug for OperandRef<'tcx> {
80     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81         write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
82     }
83 }
84
85 impl<'a, 'tcx> OperandRef<'tcx> {
86     pub fn new_zst(cx: &CodegenCx<'a, 'tcx>,
87                    layout: TyLayout<'tcx>) -> OperandRef<'tcx> {
88         assert!(layout.is_zst());
89         OperandRef {
90             val: OperandValue::Immediate(C_undef(layout.immediate_llvm_type(cx))),
91             layout
92         }
93     }
94
95     pub fn from_const(bx: &Builder<'a, 'tcx>,
96                       val: &'tcx ty::Const<'tcx>)
97                       -> Result<OperandRef<'tcx>, Lrc<ConstEvalErr<'tcx>>> {
98         let layout = bx.cx.layout_of(val.ty);
99
100         if layout.is_zst() {
101             return Ok(OperandRef::new_zst(bx.cx, layout));
102         }
103
104         let val = match val.val {
105             ConstValue::Unevaluated(..) => bug!(),
106             ConstValue::Scalar(x) => {
107                 let scalar = match layout.abi {
108                     layout::Abi::Scalar(ref x) => x,
109                     _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
110                 };
111                 let llval = scalar_to_llvm(
112                     bx.cx,
113                     x,
114                     scalar,
115                     layout.immediate_llvm_type(bx.cx),
116                 );
117                 OperandValue::Immediate(llval)
118             },
119             ConstValue::ScalarPair(a, b) => {
120                 let (a_scalar, b_scalar) = match layout.abi {
121                     layout::Abi::ScalarPair(ref a, ref b) => (a, b),
122                     _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout)
123                 };
124                 let a_llval = scalar_to_llvm(
125                     bx.cx,
126                     a,
127                     a_scalar,
128                     layout.scalar_pair_element_llvm_type(bx.cx, 0, true),
129                 );
130                 let b_llval = scalar_to_llvm(
131                     bx.cx,
132                     b,
133                     b_scalar,
134                     layout.scalar_pair_element_llvm_type(bx.cx, 1, true),
135                 );
136                 OperandValue::Pair(a_llval, b_llval)
137             },
138             ConstValue::ByRef(alloc, offset) => {
139                 return Ok(PlaceRef::from_const_alloc(bx, layout, alloc, offset).load(bx));
140             },
141         };
142
143         Ok(OperandRef {
144             val,
145             layout
146         })
147     }
148
149     /// Asserts that this operand refers to a scalar and returns
150     /// a reference to its value.
151     pub fn immediate(self) -> ValueRef {
152         match self.val {
153             OperandValue::Immediate(s) => s,
154             _ => bug!("not immediate: {:?}", self)
155         }
156     }
157
158     pub fn deref(self, cx: &CodegenCx<'a, 'tcx>) -> PlaceRef<'tcx> {
159         let projected_ty = self.layout.ty.builtin_deref(true)
160             .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
161         let (llptr, llextra) = match self.val {
162             OperandValue::Immediate(llptr) => (llptr, 0 as *mut _),
163             OperandValue::Pair(llptr, llextra) => (llptr, llextra),
164             OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
165         };
166         let layout = cx.layout_of(projected_ty);
167         PlaceRef {
168             llval: llptr,
169             llextra,
170             layout,
171             align: layout.align,
172         }
173     }
174
175     /// If this operand is a `Pair`, we return an aggregate with the two values.
176     /// For other cases, see `immediate`.
177     pub fn immediate_or_packed_pair(self, bx: &Builder<'a, 'tcx>) -> ValueRef {
178         if let OperandValue::Pair(a, b) = self.val {
179             let llty = self.layout.llvm_type(bx.cx);
180             debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
181                    self, llty);
182             // Reconstruct the immediate aggregate.
183             let mut llpair = C_undef(llty);
184             llpair = bx.insert_value(llpair, base::from_immediate(bx, a), 0);
185             llpair = bx.insert_value(llpair, base::from_immediate(bx, b), 1);
186             llpair
187         } else {
188             self.immediate()
189         }
190     }
191
192     /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
193     pub fn from_immediate_or_packed_pair(bx: &Builder<'a, 'tcx>,
194                                          llval: ValueRef,
195                                          layout: TyLayout<'tcx>)
196                                          -> OperandRef<'tcx> {
197         let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
198             debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
199                     llval, layout);
200
201             // Deconstruct the immediate aggregate.
202             let a_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 0), a);
203             let b_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 1), b);
204             OperandValue::Pair(a_llval, b_llval)
205         } else {
206             OperandValue::Immediate(llval)
207         };
208         OperandRef { val, layout }
209     }
210
211     pub fn extract_field(&self, bx: &Builder<'a, 'tcx>, i: usize) -> OperandRef<'tcx> {
212         let field = self.layout.field(bx.cx, i);
213         let offset = self.layout.fields.offset(i);
214
215         let mut val = match (self.val, &self.layout.abi) {
216             // If the field is ZST, it has no data.
217             _ if field.is_zst() => {
218                 return OperandRef::new_zst(bx.cx, field);
219             }
220
221             // Newtype of a scalar, scalar pair or vector.
222             (OperandValue::Immediate(_), _) |
223             (OperandValue::Pair(..), _) if field.size == self.layout.size => {
224                 assert_eq!(offset.bytes(), 0);
225                 self.val
226             }
227
228             // Extract a scalar component from a pair.
229             (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
230                 if offset.bytes() == 0 {
231                     assert_eq!(field.size, a.value.size(bx.cx));
232                     OperandValue::Immediate(a_llval)
233                 } else {
234                     assert_eq!(offset, a.value.size(bx.cx)
235                         .abi_align(b.value.align(bx.cx)));
236                     assert_eq!(field.size, b.value.size(bx.cx));
237                     OperandValue::Immediate(b_llval)
238                 }
239             }
240
241             // `#[repr(simd)]` types are also immediate.
242             (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
243                 OperandValue::Immediate(
244                     bx.extract_element(llval, C_usize(bx.cx, i as u64)))
245             }
246
247             _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
248         };
249
250         // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
251         match val {
252             OperandValue::Immediate(ref mut llval) => {
253                 *llval = bx.bitcast(*llval, field.immediate_llvm_type(bx.cx));
254             }
255             OperandValue::Pair(ref mut a, ref mut b) => {
256                 *a = bx.bitcast(*a, field.scalar_pair_element_llvm_type(bx.cx, 0, true));
257                 *b = bx.bitcast(*b, field.scalar_pair_element_llvm_type(bx.cx, 1, true));
258             }
259             OperandValue::Ref(..) => bug!()
260         }
261
262         OperandRef {
263             val,
264             layout: field
265         }
266     }
267 }
268
269 impl<'a, 'tcx> OperandValue {
270     pub fn store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
271         self.store_with_flags(bx, dest, MemFlags::empty());
272     }
273
274     pub fn volatile_store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
275         self.store_with_flags(bx, dest, MemFlags::VOLATILE);
276     }
277
278     pub fn unaligned_volatile_store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
279         self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
280     }
281
282     pub fn nontemporal_store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
283         self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
284     }
285
286     fn store_with_flags(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>, flags: MemFlags) {
287         debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
288         // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
289         // value is through `undef`, and store itself is useless.
290         if dest.layout.is_zst() {
291             return;
292         }
293         match self {
294             OperandValue::Ref(r, source_align) => {
295                 base::memcpy_ty(bx, dest.llval, r, dest.layout,
296                                 source_align.min(dest.align), flags)
297             }
298             OperandValue::Immediate(s) => {
299                 let val = base::from_immediate(bx, s);
300                 bx.store_with_flags(val, dest.llval, dest.align, flags);
301             }
302             OperandValue::Pair(a, b) => {
303                 for (i, &x) in [a, b].iter().enumerate() {
304                     let llptr = bx.struct_gep(dest.llval, i as u64);
305                     let val = base::from_immediate(bx, x);
306                     bx.store_with_flags(val, llptr, dest.align, flags);
307                 }
308             }
309         }
310     }
311 }
312
313 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
314     fn maybe_codegen_consume_direct(&mut self,
315                                   bx: &Builder<'a, 'tcx>,
316                                   place: &mir::Place<'tcx>)
317                                    -> Option<OperandRef<'tcx>>
318     {
319         debug!("maybe_codegen_consume_direct(place={:?})", place);
320
321         // watch out for locals that do not have an
322         // alloca; they are handled somewhat differently
323         if let mir::Place::Local(index) = *place {
324             match self.locals[index] {
325                 LocalRef::Operand(Some(o)) => {
326                     return Some(o);
327                 }
328                 LocalRef::Operand(None) => {
329                     bug!("use of {:?} before def", place);
330                 }
331                 LocalRef::Place(..) => {
332                     // use path below
333                 }
334             }
335         }
336
337         // Moves out of scalar and scalar pair fields are trivial.
338         if let &mir::Place::Projection(ref proj) = place {
339             if let Some(o) = self.maybe_codegen_consume_direct(bx, &proj.base) {
340                 match proj.elem {
341                     mir::ProjectionElem::Field(ref f, _) => {
342                         return Some(o.extract_field(bx, f.index()));
343                     }
344                     mir::ProjectionElem::Index(_) |
345                     mir::ProjectionElem::ConstantIndex { .. } => {
346                         // ZSTs don't require any actual memory access.
347                         // FIXME(eddyb) deduplicate this with the identical
348                         // checks in `codegen_consume` and `extract_field`.
349                         let elem = o.layout.field(bx.cx, 0);
350                         if elem.is_zst() {
351                             return Some(OperandRef::new_zst(bx.cx, elem));
352                         }
353                     }
354                     _ => {}
355                 }
356             }
357         }
358
359         None
360     }
361
362     pub fn codegen_consume(&mut self,
363                          bx: &Builder<'a, 'tcx>,
364                          place: &mir::Place<'tcx>)
365                          -> OperandRef<'tcx>
366     {
367         debug!("codegen_consume(place={:?})", place);
368
369         let ty = self.monomorphized_place_ty(place);
370         let layout = bx.cx.layout_of(ty);
371
372         // ZSTs don't require any actual memory access.
373         if layout.is_zst() {
374             return OperandRef::new_zst(bx.cx, layout);
375         }
376
377         if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
378             return o;
379         }
380
381         // for most places, to consume them we just load them
382         // out from their home
383         self.codegen_place(bx, place).load(bx)
384     }
385
386     pub fn codegen_operand(&mut self,
387                          bx: &Builder<'a, 'tcx>,
388                          operand: &mir::Operand<'tcx>)
389                          -> OperandRef<'tcx>
390     {
391         debug!("codegen_operand(operand={:?})", operand);
392
393         match *operand {
394             mir::Operand::Copy(ref place) |
395             mir::Operand::Move(ref place) => {
396                 self.codegen_consume(bx, place)
397             }
398
399             mir::Operand::Constant(ref constant) => {
400                 let ty = self.monomorphize(&constant.ty);
401                 self.eval_mir_constant(bx, constant)
402                     .and_then(|c| OperandRef::from_const(bx, c))
403                     .unwrap_or_else(|err| {
404                         err.report_as_error(
405                             bx.tcx().at(constant.span),
406                             "could not evaluate constant operand",
407                         );
408                         // Allow RalfJ to sleep soundly knowing that even refactorings that remove
409                         // the above error (or silence it under some conditions) will not cause UB
410                         let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
411                         bx.call(fnname, &[], None);
412                         // We've errored, so we don't have to produce working code.
413                         let layout = bx.cx.layout_of(ty);
414                         PlaceRef::new_sized(
415                             C_undef(layout.llvm_type(bx.cx).ptr_to()),
416                             layout,
417                             layout.align,
418                         ).load(bx)
419                     })
420             }
421         }
422     }
423 }