operand.rs 17.0 KB
Newer Older
1
use super::place::PlaceRef;
M
Mark Rousskov 已提交
2
use super::{FunctionCx, LocalRef};
3

4
use crate::base;
T
Taiki Endo 已提交
5 6
use crate::glue;
use crate::traits::*;
M
Mark Rousskov 已提交
7
use crate::MemFlags;
8

M
Mazdak Farrokhzad 已提交
9
use rustc_middle::mir;
10
use rustc_middle::mir::interpret::{ConstValue, Pointer, Scalar};
11
use rustc_middle::ty::layout::TyAndLayout;
M
Mazdak Farrokhzad 已提交
12
use rustc_middle::ty::Ty;
13
use rustc_target::abi::{Abi, Align, LayoutOf, Size};
14

15
use std::fmt;
16

A
Ariel Ben-Yehuda 已提交
17 18
/// The representation of a Rust value. The enum variant is in fact
/// 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 23
    /// A reference to the actual operand. The data is guaranteed
    /// to be valid for the operand's lifetime.
24 25
    /// The second value, if any, is the extra data (vtable or length)
    /// 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.
M
Mark Rousskov 已提交
30
    Pair(V, V),
31 32
}

A
Ariel Ben-Yehuda 已提交
33 34 35 36 37
/// An `OperandRef` is an "SSA" reference to a Rust value, along with
/// its type.
///
/// NOTE: unless you know a value's type exactly, you should not
/// generate LLVM opcodes acting on it and instead act via methods,
38 39
/// to avoid nasty edge cases. In particular, using `Builder::store`
/// directly is sure to cause problems -- use `OperandRef::store`
40
/// instead.
41
#[derive(Copy, Clone)]
42
pub struct OperandRef<'tcx, V> {
A
Ariel Ben-Yehuda 已提交
43
    // The value.
44
    pub val: OperandValue<V>,
45

46
    // The layout of value, based on its Rust type.
47
    pub layout: TyAndLayout<'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, V: CodegenObject> OperandRef<'tcx, V> {
57 58
    pub fn new_zst<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
        bx: &mut Bx,
59
        layout: TyAndLayout<'tcx>,
60
    ) -> OperandRef<'tcx, V> {
61
        assert!(layout.is_zst());
62
        OperandRef {
63
            val: OperandValue::Immediate(bx.const_undef(bx.immediate_backend_type(layout))),
M
Mark Rousskov 已提交
64
            layout,
65
        }
66 67
    }

68
    pub fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
69
        bx: &mut Bx,
70 71
        val: ConstValue<'tcx>,
        ty: Ty<'tcx>,
72
    ) -> Self {
73
        let layout = bx.layout_of(ty);
O
Oliver Schneider 已提交
74 75

        if layout.is_zst() {
76
            return OperandRef::new_zst(bx, layout);
O
Oliver Schneider 已提交
77 78
        }

79
        let val = match val {
80
            ConstValue::Scalar(x) => {
O
Oliver Schneider 已提交
81
                let scalar = match layout.abi {
82
                    Abi::Scalar(ref x) => x,
M
Mark Rousskov 已提交
83
                    _ => bug!("from_const: invalid ByVal layout: {:#?}", layout),
O
Oliver Schneider 已提交
84
                };
M
Mark Rousskov 已提交
85
                let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
O
Oliver Schneider 已提交
86
                OperandValue::Immediate(llval)
M
Mark Rousskov 已提交
87
            }
88
            ConstValue::Slice { data, start, end } => {
89
                let a_scalar = match layout.abi {
90
                    Abi::ScalarPair(ref a, _) => a,
M
Mark Rousskov 已提交
91
                    _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout),
O
Oliver Schneider 已提交
92
                };
93
                let a = Scalar::from(Pointer::new(
94
                    bx.tcx().create_memory_alloc(data),
95
                    Size::from_bytes(start),
96
                ));
97
                let a_llval = bx.scalar_to_backend(
O
Oliver Schneider 已提交
98 99
                    a,
                    a_scalar,
100
                    bx.scalar_pair_element_backend_type(layout, 0, true),
O
Oliver Schneider 已提交
101
                );
102
                let b_llval = bx.const_usize((end - start) as u64);
O
Oliver Schneider 已提交
103
                OperandValue::Pair(a_llval, b_llval)
M
Mark Rousskov 已提交
104
            }
105 106
            ConstValue::ByRef { alloc, offset } => {
                return bx.load_operand(bx.from_const_alloc(layout, alloc, offset));
M
Mark Rousskov 已提交
107
            }
O
Oliver Schneider 已提交
108 109
        };

M
Mark Rousskov 已提交
110
        OperandRef { val, layout }
