operand.rs 22.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

R
Ralf Jung 已提交
11 12 13
//! Functions concerning immediate values and operands, and reading from operands.
//! All high-level functions to read from memory work on operands as sources.

14
use std::hash::{Hash, Hasher};
R
Ralf Jung 已提交
15 16
use std::convert::TryInto;

17
use rustc::{mir, ty};
R
Ralf Jung 已提交
18
use rustc::ty::layout::{self, Size, Align, LayoutOf, TyLayout, HasDataLayout, IntegerExt};
R
Ralf Jung 已提交
19 20 21 22 23
use rustc_data_structures::indexed_vec::Idx;

use rustc::mir::interpret::{
    GlobalId, ConstValue, Scalar, EvalResult, Pointer, ScalarMaybeUndef, EvalErrorKind
};
24
use super::{EvalContext, Machine, MemPlace, MPlaceTy, MemoryKind};
R
Ralf Jung 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

/// A `Value` represents a single immediate self-contained Rust value.
///
/// For optimization of a few very common cases, there is also a representation for a pair of
/// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
/// operations and fat pointers. This idea was taken from rustc's codegen.
/// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
/// defined on `Value`, and do not have to work with a `Place`.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum Value {
    Scalar(ScalarMaybeUndef),
    ScalarPair(ScalarMaybeUndef, ScalarMaybeUndef),
}

impl<'tcx> Value {
    pub fn new_slice(
        val: Scalar,
        len: u64,
        cx: impl HasDataLayout
    ) -> Self {
        Value::ScalarPair(val.into(), Scalar::Bits {
            bits: len as u128,
            size: cx.data_layout().pointer_size.bytes() as u8,
        }.into())
    }

    pub fn new_dyn_trait(val: Scalar, vtable: Pointer) -> Self {
        Value::ScalarPair(val.into(), Scalar::Ptr(vtable).into())
    }

55
    #[inline]
R
Ralf Jung 已提交
56 57 58 59 60 61 62
    pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef {
        match self {
            Value::Scalar(val) => val,
            Value::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"),
        }
    }

63
    #[inline]
R
Ralf Jung 已提交
64 65 66 67
    pub fn to_scalar(self) -> EvalResult<'tcx, Scalar> {
        self.to_scalar_or_undef().not_undef()
    }

68 69 70 71 72 73 74 75
    #[inline]
    pub fn to_scalar_pair(self) -> EvalResult<'tcx, (Scalar, Scalar)> {
        match self {
            Value::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"),
            Value::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?))
        }
    }

R
Ralf Jung 已提交
76
    /// Convert the value into a pointer (or a pointer-sized integer).
77 78
    /// Throws away the second half of a ScalarPair!
    #[inline]
R
Ralf Jung 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    pub fn to_scalar_ptr(self) -> EvalResult<'tcx, Scalar> {
        match self {
            Value::Scalar(ptr) |
            Value::ScalarPair(ptr, _) => ptr.not_undef(),
        }
    }
}

// ScalarPair needs a type to interpret, so we often have a value and a type together
// as input for binary and cast operations.
#[derive(Copy, Clone, Debug)]
pub struct ValTy<'tcx> {
    pub value: Value,
    pub layout: TyLayout<'tcx>,
}

impl<'tcx> ::std::ops::Deref for ValTy<'tcx> {
    type Target = Value;
97
    #[inline(always)]
R
Ralf Jung 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    fn deref(&self) -> &Value {
        &self.value
    }
}

/// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
/// or still in memory.  The latter is an optimization, to delay reading that chunk of
/// memory and to avoid having to store arbitrary-sized data here.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum Operand {
    Immediate(Value),
    Indirect(MemPlace),
}

impl Operand {
    #[inline]
    pub fn from_ptr(ptr: Pointer, align: Align) -> Self {
        Operand::Indirect(MemPlace::from_ptr(ptr, align))
    }

    #[inline]
    pub fn from_scalar_value(val: Scalar) -> Self {
        Operand::Immediate(Value::Scalar(val.into()))
    }

    #[inline]
    pub fn to_mem_place(self) -> MemPlace {
        match self {
            Operand::Indirect(mplace) => mplace,
            _ => bug!("to_mem_place: expected Operand::Indirect, got {:?}", self),

        }
    }

    #[inline]
    pub fn to_immediate(self) -> Value {
        match self {
            Operand::Immediate(val) => val,
            _ => bug!("to_immediate: expected Operand::Immediate, got {:?}", self),

        }
    }
}

