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