O
Oliver Schneider 已提交
111 112
    }

113 114
    /// Asserts that this operand refers to a scalar and returns
    /// a reference to its value.
115
    pub fn immediate(self) -> V {
116 117
        match self.val {
            OperandValue::Immediate(s) => s,
M
Mark Rousskov 已提交
118
            _ => bug!("not immediate: {:?}", self),
119 120
        }
    }
121

M
Mark Rousskov 已提交
122 123 124 125 126 127 128
    pub fn deref<Cx: LayoutTypeMethods<'tcx>>(self, cx: &Cx) -> PlaceRef<'tcx, V> {
        let projected_ty = self
            .layout
            .ty
            .builtin_deref(true)
            .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self))
            .ty;
A
Ariel Ben-Yehuda 已提交
129
        let (llptr, llextra) = match self.val {
130 131
            OperandValue::Immediate(llptr) => (llptr, None),
            OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
M
Mark Rousskov 已提交
132
            OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self),
A
Ariel Ben-Yehuda 已提交
133
        };
134
        let layout = cx.layout_of(projected_ty);
M
Mark Rousskov 已提交
135
        PlaceRef { llval: llptr, llextra, layout, align: layout.align.abi }
A
Ariel Ben-Yehuda 已提交
136 137
    }

138 139
    /// If this operand is a `Pair`, we return an aggregate with the two values.
    /// For other cases, see `immediate`.
140 141
    pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
        self,
M
Mark Rousskov 已提交
142
        bx: &mut Bx,
143
    ) -> V {
144
        if let OperandValue::Pair(a, b) = self.val {
145
            let llty = bx.cx().backend_type(self.layout);
M
Mark Rousskov 已提交
146
            debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}", self, llty);
147
            // Reconstruct the immediate aggregate.
148
            let mut llpair = bx.cx().const_undef(llty);
149 150
            let imm_a = bx.from_immediate(a);
            let imm_b = bx.from_immediate(b);
151 152
            llpair = bx.insert_value(llpair, imm_a, 0);
            llpair = bx.insert_value(llpair, imm_b, 1);
153 154 155
            llpair
        } else {
            self.immediate()
156 157 158
        }
    }

159
    /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
160
    pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
161
        bx: &mut Bx,
162
        llval: V,
163
        layout: TyAndLayout<'tcx>,
164
    ) -> Self {
165
        let val = if let Abi::ScalarPair(ref a, ref b) = layout.abi {
M
Mark Rousskov 已提交
166
            debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}", llval, layout);
167

168
            // Deconstruct the immediate aggregate.
169
            let a_llval = bx.extract_value(llval, 0);
170
            let a_llval = bx.to_immediate_scalar(a_llval, a);
171
            let b_llval = bx.extract_value(llval, 1);
172
            let b_llval = bx.to_immediate_scalar(b_llval, b);
173
            OperandValue::Pair(a_llval, b_llval)
174 175 176 177
        } else {
            OperandValue::Immediate(llval)
        };
        OperandRef { val, layout }
178
    }
179

180
    pub fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
181
        &self,
182
        bx: &mut Bx,
M
Mark Rousskov 已提交
183
        i: usize,
184
    ) -> Self {
185
        let field = self.layout.field(bx.cx(), i);
186 187 188
        let offset = self.layout.fields.offset(i);

        let mut val = match (self.val, &self.layout.abi) {
189 190
            // If the field is ZST, it has no data.
            _ if field.is_zst() => {
191
                return OperandRef::new_zst(bx, field);
192 193
            }

194
            // Newtype of a scalar, scalar pair or vector.
195
            (OperandValue::Immediate(_) | OperandValue::Pair(..), _)
M
Mark Rousskov 已提交
196 197
                if field.size == self.layout.size =>
            {
198 199 200 201 202
                assert_eq!(offset.bytes(), 0);
                self.val
            }

            // Extract a scalar component from a pair.
203
            (OperandValue::Pair(a_llval, b_llval), &Abi::ScalarPair(ref a, ref b)) => {
204
                if offset.bytes() == 0 {
205
                    assert_eq!(field.size, a.value.size(bx.cx()));
206 207
                    OperandValue::Immediate(a_llval)
                } else {
M
Mark Rousskov 已提交
208
                    assert_eq!(offset, a.value.size(bx.cx()).align_to(b.value.align(bx.cx()).abi));
209
                    assert_eq!(field.size, b.value.size(bx.cx()));
210 211 212 213 214
                    OperandValue::Immediate(b_llval)
                }
            }

            // `#[repr(simd)]` types are also immediate.
215
            (OperandValue::Immediate(llval), &Abi::Vector { .. }) => {
M
Mark Rousskov 已提交
216
                OperandValue::Immediate(bx.extract_element(llval, bx.cx().const_usize(i as u64)))
217 218
            }

M
Mark Rousskov 已提交
219
            _ => bug!("OperandRef::extract_field({:?}): not applicable", self),
220 221
        };

222
        match (&mut val, &field.abi) {
223 224 225 226 227
            (OperandValue::Immediate(llval), _) => {
                // Bools in union fields needs to be truncated.
                *llval = bx.to_immediate(*llval, field);
                // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
                *llval = bx.bitcast(*llval, bx.cx().immediate_backend_type(field));
228
            }
229
            (OperandValue::Pair(a, b), Abi::ScalarPair(a_abi, b_abi)) => {
230
                // Bools in union fields needs to be truncated.
231 232
                *a = bx.to_immediate_scalar(*a, a_abi);
                *b = bx.to_immediate_scalar(*b, b_abi);
233 234
                // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
                *a = bx.bitcast(*a, bx.cx().scalar_pair_element_backend_type(field, 0, true));
235
                *b = bx.bitcast(*b, bx.cx().scalar_pair_element_backend_type(field, 1, true));
236
            }
237 238
            (OperandValue::Pair(..), _) => bug!(),
            (OperandValue::Ref(..), _) => bug!(),
239 240
        }

M
Mark Rousskov 已提交
241
        OperandRef { val, layout: field }
242
    }