#[derive(Copy, Clone, Debug)]
pub struct OpTy<'tcx> {
144
    crate op: Operand, // ideally we'd make this private, but we are not there yet
R
Ralf Jung 已提交
145 146 147 148 149
    pub layout: TyLayout<'tcx>,
}

impl<'tcx> ::std::ops::Deref for OpTy<'tcx> {
    type Target = Operand;
150
    #[inline(always)]
R
Ralf Jung 已提交
151 152 153 154 155 156
    fn deref(&self) -> &Operand {
        &self.op
    }
}

impl<'tcx> From<MPlaceTy<'tcx>> for OpTy<'tcx> {
157
    #[inline(always)]
R
Ralf Jung 已提交
158 159 160 161 162 163 164 165 166
    fn from(mplace: MPlaceTy<'tcx>) -> Self {
        OpTy {
            op: Operand::Indirect(*mplace),
            layout: mplace.layout
        }
    }
}

impl<'tcx> From<ValTy<'tcx>> for OpTy<'tcx> {
167
    #[inline(always)]
R
Ralf Jung 已提交
168 169 170 171 172 173 174 175
    fn from(val: ValTy<'tcx>) -> Self {
        OpTy {
            op: Operand::Immediate(val.value),
            layout: val.layout
        }
    }
}

176 177 178 179 180 181 182 183 184 185 186 187 188 189
// Validation needs to hash OpTy, but we cannot hash Layout -- so we just hash the type
impl<'tcx> Hash for OpTy<'tcx> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.op.hash(state);
        self.layout.ty.hash(state);
    }
}
impl<'tcx> PartialEq for OpTy<'tcx> {
    fn eq(&self, other: &Self) -> bool {
        self.op == other.op && self.layout.ty == other.layout.ty
    }
}
impl<'tcx> Eq for OpTy<'tcx> {}

R
Ralf Jung 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
impl<'tcx> OpTy<'tcx> {
    #[inline]
    pub fn from_ptr(ptr: Pointer, align: Align, layout: TyLayout<'tcx>) -> Self {
        OpTy { op: Operand::from_ptr(ptr, align), layout }
    }

    #[inline]
    pub fn from_aligned_ptr(ptr: Pointer, layout: TyLayout<'tcx>) -> Self {
        OpTy { op: Operand::from_ptr(ptr, layout.align), layout }
    }

    #[inline]
    pub fn from_scalar_value(val: Scalar, layout: TyLayout<'tcx>) -> Self {
        OpTy { op: Operand::Immediate(Value::Scalar(val.into())), layout }
    }
}

207 208 209 210 211 212 213 214 215 216
// Use the existing layout if given (but sanity check in debug mode),
// or compute the layout.
#[inline(always)]
fn from_known_layout<'tcx>(
    layout: Option<TyLayout<'tcx>>,
    compute: impl FnOnce() -> EvalResult<'tcx, TyLayout<'tcx>>
) -> EvalResult<'tcx, TyLayout<'tcx>> {
    match layout {
        None => compute(),
        Some(layout) => {
R
Ralf Jung 已提交
217 218 219 220 221 222
            if cfg!(debug_assertions) {
                let layout2 = compute()?;
                assert_eq!(layout.details, layout2.details,
                    "Mismatch in layout of supposedly equal-layout types {:?} and {:?}",
                    layout.ty, layout2.ty);
            }
223 224 225 226 227
            Ok(layout)
        }
    }
}

R
Ralf Jung 已提交
228 229 230
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
    /// Try reading a value in memory; this is interesting particularily for ScalarPair.
    /// Return None if the layout does not permit loading this as a value.
231
    pub(super) fn try_read_value_from_mplace(
R
Ralf Jung 已提交
232
        &self,
233
        mplace: MPlaceTy<'tcx>,
R
Ralf Jung 已提交
234
    ) -> EvalResult<'tcx, Option<Value>> {
235 236 237
        debug_assert_eq!(mplace.extra.is_some(), mplace.layout.is_unsized());
        if mplace.extra.is_some() {
            // Dont touch unsized
238 239 240
            return Ok(None);
        }
        let (ptr, ptr_align) = mplace.to_scalar_ptr_align();
R
Ralf Jung 已提交
241

