]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/mir/operand.rs
All Builder methods now take &mut self instead of &self
[rust.git] / src / librustc_codegen_ssa / 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::{ConstValue, ErrorHandled};
12 use rustc::mir;
13 use rustc::ty;
14 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
15
16 use base;
17 use MemFlags;
18 use glue;
19
20 use interfaces::*;
21
22 use std::fmt;
23
24 use super::{FunctionCx, LocalRef};
25 use super::place::PlaceRef;
26
27 /// The representation of a Rust value. The enum variant is in fact
28 /// uniquely determined by the value's type, but is kept as a
29 /// safety check.
30 #[derive(Copy, Clone, Debug)]
31 pub enum OperandValue<V> {
32     /// A reference to the actual operand. The data is guaranteed
33     /// to be valid for the operand's lifetime.
34     /// The second value, if any, is the extra data (vtable or length)
35     /// which indicates that it refers to an unsized rvalue.
36     Ref(V, Option<V>, Align),
37     /// A single LLVM value.
38     Immediate(V),
39     /// A pair of immediate LLVM values. Used by fat pointers too.
40     Pair(V, V)
41 }
42
43 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
44 /// its type.
45 ///
46 /// NOTE: unless you know a value's type exactly, you should not
47 /// generate LLVM opcodes acting on it and instead act via methods,
48 /// to avoid nasty edge cases. In particular, using `Builder::store`
49 /// directly is sure to cause problems -- use `OperandRef::store`
50 /// instead.
51 #[derive(Copy, Clone)]
52 pub struct OperandRef<'tcx, V> {
53     // The value.
54     pub val: OperandValue<V>,
55
56     // The layout of value, based on its Rust type.
57     pub layout: TyLayout<'tcx>,
58 }
59
60 impl<V: CodegenObject> fmt::Debug for OperandRef<'tcx, V> {
61     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62         write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
63     }
64 }
65
66 impl<'a, 'tcx: 'a, V: CodegenObject> OperandRef<'tcx, V> {
67     pub fn new_zst<Cx: CodegenMethods<'tcx, Value = V>>(
68         cx: &Cx,
69         layout: TyLayout<'tcx>
70     ) -> OperandRef<'tcx, V> {
71         assert!(layout.is_zst());
72         OperandRef {
73             val: OperandValue::Immediate(cx.const_undef(cx.immediate_backend_type(layout))),
74             layout
75         }
76     }
77
78     pub fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
79         bx: &mut Bx,
80         val: &'tcx ty::Const<'tcx>
81     ) -> Result<Self, ErrorHandled> {
82         let layout = bx.cx().layout_of(val.ty);
83
84         if layout.is_zst() {
85             return Ok(OperandRef::new_zst(bx.cx(), layout));
86         }
87
88         let val = match val.val {
89             ConstValue::Unevaluated(..) => bug!(),
90             ConstValue::Scalar(x) => {
91                 let scalar = match layout.abi {
92                     layout::Abi::Scalar(ref x) => x,
93                     _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
94                 };
95                 let llval = bx.cx().scalar_to_backend(
96                     x,
97                     scalar,
98                     bx.cx().immediate_backend_type(layout),
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 = bx.cx().scalar_to_backend(
108                     a,
109                     a_scalar,
110                     bx.cx().scalar_pair_element_backend_type(layout, 0, true),
111                 );
112                 let b_llval = bx.cx().scalar_to_backend(
113                     b,
114                     b_scalar,
115                     bx.cx().scalar_pair_element_backend_type(layout, 1, true),
116                 );
117                 OperandValue::Pair(a_llval, b_llval)
118             },
119             ConstValue::ByRef(_, alloc, offset) => {
120                 return Ok(bx.load_operand(bx.cx().from_const_alloc(layout, alloc, offset)));
121             },
122         };
123
124         Ok(OperandRef {
125             val,
126             layout
127         })
128     }
129
130     /// Asserts that this operand refers to a scalar and returns
131     /// a reference to its value.
132     pub fn immediate(self) -> V {
133         match self.val {
134             OperandValue::Immediate(s) => s,
135             _ => bug!("not immediate: {:?}", self)
136         }
137     }
138
139     pub fn deref<Cx: CodegenMethods<'tcx, Value = V>>(
140         self,
141         cx: &Cx
142     ) -> PlaceRef<'tcx, V> {
143         let projected_ty = self.layout.ty.builtin_deref(true)
144             .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
145         let (llptr, llextra) = match self.val {
146             OperandValue::Immediate(llptr) => (llptr, None),
147             OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
148             OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
149         };
150         let layout = cx.layout_of(projected_ty);
151         PlaceRef {
152             llval: llptr,
153             llextra,
154             layout,
155             align: layout.align,
156         }
157     }
158
159     /// If this operand is a `Pair`, we return an aggregate with the two values.
160     /// For other cases, see `immediate`.
161     pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
162         self,
163         bx: &mut Bx
164     ) -> V {
165         if let OperandValue::Pair(a, b) = self.val {
166             let llty = bx.cx().backend_type(self.layout);
167             debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
168                    self, llty);
169             // Reconstruct the immediate aggregate.
170             let mut llpair = bx.cx().const_undef(llty);
171             let imm_a = base::from_immediate(bx, a);
172             let imm_b = base::from_immediate(bx, b);
173             llpair = bx.insert_value(llpair, imm_a, 0);
174             llpair = bx.insert_value(llpair, imm_b, 1);
175             llpair
176         } else {
177             self.immediate()
178         }
179     }
180
181     /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
182     pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
183         bx: &mut Bx,
184         llval: V,
185         layout: TyLayout<'tcx>
186     ) -> Self {
187         let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
188             debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
189                     llval, layout);
190
191             // Deconstruct the immediate aggregate.
192             let a_llval = bx.extract_value(llval, 0);
193             let a_llval = base::to_immediate_scalar(bx, a_llval, a);
194             let b_llval = bx.extract_value(llval, 1);
195             let b_llval = base::to_immediate_scalar(bx, b_llval, b);
196             OperandValue::Pair(a_llval, b_llval)
197         } else {
198             OperandValue::Immediate(llval)
199         };
200         OperandRef { val, layout }
201     }
202
203     pub fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
204         &self,
205         bx: &mut Bx,
206         i: usize
207     ) -> Self {
208         let field = self.layout.field(bx.cx(), i);
209         let offset = self.layout.fields.offset(i);
210
211         let mut val = match (self.val, &self.layout.abi) {
212             // If the field is ZST, it has no data.
213             _ if field.is_zst() => {
214                 return OperandRef::new_zst(bx.cx(), field);
215             }
216
217             // Newtype of a scalar, scalar pair or vector.
218             (OperandValue::Immediate(_), _) |
219             (OperandValue::Pair(..), _) if field.size == self.layout.size => {
220                 assert_eq!(offset.bytes(), 0);
221                 self.val
222             }
223
224             // Extract a scalar component from a pair.
225             (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
226                 if offset.bytes() == 0 {
227                     assert_eq!(field.size, a.value.size(bx.cx()));
228                     OperandValue::Immediate(a_llval)
229                 } else {
230                     assert_eq!(offset, a.value.size(bx.cx())
231                         .abi_align(b.value.align(bx.cx())));
232                     assert_eq!(field.size, b.value.size(bx.cx()));
233                     OperandValue::Immediate(b_llval)
234                 }
235             }
236
237             // `#[repr(simd)]` types are also immediate.
238             (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
239                 OperandValue::Immediate(
240                     bx.extract_element(llval, bx.cx().const_usize(i as u64)))
241             }
242
243             _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
244         };
245
246         // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
247         match val {
248             OperandValue::Immediate(ref mut llval) => {
249                 *llval = bx.bitcast(*llval, bx.cx().immediate_backend_type(field));
250             }
251             OperandValue::Pair(ref mut a, ref mut b) => {
252                 *a = bx.bitcast(*a, bx.cx().scalar_pair_element_backend_type(field, 0, true));
253                 *b = bx.bitcast(*b, bx.cx().scalar_pair_element_backend_type(field, 1, true));
254             }
255             OperandValue::Ref(..) => bug!()
256         }
257
258         OperandRef {
259             val,
260             layout: field
261         }
262     }
263 }
264
265 impl<'a, 'tcx: 'a, V: CodegenObject> OperandValue<V> {
266     pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
267         self,
268         bx: &mut Bx,
269         dest: PlaceRef<'tcx, V>
270     ) {
271         self.store_with_flags(bx, dest, MemFlags::empty());
272     }
273
274     pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
275         self,
276         bx: &mut Bx,
277         dest: PlaceRef<'tcx, V>
278     ) {
279         self.store_with_flags(bx, dest, MemFlags::VOLATILE);
280     }
281
282     pub fn unaligned_volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
283         self,
284         bx: &mut Bx,
285         dest: PlaceRef<'tcx, V>,
286     ) {
287         self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
288     }
289
290     pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
291         self,
292         bx: &mut Bx,
293         dest: PlaceRef<'tcx, V>
294     ) {
295         self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
296     }
297
298     fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
299         self,
300         bx: &mut Bx,
301         dest: PlaceRef<'tcx, V>,
302         flags: MemFlags,
303     ) {
304         debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
305         // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
306         // value is through `undef`, and store itself is useless.
307         if dest.layout.is_zst() {
308             return;
309         }
310         match self {
311             OperandValue::Ref(r, None, source_align) => {
312                 base::memcpy_ty(bx, dest.llval, dest.align, r, source_align,
313                                 dest.layout, flags)
314             }
315             OperandValue::Ref(_, Some(_), _) => {
316                 bug!("cannot directly store unsized values");
317             }
318             OperandValue::Immediate(s) => {
319                 let val = base::from_immediate(bx, s);
320                 bx.store_with_flags(val, dest.llval, dest.align, flags);
321             }
322             OperandValue::Pair(a, b) => {
323                 for (i, &x) in [a, b].iter().enumerate() {
324                     let llptr = bx.struct_gep(dest.llval, i as u64);
325                     let val = base::from_immediate(bx, x);
326                     bx.store_with_flags(val, llptr, dest.align, flags);
327                 }
328             }
329         }
330     }
331     pub fn store_unsized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
332         self,
333         bx: &mut Bx,
334         indirect_dest: PlaceRef<'tcx, V>
335     ) {
336         debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
337         let flags = MemFlags::empty();
338
339         // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
340         let unsized_ty = indirect_dest.layout.ty.builtin_deref(true)
341             .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest)).ty;
342
343         let (llptr, llextra) =
344             if let OperandValue::Ref(llptr, Some(llextra), _) = self {
345                 (llptr, llextra)
346             } else {
347                 bug!("store_unsized called with a sized value")
348             };
349
350         // FIXME: choose an appropriate alignment, or use dynamic align somehow
351         let max_align = Align::from_bits(128, 128).unwrap();
352         let min_align = Align::from_bits(8, 8).unwrap();
353
354         // Allocate an appropriate region on the stack, and copy the value into it
355         let (llsize, _) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
356         let lldst = bx.array_alloca(bx.cx().type_i8(), llsize, "unsized_tmp", max_align);
357         bx.memcpy(lldst, max_align, llptr, min_align, llsize, flags);
358
359         // Store the allocated region and the extra to the indirect place.
360         let indirect_operand = OperandValue::Pair(lldst, llextra);
361         indirect_operand.store(bx, indirect_dest);
362     }
363 }
364
365 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
366     fn maybe_codegen_consume_direct(
367         &mut self,
368         bx: &mut Bx,
369         place: &mir::Place<'tcx>
370     ) -> Option<OperandRef<'tcx, Bx::Value>> {
371         debug!("maybe_codegen_consume_direct(place={:?})", place);
372
373         // watch out for locals that do not have an
374         // alloca; they are handled somewhat differently
375         if let mir::Place::Local(index) = *place {
376             match self.locals[index] {
377                 LocalRef::Operand(Some(o)) => {
378                     return Some(o);
379                 }
380                 LocalRef::Operand(None) => {
381                     bug!("use of {:?} before def", place);
382                 }
383                 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
384                     // use path below
385                 }
386             }
387         }
388
389         // Moves out of scalar and scalar pair fields are trivial.
390         if let &mir::Place::Projection(ref proj) = place {
391             if let Some(o) = self.maybe_codegen_consume_direct(bx, &proj.base) {
392                 match proj.elem {
393                     mir::ProjectionElem::Field(ref f, _) => {
394                         return Some(o.extract_field(bx, f.index()));
395                     }
396                     mir::ProjectionElem::Index(_) |
397                     mir::ProjectionElem::ConstantIndex { .. } => {
398                         // ZSTs don't require any actual memory access.
399                         // FIXME(eddyb) deduplicate this with the identical
400                         // checks in `codegen_consume` and `extract_field`.
401                         let elem = o.layout.field(bx.cx(), 0);
402                         if elem.is_zst() {
403                             return Some(OperandRef::new_zst(bx.cx(), elem));
404                         }
405                     }
406                     _ => {}
407                 }
408             }
409         }
410
411         None
412     }
413
414     pub fn codegen_consume(
415         &mut self,
416         bx: &mut Bx,
417         place: &mir::Place<'tcx>
418     ) -> OperandRef<'tcx, Bx::Value> {
419         debug!("codegen_consume(place={:?})", place);
420
421         let ty = self.monomorphized_place_ty(place);
422         let layout = bx.cx().layout_of(ty);
423
424         // ZSTs don't require any actual memory access.
425         if layout.is_zst() {
426             return OperandRef::new_zst(bx.cx(), layout);
427         }
428
429         if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
430             return o;
431         }
432
433         // for most places, to consume them we just load them
434         // out from their home
435         let place = self.codegen_place(bx, place);
436         bx.load_operand(place)
437     }
438
439     pub fn codegen_operand(
440         &mut self,
441         bx: &mut Bx,
442         operand: &mir::Operand<'tcx>
443     ) -> OperandRef<'tcx, Bx::Value> {
444         debug!("codegen_operand(operand={:?})", operand);
445
446         match *operand {
447             mir::Operand::Copy(ref place) |
448             mir::Operand::Move(ref place) => {
449                 self.codegen_consume(bx, place)
450             }
451
452             mir::Operand::Constant(ref constant) => {
453                 let ty = self.monomorphize(&constant.ty);
454                 self.eval_mir_constant(bx, constant)
455                     .and_then(|c| OperandRef::from_const(bx, c))
456                     .unwrap_or_else(|err| {
457                         match err {
458                             // errored or at least linted
459                             ErrorHandled::Reported => {},
460                             ErrorHandled::TooGeneric => {
461                                 bug!("codgen encountered polymorphic constant")
462                             },
463                         }
464                         // Allow RalfJ to sleep soundly knowing that even refactorings that remove
465                         // the above error (or silence it under some conditions) will not cause UB
466                         let fnname = bx.cx().get_intrinsic(&("llvm.trap"));
467                         bx.call(fnname, &[], None);
468                         // We've errored, so we don't have to produce working code.
469                         let layout = bx.cx().layout_of(ty);
470                         bx.load_operand(PlaceRef::new_sized(
471                             bx.cx().const_undef(bx.cx().type_ptr_to(bx.cx().backend_type(layout))),
472                             layout,
473                             layout.align,
474                         ))
475                     })
476             }
477         }
478     }
479 }