243
}
244

245
impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
246 247
    pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
        self,
248
        bx: &mut Bx,
M
Mark Rousskov 已提交
249
        dest: PlaceRef<'tcx, V>,
250
    ) {
251
        self.store_with_flags(bx, dest, MemFlags::empty());
252 253
    }

254
    pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
255
        self,
256
        bx: &mut Bx,
M
Mark Rousskov 已提交
257
        dest: PlaceRef<'tcx, V>,
258
    ) {
259
        self.store_with_flags(bx, dest, MemFlags::VOLATILE);
260 261
    }

262
    pub fn unaligned_volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
263
        self,
264
        bx: &mut Bx,
265
        dest: PlaceRef<'tcx, V>,
266
    ) {
267 268 269
        self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
    }

270
    pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
271
        self,
272
        bx: &mut Bx,
M
Mark Rousskov 已提交
273
        dest: PlaceRef<'tcx, V>,
274
    ) {
275 276 277
        self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
    }

278
    fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
279
        self,
280
        bx: &mut Bx,
281
        dest: PlaceRef<'tcx, V>,
282 283
        flags: MemFlags,
    ) {
284 285 286
        debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
        // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
        // value is through `undef`, and store itself is useless.
287
        if dest.layout.is_zst() {
288 289
            return;
        }
290
        match self {
291
            OperandValue::Ref(r, None, source_align) => {
N
Nikita Popov 已提交
292 293 294 295 296 297 298 299 300
                if flags.contains(MemFlags::NONTEMPORAL) {
                    // HACK(nox): This is inefficient but there is no nontemporal memcpy.
                    // FIXME: Don't access pointer element type.
                    let ty = bx.element_type(bx.val_ty(r));
                    let val = bx.load(ty, r, source_align);
                    let ptr = bx.pointercast(dest.llval, bx.type_ptr_to(ty));
                    bx.store_with_flags(val, ptr, dest.align, flags);
                    return;
                }
M
Mark Rousskov 已提交
301
                base::memcpy_ty(bx, dest.llval, dest.align, r, source_align, dest.layout, flags)
302
            }
303
            OperandValue::Ref(_, Some(_), _) => {
304 305
                bug!("cannot directly store unsized values");
            }
306
            OperandValue::Immediate(s) => {
307
                let val = bx.from_immediate(s);
308
                bx.store_with_flags(val, dest.llval, dest.align, flags);
309 310
            }
            OperandValue::Pair(a, b) => {
311
                let (a_scalar, b_scalar) = match dest.layout.abi {
312
                    Abi::ScalarPair(ref a, ref b) => (a, b),
M
Mark Rousskov 已提交
313
                    _ => bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout),
314 315 316 317
                };
                let b_offset = a_scalar.value.size(bx).align_to(b_scalar.value.align(bx).abi);

                let llptr = bx.struct_gep(dest.llval, 0);
318
                let val = bx.from_immediate(a);
319 320 321 322
                let align = dest.align;
                bx.store_with_flags(val, llptr, align, flags);

                let llptr = bx.struct_gep(dest.llval, 1);
323
                let val = bx.from_immediate(b);
324 325
                let align = dest.align.restrict_for_offset(b_offset);
                bx.store_with_flags(val, llptr, align, flags);
326 327
            }
        }
328
    }
329

330
    pub fn store_unsized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
331
        self,
332
        bx: &mut Bx,