242
        if mplace.layout.size.bytes() == 0 {
243 244 245
            // Not all ZSTs have a layout we would handle below, so just short-circuit them
            // all here.
            self.memory.check_align(ptr, ptr_align)?;
R
Ralf Jung 已提交
246
            return Ok(Some(Value::Scalar(Scalar::zst().into())));
R
Ralf Jung 已提交
247 248 249
        }

        let ptr = ptr.to_ptr()?;
250
        match mplace.layout.abi {
R
Ralf Jung 已提交
251
            layout::Abi::Scalar(..) => {
252
                let scalar = self.memory.read_scalar(ptr, ptr_align, mplace.layout.size)?;
R
Ralf Jung 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
                Ok(Some(Value::Scalar(scalar)))
            }
            layout::Abi::ScalarPair(ref a, ref b) => {
                let (a, b) = (&a.value, &b.value);
                let (a_size, b_size) = (a.size(self), b.size(self));
                let a_ptr = ptr;
                let b_offset = a_size.abi_align(b.align(self));
                assert!(b_offset.bytes() > 0); // we later use the offset to test which field to use
                let b_ptr = ptr.offset(b_offset, self)?.into();
                let a_val = self.memory.read_scalar(a_ptr, ptr_align, a_size)?;
                let b_val = self.memory.read_scalar(b_ptr, ptr_align, b_size)?;
                Ok(Some(Value::ScalarPair(a_val, b_val)))
            }
            _ => Ok(None),
        }
    }

    /// Try returning an immediate value for the operand.
    /// If the layout does not permit loading this as a value, return where in memory
    /// we can find the data.
    /// Note that for a given layout, this operation will either always fail or always
    /// succeed!  Whether it succeeds depends on whether the layout can be represented
    /// in a `Value`, not on which data is stored there currently.
276
    pub(crate) fn try_read_value(
R
Ralf Jung 已提交
277
        &self,
R
Ralf Jung 已提交
278
        src: OpTy<'tcx>,
R
Ralf Jung 已提交
279
    ) -> EvalResult<'tcx, Result<Value, MemPlace>> {
280 281 282 283 284 285
        Ok(match src.try_as_mplace() {
            Ok(mplace) => {
                if let Some(val) = self.try_read_value_from_mplace(mplace)? {
                    Ok(val)
                } else {
                    Err(*mplace)
R
Ralf Jung 已提交
286 287
                }
            },
288 289
            Err(val) => Ok(val),
        })
R
Ralf Jung 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302
    }

    /// Read a value from a place, asserting that that is possible with the given layout.
    #[inline(always)]
    pub fn read_value(&self, op: OpTy<'tcx>) -> EvalResult<'tcx, ValTy<'tcx>> {
        if let Ok(value) = self.try_read_value(op)? {
            Ok(ValTy { value, layout: op.layout })
        } else {
            bug!("primitive read failed for type: {:?}", op.layout.ty);
        }
    }

    /// Read a scalar from a place
R
Ralf Jung 已提交
303
    pub fn read_scalar(&self, op: OpTy<'tcx>) -> EvalResult<'tcx, ScalarMaybeUndef> {
R
Ralf Jung 已提交
304 305 306 307 308 309
        match *self.read_value(op)? {
            Value::ScalarPair(..) => bug!("got ScalarPair for type: {:?}", op.layout.ty),
            Value::Scalar(val) => Ok(val),
        }
    }

310
    // Turn the MPlace into a string (must already be dereferenced!)
R
Ralf Jung 已提交
311 312
    pub fn read_str(
        &self,
313
        mplace: MPlaceTy<'tcx>,
R
Ralf Jung 已提交
314
    ) -> EvalResult<'tcx, &str> {
315 316 317 318 319
        let len = mplace.len(self)?;
        let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?;
        let str = ::std::str::from_utf8(bytes)
            .map_err(|err| EvalErrorKind::ValidationFailure(err.to_string()))?;
        Ok(str)
R
Ralf Jung 已提交
320 321
    }

