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