M
Mark Rousskov 已提交
333
        indirect_dest: PlaceRef<'tcx, V>,
334
    ) {
335 336 337 338
        debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
        let flags = MemFlags::empty();

        // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
M
Mark Rousskov 已提交
339 340 341 342 343 344 345 346 347 348 349 350
        let unsized_ty = indirect_dest
            .layout
            .ty
            .builtin_deref(true)
            .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest))
            .ty;

        let (llptr, llextra) = if let OperandValue::Ref(llptr, Some(llextra), _) = self {
            (llptr, llextra)
        } else {
            bug!("store_unsized called with a sized value")
        };
351 352

        // FIXME: choose an appropriate alignment, or use dynamic align somehow
353 354
        let max_align = Align::from_bits(128).unwrap();
        let min_align = Align::from_bits(8).unwrap();
355 356

        // Allocate an appropriate region on the stack, and copy the value into it
357
        let (llsize, _) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
358
        let lldst = bx.array_alloca(bx.cx().type_i8(), llsize, max_align);
359
        bx.memcpy(lldst, max_align, llptr, min_align, llsize, flags);
360 361 362

        // Store the allocated region and the extra to the indirect place.
        let indirect_operand = OperandValue::Pair(lldst, llextra);
363
        indirect_operand.store(bx, indirect_dest);
364
    }
365
}
366

367
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
368 369
    fn maybe_codegen_consume_direct(
        &mut self,
370
        bx: &mut Bx,
371
        place_ref: mir::PlaceRef<'tcx>,
372
    ) -> Option<OperandRef<'tcx, Bx::Value>> {
373
        debug!("maybe_codegen_consume_direct(place_ref={:?})", place_ref);
374

375
        match self.locals[place_ref.local] {
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
            LocalRef::Operand(Some(mut o)) => {
                // Moves out of scalar and scalar pair fields are trivial.
                for elem in place_ref.projection.iter() {
                    match elem {
                        mir::ProjectionElem::Field(ref f, _) => {
                            o = o.extract_field(bx, f.index());
                        }
                        mir::ProjectionElem::Index(_)
                        | mir::ProjectionElem::ConstantIndex { .. } => {
                            // ZSTs don't require any actual memory access.
                            // FIXME(eddyb) deduplicate this with the identical
                            // checks in `codegen_consume` and `extract_field`.
                            let elem = o.layout.field(bx.cx(), 0);
                            if elem.is_zst() {
                                o = OperandRef::new_zst(bx, elem);
                            } else {
                                return None;
393 394
                            }
                        }
395
                        _ => return None,
396
                    }
397
                }
398 399 400 401 402 403 404 405 406 407

                Some(o)
            }
            LocalRef::Operand(None) => {
                bug!("use of {:?} before def", place_ref);
            }
            LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
                // watch out for locals that do not have an
                // alloca; they are handled somewhat differently
                None
408
            }
409
        }
410 411
    }

412 413
    pub fn codegen_consume(
        &mut self,
414
        bx: &mut Bx,
415
        place_ref: mir::PlaceRef<'tcx>,
416
    ) -> OperandRef<'tcx, Bx::Value> {
417
        debug!("codegen_consume(place_ref={:?})", place_ref);
418

419
        let ty = self.monomorphized_place_ty(place_ref);
420
        let layout = bx.cx().layout_of(ty);
421 422 423

        // ZSTs don't require any actual memory access.
        if layout.is_zst() {
424
            return OperandRef::new_zst(bx, layout);
425 426
        }

427
        if let Some(o) = self.maybe_codegen_consume_direct(bx, place_ref) {
428 429 430
            return o;
        }

431
        // for most places, to consume them we just load them
432
        // out from their home
433
        let place = self.codegen_place(bx, place_ref);
434
        bx.load_operand(place)
435
    }
436

437 438
    pub fn codegen_operand(
        &mut self,
439
        bx: &mut Bx,
M
Mark Rousskov 已提交
440
        operand: &mir::Operand<'tcx>,
441
    ) -> OperandRef<'tcx, Bx::Value> {
I
Irina Popa 已提交
442
        debug!("codegen_operand(operand={:?})", operand);
443 444

        match *operand {
M
Mark Rousskov 已提交
445
            mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
446
                self.codegen_consume(bx, place.as_ref())
447 448 449
            }

            mir::Operand::Constant(ref constant) => {
450 451 452
                // This cannot fail because we checked all required_consts in advance.
                self.eval_mir_constant_to_operand(bx, constant).unwrap_or_else(|_err| {
                    span_bug!(constant.span, "erroneous constant not captured by required_consts")
M
Mark Rousskov 已提交
453
                })
454 455 456 457
            }
        }
    }
}