R
Ralf Jung 已提交
322 323 324
    pub fn uninit_operand(&mut self, layout: TyLayout<'tcx>) -> EvalResult<'tcx, Operand> {
        // This decides which types we will use the Immediate optimization for, and hence should
        // match what `try_read_value` and `eval_place_to_op` support.
R
Ralf Jung 已提交
325
        if layout.is_zst() {
326
            return Ok(Operand::Immediate(Value::Scalar(Scalar::zst().into())));
R
Ralf Jung 已提交
327 328
        }

R
Ralf Jung 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
        Ok(match layout.abi {
            layout::Abi::Scalar(..) =>
                Operand::Immediate(Value::Scalar(ScalarMaybeUndef::Undef)),
            layout::Abi::ScalarPair(..) =>
                Operand::Immediate(Value::ScalarPair(
                    ScalarMaybeUndef::Undef,
                    ScalarMaybeUndef::Undef,
                )),
            _ => {
                trace!("Forcing allocation for local of type {:?}", layout.ty);
                Operand::Indirect(
                    *self.allocate(layout, MemoryKind::Stack)?
                )
            }
        })
    }

    /// Projection functions
    pub fn operand_field(
        &self,
        op: OpTy<'tcx>,
        field: u64,
    ) -> EvalResult<'tcx, OpTy<'tcx>> {
        let base = match op.try_as_mplace() {
            Ok(mplace) => {
                // The easy case
                let field = self.mplace_field(mplace, field)?;
                return Ok(field.into());
            },
            Err(value) => value
        };

        let field = field.try_into().unwrap();
        let field_layout = op.layout.field(self, field)?;
        if field_layout.size.bytes() == 0 {
            let val = Value::Scalar(Scalar::zst().into());
            return Ok(OpTy { op: Operand::Immediate(val), layout: field_layout });
        }
        let offset = op.layout.fields.offset(field);
        let value = match base {
            // the field covers the entire type
            _ if offset.bytes() == 0 && field_layout.size == op.layout.size => base,
            // extract fields from types with `ScalarPair` ABI
            Value::ScalarPair(a, b) => {
                let val = if offset.bytes() == 0 { a } else { b };
                Value::Scalar(val)
            },
            Value::Scalar(val) =>
                bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout),
        };
        Ok(OpTy { op: Operand::Immediate(value), layout: field_layout })
    }

382
    pub fn operand_downcast(
R
Ralf Jung 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
        &self,
        op: OpTy<'tcx>,
        variant: usize,
    ) -> EvalResult<'tcx, OpTy<'tcx>> {
        // Downcasts only change the layout
        Ok(match op.try_as_mplace() {
            Ok(mplace) => {
                self.mplace_downcast(mplace, variant)?.into()
            },
            Err(..) => {
                let layout = op.layout.for_variant(self, variant);
                OpTy { layout, ..op }
            }
        })
    }

    // Take an operand, representing a pointer, and dereference it -- that
    // will always be a MemPlace.
    pub(super) fn deref_operand(
        &self,
        src: OpTy<'tcx>,
    ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
        let val = self.read_value(src)?;
        trace!("deref to {} on {:?}", val.layout.ty, val);
        Ok(self.ref_to_mplace(val)?)
    }

    pub fn operand_projection(
        &self,
        base: OpTy<'tcx>,
        proj_elem: &mir::PlaceElem<'tcx>,
    ) -> EvalResult<'tcx, OpTy<'tcx>> {
        use rustc::mir::ProjectionElem::*;
        Ok(match *proj_elem {
            Field(field, _) => self.operand_field(base, field.index() as u64)?,
            Downcast(_, variant) => self.operand_downcast(base, variant)?,
            Deref => self.deref_operand(base)?.into(),
            // The rest should only occur as mplace, we do not use Immediates for types
            // allowing such operations.  This matches place_projection forcing an allocation.
            Subslice { .. } | ConstantIndex { .. } | Index(_) => {
                let mplace = base.to_mem_place();
                self.mplace_projection(mplace, proj_elem)?.into()
            }
        })
    }

    // Evaluate a place with the goal of reading from it.  This lets us sometimes
430 431
    // avoid allocations.  If you already know the layout, you can pass it in
    // to avoid looking it up again.
R
Ralf Jung 已提交
432
    fn eval_place_to_op(
433
        &self,
R
Ralf Jung 已提交
434
        mir_place: &mir::Place<'tcx>,
435
        layout: Option<TyLayout<'tcx>>,
R
Ralf Jung 已提交
436 437
    ) -> EvalResult<'tcx, OpTy<'tcx>> {
        use rustc::mir::Place::*;
438
        let op = match *mir_place {
R
Ralf Jung 已提交
439 440 441
            Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer),
            Local(local) => {
                let op = *self.frame().locals[local].access()?;
442 443 444
                let layout = from_known_layout(layout,
                    || self.layout_of_local(self.cur_frame(), local))?;
                OpTy { op, layout }
R
Ralf Jung 已提交
445 446 447
            },

            Projection(ref proj) => {
448
                let op = self.eval_place_to_op(&proj.base, None)?;
R
Ralf Jung 已提交
449 450 451
                self.operand_projection(op, &proj.elem)?
            }

452 453 454 455 456
            _ => self.eval_place_to_mplace(mir_place)?.into(),
        };

        trace!("eval_place_to_op: got {:?}", *op);
        Ok(op)
