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