R
Ralf Jung 已提交
457 458 459
    }

    /// Evaluate the operand, returning a place where you can then find the data.
460 461 462
    /// if you already know the layout, you can save two some table lookups
    /// by passing it in here.
    pub fn eval_operand(
463
        &self,
464 465 466
        mir_op: &mir::Operand<'tcx>,
        layout: Option<TyLayout<'tcx>>,
    ) -> EvalResult<'tcx, OpTy<'tcx>> {
R
Ralf Jung 已提交
467
        use rustc::mir::Operand::*;
R
Ralf Jung 已提交
468
        let op = match *mir_op {
R
Ralf Jung 已提交
469 470 471
            // FIXME: do some more logic on `move` to invalidate the old location
            Copy(ref place) |
            Move(ref place) =>
472
                self.eval_place_to_op(place, layout)?,
R
Ralf Jung 已提交
473 474

            Constant(ref constant) => {
475 476 477 478
                let layout = from_known_layout(layout, || {
                    let ty = self.monomorphize(mir_op.ty(self.mir(), *self.tcx), self.substs());
                    self.layout_of(ty)
                })?;
R
Ralf Jung 已提交
479
                let op = self.const_value_to_op(constant.literal.val)?;
R
Ralf Jung 已提交
480
                OpTy { op, layout }
R
Ralf Jung 已提交
481
            }
R
Ralf Jung 已提交
482 483 484
        };
        trace!("{:?}: {:?}", mir_op, *op);
        Ok(op)
R
Ralf Jung 已提交
485 486 487
    }

    /// Evaluate a bunch of operands at once
488
    pub(super) fn eval_operands(
489
        &self,
R
Ralf Jung 已提交
490 491 492
        ops: &[mir::Operand<'tcx>],
    ) -> EvalResult<'tcx, Vec<OpTy<'tcx>>> {
        ops.into_iter()
493
            .map(|op| self.eval_operand(op, None))
R
Ralf Jung 已提交
494 495 496 497
            .collect()
    }

    // Also used e.g. when miri runs into a constant.
498
    pub(super) fn const_value_to_op(
R
Ralf Jung 已提交
499
        &self,
R
Ralf Jung 已提交
500 501
        val: ConstValue<'tcx>,
    ) -> EvalResult<'tcx, Operand> {
R
Ralf Jung 已提交
502
        trace!("const_value_to_op: {:?}", val);
R
Ralf Jung 已提交
503 504 505 506 507 508 509 510
        match val {
            ConstValue::Unevaluated(def_id, substs) => {
                let instance = self.resolve(def_id, substs)?;
                self.global_to_op(GlobalId {
                    instance,
                    promoted: None,
                })
            }
R
Ralf Jung 已提交
511 512 513
            ConstValue::ByRef(id, alloc, offset) => {
                // We rely on mutability being set correctly in that allocation to prevent writes
                // where none should happen -- and for `static mut`, we copy on demand anyway.
R
Ralf Jung 已提交
514 515 516 517 518 519 520 521
                Ok(Operand::from_ptr(Pointer::new(id, offset), alloc.align))
            },
            ConstValue::ScalarPair(a, b) =>
                Ok(Operand::Immediate(Value::ScalarPair(a.into(), b))),
            ConstValue::Scalar(x) =>
                Ok(Operand::Immediate(Value::Scalar(x.into()))),
        }
    }
522 523 524 525 526 527 528
    pub fn const_to_op(
        &self,
        cnst: &ty::Const<'tcx>,
    ) -> EvalResult<'tcx, OpTy<'tcx>> {
        let op = self.const_value_to_op(cnst.val)?;
        Ok(OpTy { op, layout: self.layout_of(cnst.ty)? })
    }
R
Ralf Jung 已提交
529

R
Ralf Jung 已提交
530
    pub(super) fn global_to_op(&self, gid: GlobalId<'tcx>) -> EvalResult<'tcx, Operand> {
R
Ralf Jung 已提交
531 532 533 534
        let cv = self.const_eval(gid)?;
        self.const_value_to_op(cv.val)
    }

535 536
    /// Read discriminant, return the runtime value as well as the variant index.
    pub fn read_discriminant(
R
Ralf Jung 已提交
537 538
        &self,
        rval: OpTy<'tcx>,
539
    ) -> EvalResult<'tcx, (u128, usize)> {
R
Ralf Jung 已提交
540 541 542 543 544 545 546 547 548 549
        trace!("read_discriminant_value {:#?}", rval.layout);
        if rval.layout.abi == layout::Abi::Uninhabited {
            return err!(Unreachable);
        }

        match rval.layout.variants {
            layout::Variants::Single { index } => {
                let discr_val = rval.layout.ty.ty_adt_def().map_or(
                    index as u128,
                    |def| def.discriminant_for_variant(*self.tcx, index).val);
550
                return Ok((discr_val, index));
R
Ralf Jung 已提交
551 552 553 554
            }
            layout::Variants::Tagged { .. } |
            layout::Variants::NicheFilling { .. } => {},
        }
555
        // read raw discriminant value
R
Ralf Jung 已提交
556 557 558
        let discr_op = self.operand_field(rval, 0)?;
        let discr_val = self.read_value(discr_op)?;
        let raw_discr = discr_val.to_scalar()?;
559 560
        trace!("discr value: {:?}", raw_discr);
        // post-process
R
Ralf Jung 已提交
561 562 563
        Ok(match rval.layout.variants {
            layout::Variants::Single { .. } => bug!(),
            layout::Variants::Tagged { .. } => {
564
                let real_discr = if discr_val.layout.ty.is_signed() {
R
Ralf Jung 已提交
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
                    let i = raw_discr.to_bits(discr_val.layout.size)? as i128;
                    // going from layout tag type to typeck discriminant type
                    // requires first sign extending with the layout discriminant
                    let shift = 128 - discr_val.layout.size.bits();
                    let sexted = (i << shift) >> shift;
                    // and then zeroing with the typeck discriminant type
                    let discr_ty = rval.layout.ty
                        .ty_adt_def().expect("tagged layout corresponds to adt")
                        .repr
                        .discr_type();
                    let discr_ty = layout::Integer::from_attr(self.tcx.tcx, discr_ty);
                    let shift = 128 - discr_ty.size().bits();
                    let truncatee = sexted as u128;
                    (truncatee << shift) >> shift
                } else {
                    raw_discr.to_bits(discr_val.layout.size)?
581 582 583 584 585 586 587
                };
                // Make sure we catch invalid discriminants
                let index = rval.layout.ty
                    .ty_adt_def()
                    .expect("tagged layout for non adt")
                    .discriminants(self.tcx.tcx)
                    .position(|var| var.val == real_discr)
R
Ralf Jung 已提交
588
                    .ok_or_else(|| EvalErrorKind::InvalidDiscriminant(real_discr))?;
589
                (real_discr, index)
R
Ralf Jung 已提交
590 591 592 593 594 595 596 597 598
            },
            layout::Variants::NicheFilling {
                dataful_variant,
                ref niche_variants,
                niche_start,
                ..
            } => {
                let variants_start = *niche_variants.start() as u128;
                let variants_end = *niche_variants.end() as u128;
599
                let real_discr = match raw_discr {
R
Ralf Jung 已提交
600
                    Scalar::Ptr(_) => {
601
                        // The niche must be just 0 (which a pointer value never is)
R
Ralf Jung 已提交
602 603 604 605 606 607 608 609 610 611 612 613 614 615
                        assert!(niche_start == 0);
                        assert!(variants_start == variants_end);
                        dataful_variant as u128
                    },
                    Scalar::Bits { bits: raw_discr, size } => {
                        assert_eq!(size as u64, discr_val.layout.size.bytes());
                        let discr = raw_discr.wrapping_sub(niche_start)
                            .wrapping_add(variants_start);
                        if variants_start <= discr && discr <= variants_end {
                            discr
                        } else {
                            dataful_variant as u128
                        }
                    },
616 617 618 619 620 621 622 623
                };
                let index = real_discr as usize;
                assert_eq!(index as u128, real_discr);
                assert!(index < rval.layout.ty
                    .ty_adt_def()
                    .expect("tagged layout for non adt")
                    .variants.len());
                (real_discr, index)
R
Ralf Jung 已提交
624 625 626 627 628
            }
        })
    }

}