eval_context.rs 85.2 KB
Newer Older
1
use std::collections::{HashMap, HashSet};
S
Scott Olson 已提交
2
use std::fmt::Write;
3

4
use rustc::hir::def_id::DefId;
5
use rustc::hir::map::definitions::DefPathData;
6
use rustc::middle::const_val::ConstVal;
7
use rustc::mir;
S
Scott Olson 已提交
8
use rustc::traits::Reveal;
9
use rustc::ty::layout::{self, Layout, Size};
O
Oliver Schneider 已提交
10
use rustc::ty::subst::{Subst, Substs, Kind};
11
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Binder};
O
Oliver Schneider 已提交
12
use rustc::traits;
13
use rustc_data_structures::indexed_vec::Idx;
O
Oliver Schneider 已提交
14 15 16
use syntax::codemap::{self, DUMMY_SP, Span};
use syntax::ast;
use syntax::abi::Abi;
17

18
use error::{EvalError, EvalResult};
19
use lvalue::{Global, GlobalId, Lvalue, LvalueExtra};
20
use memory::{Memory, Pointer, TlsKey};
21
use operator;
S
Scott Olson 已提交
22
use value::{PrimVal, PrimValKind, Value};
O
Oliver Schneider 已提交
23

24
pub struct EvalContext<'a, 'tcx: 'a> {
25
    /// The results of the type checker, from rustc.
S
Scott Olson 已提交
26
    pub(crate) tcx: TyCtxt<'a, 'tcx, 'tcx>,
27 28

    /// The virtual memory system.
S
Scott Olson 已提交
29
    pub(crate) memory: Memory<'a, 'tcx>,
30

31
    /// Precomputed statics, constants and promoteds.
S
Scott Olson 已提交
32
    pub(crate) globals: HashMap<GlobalId<'tcx>, Global<'tcx>>,
33 34

    /// The virtual call stack.
S
Scott Olson 已提交
35
    pub(crate) stack: Vec<Frame<'tcx>>,
36 37

    /// The maximum number of stack frames allowed
S
Scott Olson 已提交
38
    pub(crate) stack_limit: usize,
39 40 41 42

    /// The maximum number of operations that may be executed.
    /// This prevents infinite loops and huge computations from freezing up const eval.
    /// Remove once halting problem is solved.
S
Scott Olson 已提交
43
    pub(crate) steps_remaining: u64,
44 45 46 47

    /// Environment variables set by `setenv`
    /// Miri does not expose env vars from the host to the emulated program
    pub(crate) env_vars: HashMap<Vec<u8>, Pointer>,
48 49
}

50
/// A stack frame.
51
pub struct Frame<'tcx> {
52 53 54
    ////////////////////////////////////////////////////////////////////////////////
    // Function and callsite information
    ////////////////////////////////////////////////////////////////////////////////
55

56
    /// The MIR for the function called on this frame.
57
    pub mir: &'tcx mir::Mir<'tcx>,
58

O
Oliver Schneider 已提交
59 60
    /// The def_id and substs of the current function
    pub instance: ty::Instance<'tcx>,
61

62 63
    /// The span of the call site.
    pub span: codemap::Span,
64

65
    ////////////////////////////////////////////////////////////////////////////////
66
    // Return lvalue and locals
67
    ////////////////////////////////////////////////////////////////////////////////
68

69
    /// The block to return to when returning from the current stack frame
70
    pub return_to_block: StackPopCleanup,
71

72
    /// The location where the result of the current stack frame should be written to.
O
Oliver Schneider 已提交
73
    pub return_lvalue: Lvalue<'tcx>,
74 75

    /// The list of locals for this stack frame, stored in order as
76 77
    /// `[arguments..., variables..., temporaries...]`. The locals are stored as `Option<Value>`s.
    /// `None` represents a local that is currently dead, while a live local
78
    /// can either directly contain `PrimVal` or refer to some part of an `Allocation`.
S
Scott Olson 已提交
79
    ///
80 81
    /// Before being initialized, arguments are `Value::ByVal(PrimVal::Undef)` and other locals are `None`.
    pub locals: Vec<Option<Value>>,
82

83 84 85 86 87 88 89 90 91
    ////////////////////////////////////////////////////////////////////////////////
    // Current position within the function
    ////////////////////////////////////////////////////////////////////////////////

    /// The block that is currently executed (or will be executed after the above call stacks
    /// return).
    pub block: mir::BasicBlock,

    /// The index of the currently evaluated statment.
92
    pub stmt: usize,
93
}
94

95 96
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum StackPopCleanup {
97
    /// The stackframe existed to compute the initial value of a static/constant, make sure it
98 99 100 101 102
    /// isn't modifyable afterwards in case of constants.
    /// In case of `static mut`, mark the memory to ensure it's never marked as immutable through
    /// references or deallocated
    /// The bool decides whether the value is mutable (true) or not (false)
    MarkStatic(bool),
103 104 105
    /// A regular stackframe added due to a function call will need to get forwarded to the next
    /// block
    Goto(mir::BasicBlock),
106 107 108 109 110
    /// After finishing a tls destructor, find the next one instead of starting from the beginning
    /// and thus just rerunning the first one until its `data` argument is null
    ///
    /// The index is the current tls destructor's index
    Tls(Option<TlsKey>),
111 112 113 114
    /// The main function and diverging functions have nowhere to return to
    None,
}

S
Scott Olson 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
#[derive(Copy, Clone, Debug)]
pub struct ResourceLimits {
    pub memory_size: u64,
    pub step_limit: u64,
    pub stack_limit: usize,
}

impl Default for ResourceLimits {
    fn default() -> Self {
        ResourceLimits {
            memory_size: 100 * 1024 * 1024, // 100 MB
            step_limit: 1_000_000,
            stack_limit: 100,
        }
    }
}

132
impl<'a, 'tcx> EvalContext<'a, 'tcx> {
S
Scott Olson 已提交
133
    pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, limits: ResourceLimits) -> Self {
134
        EvalContext {
S
Scott Olson 已提交
135
            tcx,
S
Scott Olson 已提交
136
            memory: Memory::new(&tcx.data_layout, limits.memory_size),
137
            globals: HashMap::new(),
138
            stack: Vec::new(),
S
Scott Olson 已提交
139 140
            stack_limit: limits.stack_limit,
            steps_remaining: limits.step_limit,
141
            env_vars: HashMap::new(),
142 143
        }
    }
144

S
Scott Olson 已提交
145 146 147 148 149 150
    pub fn alloc_ptr(&mut self, ty: Ty<'tcx>) -> EvalResult<'tcx, Pointer> {
        let substs = self.substs();
        self.alloc_ptr_with_substs(ty, substs)
    }

    pub fn alloc_ptr_with_substs(
151 152 153 154
        &mut self,
        ty: Ty<'tcx>,
        substs: &'tcx Substs<'tcx>
    ) -> EvalResult<'tcx, Pointer> {
155 156
        let size = self.type_size_with_substs(ty, substs)?.expect("cannot alloc memory for unsized type");
        let align = self.type_align_with_substs(ty, substs)?;
S
Scott Olson 已提交
157
        self.memory.allocate(size, align)
158
    }
O
Oliver Schneider 已提交
159

160
    pub fn memory(&self) -> &Memory<'a, 'tcx> {
161 162 163
        &self.memory
    }

164
    pub fn memory_mut(&mut self) -> &mut Memory<'a, 'tcx> {
O
Oliver Schneider 已提交
165 166 167
        &mut self.memory
    }

168
    pub fn stack(&self) -> &[Frame<'tcx>] {
169 170 171
        &self.stack
    }

172 173
    pub(crate) fn str_to_value(&mut self, s: &str) -> EvalResult<'tcx, Value> {
        let ptr = self.memory.allocate_cached(s.as_bytes())?;
O
Oliver Schneider 已提交
174
        Ok(Value::ByValPair(PrimVal::Ptr(ptr), PrimVal::from_u128(s.len() as u128)))
175 176
    }

177
    pub(super) fn const_to_value(&mut self, const_val: &ConstVal<'tcx>) -> EvalResult<'tcx, Value> {
178
        use rustc::middle::const_val::ConstVal::*;
S
Scott Olson 已提交
179
        use rustc_const_math::ConstFloat;
180 181

        let primval = match *const_val {
O
Oliver Schneider 已提交
182
            Integral(const_int) => PrimVal::Bytes(const_int.to_u128_unchecked()),
S
Scott Olson 已提交
183 184 185 186 187 188

            Float(ConstFloat::F32(f)) => PrimVal::from_f32(f),
            Float(ConstFloat::F64(f)) => PrimVal::from_f64(f),

            Bool(b) => PrimVal::from_bool(b),
            Char(c) => PrimVal::from_char(c),
189

190
            Str(ref s) => return self.str_to_value(s),
191

192
            ByteStr(ref bs) => {
193
                let ptr = self.memory.allocate_cached(bs)?;
194
                PrimVal::Ptr(ptr)
195
            }
196

197
            Variant(_)   => unimplemented!(),
198 199
            Struct(_)    => unimplemented!(),
            Tuple(_)     => unimplemented!(),
200 201
            // function items are zero sized and thus have no readable value
            Function(..)  => PrimVal::Undef,
S
Scott Olson 已提交
202
            Array(_)     => unimplemented!(),
203 204 205
            Repeat(_, _) => unimplemented!(),
        };

206
        Ok(Value::ByVal(primval))
207 208
    }

209
    pub(super) fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
O
Oliver Schneider 已提交
210
        // generics are weird, don't run this function on a generic
211
        assert!(!ty.needs_subst());
212
        ty.is_sized(self.tcx, ty::ParamEnv::empty(Reveal::All), DUMMY_SP)
213 214
    }

215
    pub fn load_mir(&self, instance: ty::InstanceDef<'tcx>) -> EvalResult<'tcx, &'tcx mir::Mir<'tcx>> {
O
Oliver Schneider 已提交
216 217
        trace!("load mir {:?}", instance);
        match instance {
218
            ty::InstanceDef::Item(def_id) => self.tcx.maybe_optimized_mir(def_id).ok_or_else(|| EvalError::NoMirFor(self.tcx.item_path_str(def_id))),
O
Oliver Schneider 已提交
219
            _ => Ok(self.tcx.instance_mir(instance)),
220 221
        }
    }
O
Oliver Schneider 已提交
222

223
    pub fn monomorphize(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
O
Oliver Schneider 已提交
224 225 226 227
        // miri doesn't care about lifetimes, and will choke on some crazy ones
        // let's simply get rid of them
        let without_lifetimes = self.tcx.erase_regions(&ty);
        let substituted = without_lifetimes.subst(self.tcx, substs);
S
Scott Olson 已提交
228
        self.tcx.normalize_associated_type(&substituted)
O
Oliver Schneider 已提交
229 230
    }

231 232 233 234 235 236 237
    pub fn erase_lifetimes<T>(&self, value: &Binder<T>) -> T
        where T : TypeFoldable<'tcx>
    {
        let value = self.tcx.erase_late_bound_regions(value);
        self.tcx.erase_regions(&value)
    }

238
    pub(super) fn type_size(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, Option<u64>> {
239
        self.type_size_with_substs(ty, self.substs())
O
Oliver Schneider 已提交
240 241
    }

242
    pub(super) fn type_align(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, u64> {
243 244 245
        self.type_align_with_substs(ty, self.substs())
    }

246 247 248 249 250
    fn type_size_with_substs(
        &self,
        ty: Ty<'tcx>,
        substs: &'tcx Substs<'tcx>,
    ) -> EvalResult<'tcx, Option<u64>> {
251
        let layout = self.type_layout_with_substs(ty, substs)?;
252
        if layout.is_unsized() {
253
            Ok(None)
254
        } else {
255
            Ok(Some(layout.size(&self.tcx.data_layout).bytes()))
256
        }
257 258
    }

259 260
    fn type_align_with_substs(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> EvalResult<'tcx, u64> {
        self.type_layout_with_substs(ty, substs).map(|layout| layout.align(&self.tcx.data_layout).abi())
261 262
    }

263
    pub(super) fn type_layout(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, &'tcx Layout> {
264 265 266
        self.type_layout_with_substs(ty, self.substs())
    }

267
    fn type_layout_with_substs(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> EvalResult<'tcx, &'tcx Layout> {
O
Oliver Schneider 已提交
268 269 270
        // TODO(solson): Is this inefficient? Needs investigation.
        let ty = self.monomorphize(ty, substs);

271
        ty.layout(self.tcx, ty::ParamEnv::empty(Reveal::All)).map_err(EvalError::Layout)
O
Oliver Schneider 已提交
272
    }
273

O
Oliver Schneider 已提交
274 275
    pub fn push_stack_frame(
        &mut self,
O
Oliver Schneider 已提交
276
        instance: ty::Instance<'tcx>,
O
Oliver Schneider 已提交
277
        span: codemap::Span,
278
        mir: &'tcx mir::Mir<'tcx>,
O
Oliver Schneider 已提交
279
        return_lvalue: Lvalue<'tcx>,
280
        return_to_block: StackPopCleanup,
281
    ) -> EvalResult<'tcx> {
282 283
        ::log_settings::settings().indentation += 1;

R
Ralf Jung 已提交
284
        /// Return the set of locals that have a storage annotation anywhere
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        fn collect_storage_annotations<'tcx>(mir: &'tcx mir::Mir<'tcx>) -> HashSet<mir::Local> {
            use rustc::mir::StatementKind::*;

            let mut set = HashSet::new();
            for block in mir.basic_blocks() {
                for stmt in block.statements.iter() {
                    match stmt.kind {
                        StorageLive(mir::Lvalue::Local(local)) | StorageDead(mir::Lvalue::Local(local)) => {
                            set.insert(local);
                        }
                        _ => {}
                    }
                }
            };
            set
        }

S
Scott Olson 已提交
302 303
        // Subtract 1 because `local_decls` includes the ReturnPointer, but we don't store a local
        // `Value` for that.
304
        let annotated_locals = collect_storage_annotations(mir);
S
Scott Olson 已提交
305
        let num_locals = mir.local_decls.len() - 1;
R
Ralf Jung 已提交
306
        let mut locals = vec![None; num_locals];
307 308
        for i in 0..num_locals {
            let local = mir::Local::new(i+1);
R
Ralf Jung 已提交
309 310 311
            if !annotated_locals.contains(&local) {
                locals[i] = Some(Value::ByVal(PrimVal::Undef));
            }
312
        }
313

314
        self.stack.push(Frame {
S
Scott Olson 已提交
315
            mir,
316
            block: mir::START_BLOCK,
S
Scott Olson 已提交
317 318 319 320
            return_to_block,
            return_lvalue,
            locals,
            span,
O
Oliver Schneider 已提交
321
            instance,
322
            stmt: 0,
323
        });
324

325 326 327 328 329
        if self.stack.len() > self.stack_limit {
            Err(EvalError::StackFrameLimitReached)
        } else {
            Ok(())
        }
330 331
    }

332
    pub(super) fn pop_stack_frame(&mut self) -> EvalResult<'tcx> {
333
        ::log_settings::settings().indentation -= 1;
334
        let frame = self.stack.pop().expect("tried to pop a stack frame, but there were none");
335
        match frame.return_to_block {
O
Oliver Schneider 已提交
336
            StackPopCleanup::MarkStatic(mutable) => if let Lvalue::Global(id) = frame.return_lvalue {
337
                let global_value = self.globals.get_mut(&id)
O
Oliver Schneider 已提交
338
                    .expect("global should have been cached (static)");
339
                match global_value.value {
340
                    Value::ByRef(ptr) => self.memory.mark_static_initalized(ptr.alloc_id, mutable)?,
341
                    Value::ByVal(val) => if let PrimVal::Ptr(ptr) = val {
342
                        self.memory.mark_inner_allocation(ptr.alloc_id, mutable)?;
343
                    },
344 345
                    Value::ByValPair(val1, val2) => {
                        if let PrimVal::Ptr(ptr) = val1 {
346
                            self.memory.mark_inner_allocation(ptr.alloc_id, mutable)?;
347
                        }
348
                        if let PrimVal::Ptr(ptr) = val2 {
349
                            self.memory.mark_inner_allocation(ptr.alloc_id, mutable)?;
350 351 352
                        }
                    },
                }
353 354 355
                // see comment on `initialized` field
                assert!(!global_value.initialized);
                global_value.initialized = true;
356
                assert!(global_value.mutable);
357
                global_value.mutable = mutable;
358
            } else {
O
Oliver Schneider 已提交
359
                bug!("StackPopCleanup::MarkStatic on: {:?}", frame.return_lvalue);
360
            },
361 362
            StackPopCleanup::Goto(target) => self.goto_block(target),
            StackPopCleanup::None => {},
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
            StackPopCleanup::Tls(key) => {
                // either fetch the next dtor or start new from the beginning, if any are left with a non-null data
                if let Some((instance, ptr, key)) = self.memory.fetch_tls_dtor(key).or_else(|| self.memory.fetch_tls_dtor(None)) {
                    trace!("Running TLS dtor {:?} on {:?}", instance, ptr);
                    // TODO: Potentially, this has to support all the other possible instances? See eval_fn_call in terminator/mod.rs
                    let mir = self.load_mir(instance.def)?;
                    self.push_stack_frame(
                        instance,
                        mir.span,
                        mir,
                        Lvalue::zst(),
                        StackPopCleanup::Tls(Some(key)),
                    )?;
                    let arg_local = self.frame().mir.args_iter().next().ok_or(EvalError::AbiViolation("TLS dtor does not take enough arguments.".to_owned()))?;
                    let dest = self.eval_lvalue(&mir::Lvalue::Local(arg_local))?;
                    let ty = self.tcx.mk_mut_ptr(self.tcx.types.u8);
                    self.write_primval(dest, ptr, ty)?;
                }
            }
382
        }
O
Oliver Schneider 已提交
383
        // deallocate all locals that are backed by an allocation
S
Scott Olson 已提交
384
        for local in frame.locals {
385
            self.deallocate_local(local)?;
386
        }
O
Oliver Schneider 已提交
387

388
        Ok(())
389 390
    }

391 392 393 394 395 396 397 398 399 400 401 402 403 404
    pub fn deallocate_local(&mut self, local: Option<Value>) -> EvalResult<'tcx> {
        if let Some(Value::ByRef(ptr)) = local {
            trace!("deallocating local");
            self.memory.dump_alloc(ptr.alloc_id);
            match self.memory.deallocate(ptr) {
                // We could alternatively check whether the alloc_id is static before calling
                // deallocate, but this is much simpler and is probably the rare case.
                Ok(()) | Err(EvalError::DeallocatedStaticMemory) => {},
                other => return other,
            }
        };
        Ok(())
    }

405 406 407 408
    pub fn assign_discr_and_fields<
        V: IntoValTyPair<'tcx>,
        J: IntoIterator<Item = V>,
    >(
409
        &mut self,
410
        dest: Lvalue<'tcx>,
411 412
        dest_ty: Ty<'tcx>,
        discr_offset: u64,
413 414
        operands: J,
        discr_val: u128,
415
        variant_idx: usize,
416
        discr_size: u64,
417 418 419
    ) -> EvalResult<'tcx>
        where J::IntoIter: ExactSizeIterator,
    {
420
        // FIXME(solson)
421
        let dest_ptr = self.force_allocation(dest)?.to_ptr()?;
422

423
        let discr_dest = dest_ptr.offset(discr_offset, self.memory.layout)?;
424 425
        self.memory.write_uint(discr_dest, discr_val, discr_size)?;

426
        let dest = Lvalue::Ptr {
427
            ptr: PrimVal::Ptr(dest_ptr),
428 429 430 431
            extra: LvalueExtra::DowncastVariant(variant_idx),
        };

        self.assign_fields(dest, dest_ty, operands)
432 433 434 435 436 437 438 439
    }

    pub fn assign_fields<
        V: IntoValTyPair<'tcx>,
        J: IntoIterator<Item = V>,
    >(
        &mut self,
        dest: Lvalue<'tcx>,
440
        dest_ty: Ty<'tcx>,
441
        operands: J,
442 443 444 445 446 447 448 449 450 451 452 453 454
    ) -> EvalResult<'tcx>
        where J::IntoIter: ExactSizeIterator,
    {
        if self.type_size(dest_ty)? == Some(0) {
            // zst assigning is a nop
            return Ok(());
        }
        if self.ty_to_primval_kind(dest_ty).is_ok() {
            let mut iter = operands.into_iter();
            assert_eq!(iter.len(), 1);
            let (value, value_ty) = iter.next().unwrap().into_val_ty_pair(self)?;
            return self.write_value(value, dest, value_ty);
        }
455
        for (field_index, operand) in operands.into_iter().enumerate() {
456
            let (value, value_ty) = operand.into_val_ty_pair(self)?;
457 458
            let field_dest = self.lvalue_field(dest, field_index, dest_ty, value_ty)?;
            self.write_value(value, field_dest, value_ty)?;
459 460 461 462
        }
        Ok(())
    }

463 464 465 466
    /// Evaluate an assignment statement.
    ///
    /// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
    /// type writes its results directly into the memory specified by the lvalue.
467
    pub(super) fn eval_rvalue_into_lvalue(
468 469 470
        &mut self,
        rvalue: &mir::Rvalue<'tcx>,
        lvalue: &mir::Lvalue<'tcx>,
471
    ) -> EvalResult<'tcx> {
472
        let dest = self.eval_lvalue(lvalue)?;
S
Scott Olson 已提交
473
        let dest_ty = self.lvalue_ty(lvalue);
474
        let dest_layout = self.type_layout(dest_ty)?;
475

476
        use rustc::mir::Rvalue::*;
477
        match *rvalue {
478
            Use(ref operand) => {
479 480
                let value = self.eval_operand(operand)?;
                self.write_value(value, dest, dest_ty)?;
481
            }
482

483
            BinaryOp(bin_op, ref left, ref right) => {
484 485 486
                if self.intrinsic_overflowing(bin_op, left, right, dest, dest_ty)? {
                    // There was an overflow in an unchecked binop.  Right now, we consider this an error and bail out.
                    // The rationale is that the reason rustc emits unchecked binops in release mode (vs. the checked binops
R
typos  
Ralf Jung 已提交
487
                    // it emits in debug mode) is performance, but it doesn't cost us any performance in miri.
488 489 490 491
                    // If, however, the compiler ever starts transforming unchecked intrinsics into unchecked binops,
                    // we have to go back to just ignoring the overflow here.
                    return Err(EvalError::OverflowingMath);
                }
492
            }
493

494
            CheckedBinaryOp(bin_op, ref left, ref right) => {
495
                self.intrinsic_with_overflow(bin_op, left, right, dest, dest_ty)?;
496
            }
497

498
            UnaryOp(un_op, ref operand) => {
499
                let val = self.eval_operand_to_primval(operand)?;
500
                let kind = self.ty_to_primval_kind(dest_ty)?;
501
                self.write_primval(dest, operator::unary_op(un_op, val, kind)?, dest_ty)?;
502
            }
503

O
Oliver Schneider 已提交
504 505 506
            // Skip everything for zsts
            Aggregate(..) if self.type_size(dest_ty)? == Some(0) => {}

507
            Aggregate(ref kind, ref operands) => {
508
                self.inc_step_counter_and_check_limit(operands.len() as u64)?;
509
                use rustc::ty::layout::Layout::*;
510
                match *dest_layout {
511
                    Univariant { ref variant, .. } => {
512
                        if variant.packed {
513
                            let ptr = self.force_allocation(dest)?.to_ptr_and_extra().0.to_ptr()?;
514 515
                            self.memory.mark_packed(ptr, variant.stride().bytes());
                        }
516
                        self.assign_fields(dest, dest_ty, operands)?;
517 518
                    }

519
                    Array { .. } => {
520
                        self.assign_fields(dest, dest_ty, operands)?;
521
                    }
522

523
                    General { discr, ref variants, .. } => {
D
David Renshaw 已提交
524
                        if let mir::AggregateKind::Adt(adt_def, variant, _, _) = **kind {
525 526 527 528
                            let discr_val = adt_def.discriminants(self.tcx)
                                .nth(variant)
                                .expect("broken mir: Adt variant id invalid")
                                .to_u128_unchecked();
529
                            let discr_size = discr.size().bytes();
530
                            if variants[variant].packed {
531
                                let ptr = self.force_allocation(dest)?.to_ptr_and_extra().0.to_ptr()?;
532 533
                                self.memory.mark_packed(ptr, variants[variant].stride().bytes());
                            }
534

535 536
                            self.assign_discr_and_fields(
                                dest,
537 538
                                dest_ty,
                                variants[variant].offsets[0].bytes(),
539 540
                                operands,
                                discr_val,
541
                                variant,
542 543
                                discr_size,
                            )?;
544
                        } else {
545
                            bug!("tried to assign {:?} to Layout::General", kind);
S
Scott Olson 已提交
546
                        }
547 548
                    }

549
                    RawNullablePointer { nndiscr, .. } => {
D
David Renshaw 已提交
550
                        if let mir::AggregateKind::Adt(_, variant, _, _) = **kind {
551 552 553
                            if nndiscr == variant as u64 {
                                assert_eq!(operands.len(), 1);
                                let operand = &operands[0];
554 555 556
                                let value = self.eval_operand(operand)?;
                                let value_ty = self.operand_ty(operand);
                                self.write_value(value, dest, value_ty)?;
557
                            } else {
558 559 560
                                if let Some(operand) = operands.get(0) {
                                    assert_eq!(operands.len(), 1);
                                    let operand_ty = self.operand_ty(operand);
561
                                    assert_eq!(self.type_size(operand_ty)?, Some(0));
562
                                }
S
Scott Olson 已提交
563
                                self.write_primval(dest, PrimVal::Bytes(0), dest_ty)?;
564 565
                            }
                        } else {
566
                            bug!("tried to assign {:?} to Layout::RawNullablePointer", kind);
S
Scott Olson 已提交
567
                        }
568 569
                    }

S
Scott Olson 已提交
570
                    StructWrappedNullablePointer { nndiscr, ref nonnull, ref discrfield, .. } => {
D
David Renshaw 已提交
571
                        if let mir::AggregateKind::Adt(_, variant, _, _) = **kind {
572
                            if nonnull.packed {
573
                                let ptr = self.force_allocation(dest)?.to_ptr_and_extra().0.to_ptr()?;
574 575
                                self.memory.mark_packed(ptr, nonnull.stride().bytes());
                            }
576
                            if nndiscr == variant as u64 {
577
                                self.assign_fields(dest, dest_ty, operands)?;
578
                            } else {
579 580
                                for operand in operands {
                                    let operand_ty = self.operand_ty(operand);
581
                                    assert_eq!(self.type_size(operand_ty)?, Some(0));
582
                                }
583
                                let (offset, ty) = self.nonnull_offset_and_ty(dest_ty, nndiscr, discrfield)?;
584 585

                                // FIXME(solson)
586
                                let dest = self.force_allocation(dest)?.to_ptr()?;
587

588
                                let dest = dest.offset(offset.bytes(), self.memory.layout)?;
589 590
                                let dest_size = self.type_size(ty)?
                                    .expect("bad StructWrappedNullablePointer discrfield");
S
Scott Olson 已提交
591
                                self.memory.write_int(dest, 0, dest_size)?;
592 593
                            }
                        } else {
594
                            bug!("tried to assign {:?} to Layout::RawNullablePointer", kind);
595 596 597
                        }
                    }

598
                    CEnum { .. } => {
599
                        assert_eq!(operands.len(), 0);
D
David Renshaw 已提交
600
                        if let mir::AggregateKind::Adt(adt_def, variant, _, _) = **kind {
601 602 603 604
                            let n = adt_def.discriminants(self.tcx)
                                .nth(variant)
                                .expect("broken mir: Adt variant index invalid")
                                .to_u128_unchecked();
605
                            self.write_primval(dest, PrimVal::Bytes(n), dest_ty)?;
606
                        } else {
607
                            bug!("tried to assign {:?} to Layout::CEnum", kind);
608 609 610
                        }
                    }

611
                    Vector { count, .. } => {
O
Oliver Schneider 已提交
612
                        debug_assert_eq!(count, operands.len() as u64);
613
                        self.assign_fields(dest, dest_ty, operands)?;
O
Oliver Schneider 已提交
614 615
                    }

S
Scott Olson 已提交
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
                    UntaggedUnion { .. } => {
                        assert_eq!(operands.len(), 1);
                        let operand = &operands[0];
                        let value = self.eval_operand(operand)?;
                        let value_ty = self.operand_ty(operand);
                        self.write_value(value, dest, value_ty)?;
                    }

                    _ => {
                        return Err(EvalError::Unimplemented(format!(
                            "can't handle destination layout {:?} when assigning {:?}",
                            dest_layout,
                            kind
                        )));
                    }
631
                }
632
            }
633

634
            Repeat(ref operand, _) => {
635
                let (elem_ty, length) = match dest_ty.sty {
636
                    ty::TyArray(elem_ty, n) => (elem_ty, n as u64),
637
                    _ => bug!("tried to assign array-repeat to non-array type {:?}", dest_ty),
638
                };
639
                self.inc_step_counter_and_check_limit(length)?;
640 641
                let elem_size = self.type_size(elem_ty)?
                    .expect("repeat element type must be sized");
642
                let value = self.eval_operand(operand)?;
643 644

                // FIXME(solson)
645
                let dest = PrimVal::Ptr(self.force_allocation(dest)?.to_ptr()?);
646

647
                for i in 0..length {
648
                    let elem_dest = dest.offset(i * elem_size, self.memory.layout)?;
649
                    self.write_value_to_ptr(value, elem_dest, elem_ty)?;
650 651
                }
            }
652

653
            Len(ref lvalue) => {
S
Scott Olson 已提交
654
                let src = self.eval_lvalue(lvalue)?;
655
                let ty = self.lvalue_ty(lvalue);
O
Oliver Schneider 已提交
656
                let (_, len) = src.elem_ty_and_len(ty);
O
Oliver Schneider 已提交
657
                self.write_primval(dest, PrimVal::from_u128(len as u128), dest_ty)?;
658 659
            }

S
Scott Olson 已提交
660
            Ref(_, _, ref lvalue) => {
661
                let src = self.eval_lvalue(lvalue)?;
662
                let (ptr, extra) = self.force_allocation(src)?.to_ptr_and_extra();
663

664 665
                let val = match extra {
                    LvalueExtra::None => Value::ByVal(ptr),
O
Oliver Schneider 已提交
666
                    LvalueExtra::Length(len) => Value::ByValPair(ptr, PrimVal::from_u128(len as u128)),
667
                    LvalueExtra::Vtable(vtable) => Value::ByValPair(ptr, PrimVal::Ptr(vtable)),
668 669
                    LvalueExtra::DowncastVariant(..) =>
                        bug!("attempted to take a reference to an enum downcast lvalue"),
670 671 672
                };

                self.write_value(val, dest, dest_ty)?;
S
Scott Olson 已提交
673
            }
S
Scott Olson 已提交
674

D
David Renshaw 已提交
675
            NullaryOp(mir::NullOp::Box, ty) => {
676
                let ptr = self.alloc_ptr(ty)?;
677
                self.write_primval(dest, PrimVal::Ptr(ptr), dest_ty)?;
S
Scott Olson 已提交
678 679
            }

680 681 682
            NullaryOp(mir::NullOp::SizeOf, ty) => {
                let size = self.type_size(ty)?.expect("SizeOf nullary MIR operator called for unsized type");
                self.write_primval(dest, PrimVal::from_u128(size as u128), dest_ty)?;
D
David Renshaw 已提交
683 684
            }

685 686
            Cast(kind, ref operand, cast_ty) => {
                debug_assert_eq!(self.monomorphize(cast_ty, self.substs()), dest_ty);
687
                use rustc::mir::CastKind::*;
688 689
                match kind {
                    Unsize => {
690
                        let src = self.eval_operand(operand)?;
O
Oliver Schneider 已提交
691
                        let src_ty = self.operand_ty(operand);
692
                        self.unsize_into(src, src_ty, dest, dest_ty)?;
693 694 695
                    }

                    Misc => {
696
                        let src = self.eval_operand(operand)?;
697
                        let src_ty = self.operand_ty(operand);
698
                        if self.type_is_fat_ptr(src_ty) {
699
                            match (src, self.type_is_fat_ptr(dest_ty)) {
700 701 702
                                (Value::ByRef(_), _) |
                                (Value::ByValPair(..), true) => {
                                    self.write_value(src, dest, dest_ty)?;
703
                                },
704
                                (Value::ByValPair(data, _), false) => {
705
                                    self.write_value(Value::ByVal(data), dest, dest_ty)?;
706 707
                                },
                                (Value::ByVal(_), _) => bug!("expected fat ptr"),
O
Oliver Schneider 已提交
708
                            }
709
                        } else {
R
Ralf Jung 已提交
710 711 712 713 714 715 716 717 718 719 720 721 722
                            // First, try casting
                            let dest_val = self.value_to_primval(src, src_ty).and_then(
                                |src_val| { self.cast_primval(src_val, src_ty, dest_ty) })
                                // Alternatively, if the sizes are equal, try just reading at the target type
                                .or_else(|err| {
                                    let size = self.type_size(src_ty)?;
                                    if size.is_some() && size == self.type_size(dest_ty)? {
                                        self.value_to_primval(src, dest_ty)
                                    } else {
                                        Err(err)
                                    }
                                });
                            self.write_value(Value::ByVal(dest_val?), dest, dest_ty)?;
723
                        }
724 725
                    }

O
Oliver Schneider 已提交
726
                    ReifyFnPointer => match self.operand_ty(operand).sty {
O
Oliver Schneider 已提交
727
                        ty::TyFnDef(def_id, substs, _) => {
728 729
                            let instance = resolve(self.tcx, def_id, substs);
                            let fn_ptr = self.memory.create_fn_alloc(instance);
730
                            self.write_value(Value::ByVal(PrimVal::Ptr(fn_ptr)), dest, dest_ty)?;
O
Oliver Schneider 已提交
731
                        },
732
                        ref other => bug!("reify fn pointer on {:?}", other),
O
Oliver Schneider 已提交
733 734
                    },

735
                    UnsafeFnPointer => match dest_ty.sty {
736
                        ty::TyFnPtr(_) => {
737
                            let src = self.eval_operand(operand)?;
738
                            self.write_value(src, dest, dest_ty)?;
739
                        },
740
                        ref other => bug!("fn to unsafe fn cast on {:?}", other),
741
                    },
742 743 744

                    ClosureFnPointer => match self.operand_ty(operand).sty {
                        ty::TyClosure(def_id, substs) => {
O
Oliver Schneider 已提交
745 746
                            let instance = resolve_closure(self.tcx, def_id, substs, ty::ClosureKind::FnOnce);
                            let fn_ptr = self.memory.create_fn_alloc(instance);
747 748
                            self.write_value(Value::ByVal(PrimVal::Ptr(fn_ptr)), dest, dest_ty)?;
                        },
749
                        ref other => bug!("closure fn pointer on {:?}", other),
750
                    },
751 752 753
                }
            }

O
rustup  
Oliver Schneider 已提交
754 755 756
            Discriminant(ref lvalue) => {
                let lval = self.eval_lvalue(lvalue)?;
                let ty = self.lvalue_ty(lvalue);
757
                let ptr = self.force_allocation(lval)?.to_ptr()?;
O
rustup  
Oliver Schneider 已提交
758 759
                let discr_val = self.read_discriminant_value(ptr, ty)?;
                if let ty::TyAdt(adt_def, _) = ty.sty {
760
                    if adt_def.discriminants(self.tcx).all(|v| discr_val != v.to_u128_unchecked()) {
O
rustup  
Oliver Schneider 已提交
761 762 763 764 765 766 767
                        return Err(EvalError::InvalidDiscriminant);
                    }
                } else {
                    bug!("rustc only generates Rvalue::Discriminant for enums");
                }
                self.write_primval(dest, PrimVal::Bytes(discr_val), dest_ty)?;
            },
768
        }
769

S
Scott Olson 已提交
770 771 772 773
        if log_enabled!(::log::LogLevel::Trace) {
            self.dump_local(dest);
        }

774
        Ok(())
775 776
    }

O
Oliver Schneider 已提交
777 778
    fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
        match ty.sty {
O
rustup  
Oliver Schneider 已提交
779 780 781
            ty::TyRawPtr(ref tam) |
            ty::TyRef(_, ref tam) => !self.type_is_sized(tam.ty),
            ty::TyAdt(def, _) if def.is_box() => !self.type_is_sized(ty.boxed_ty()),
O
Oliver Schneider 已提交
782 783 784 785
            _ => false,
        }
    }

786 787 788 789 790 791
    pub(super) fn nonnull_offset_and_ty(
        &self,
        ty: Ty<'tcx>,
        nndiscr: u64,
        discrfield: &[u32],
    ) -> EvalResult<'tcx, (Size, Ty<'tcx>)> {
792 793
        // Skip the constant 0 at the start meant for LLVM GEP and the outer non-null variant
        let path = discrfield.iter().skip(2).map(|&i| i as usize);
794 795

        // Handle the field index for the outer non-null variant.
796
        let (inner_offset, inner_ty) = match ty.sty {
S
Scott Olson 已提交
797
            ty::TyAdt(adt_def, substs) => {
798
                let variant = &adt_def.variants[nndiscr as usize];
799 800
                let index = discrfield[1];
                let field = &variant.fields[index as usize];
801
                (self.get_field_offset(ty, index as usize)?, field.ty(self.tcx, substs))
802
            }
803
            _ => bug!("non-enum for StructWrappedNullablePointer: {}", ty),
804 805
        };

806
        self.field_path_offset_and_ty(inner_offset, inner_ty, path)
807 808
    }

809 810 811 812 813 814
    fn field_path_offset_and_ty<I: Iterator<Item = usize>>(
        &self,
        mut offset: Size,
        mut ty: Ty<'tcx>,
        path: I,
    ) -> EvalResult<'tcx, (Size, Ty<'tcx>)> {
815 816
        // Skip the initial 0 intended for LLVM GEP.
        for field_index in path {
817
            let field_offset = self.get_field_offset(ty, field_index)?;
818
            trace!("field_path_offset_and_ty: {}, {}, {:?}, {:?}", field_index, ty, field_offset, offset);
819
            ty = self.get_field_ty(ty, field_index)?;
820 821 822
            offset = offset.checked_add(field_offset, &self.tcx.data_layout).unwrap();
        }

823
        Ok((offset, ty))
824
    }
O
rustup  
Oliver Schneider 已提交
825 826 827 828 829 830 831 832 833
    fn get_fat_field(&self, pointee_ty: Ty<'tcx>, field_index: usize) -> EvalResult<'tcx, Ty<'tcx>> {
        match (field_index, &self.tcx.struct_tail(pointee_ty).sty) {
            (1, &ty::TyStr) |
            (1, &ty::TySlice(_)) => Ok(self.tcx.types.usize),
            (1, &ty::TyDynamic(..)) |
            (0, _) => Ok(self.tcx.mk_imm_ptr(self.tcx.types.u8)),
            _ => bug!("invalid fat pointee type: {}", pointee_ty),
        }
    }
834

O
Oliver Schneider 已提交
835
    pub fn get_field_ty(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<'tcx, Ty<'tcx>> {
836
        match ty.sty {
O
rustup  
Oliver Schneider 已提交
837
            ty::TyAdt(adt_def, _) if adt_def.is_box() => self.get_fat_field(ty.boxed_ty(), field_index),
S
Scott Olson 已提交
838
            ty::TyAdt(adt_def, substs) => {
839
                Ok(adt_def.struct_variant().fields[field_index].ty(self.tcx, substs))
840 841
            }

S
Scott Olson 已提交
842
            ty::TyTuple(fields, _) => Ok(fields[field_index]),
843

O
rustup  
Oliver Schneider 已提交
844 845
            ty::TyRef(_, ref tam) |
            ty::TyRawPtr(ref tam) => self.get_fat_field(tam.ty, field_index),
846
            _ => Err(EvalError::Unimplemented(format!("can't handle type: {:?}, {:?}", ty, ty.sty))),
847 848 849
        }
    }

850
    fn get_field_offset(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<'tcx, Size> {
851
        let layout = self.type_layout(ty)?;
852 853 854

        use rustc::ty::layout::Layout::*;
        match *layout {
855
            Univariant { ref variant, .. } => {
S
Scott Olson 已提交
856
                Ok(variant.offsets[field_index])
857 858
            }
            FatPointer { .. } => {
859 860
                let bytes = field_index as u64 * self.memory.pointer_size();
                Ok(Size::from_bytes(bytes))
861
            }
862 863 864
            StructWrappedNullablePointer { ref nonnull, .. } => {
                Ok(nonnull.offsets[field_index])
            }
865 866 867 868 869 870 871
            _ => {
                let msg = format!("can't handle type: {:?}, with layout: {:?}", ty, layout);
                Err(EvalError::Unimplemented(msg))
            }
        }
    }

872
    pub fn get_field_count(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, usize> {
873
        let layout = self.type_layout(ty)?;
874 875 876 877 878

        use rustc::ty::layout::Layout::*;
        match *layout {
            Univariant { ref variant, .. } => Ok(variant.offsets.len()),
            FatPointer { .. } => Ok(2),
879
            StructWrappedNullablePointer { ref nonnull, .. } => Ok(nonnull.offsets.len()),
880 881 882 883
            _ => {
                let msg = format!("can't handle type: {:?}, with layout: {:?}", ty, layout);
                Err(EvalError::Unimplemented(msg))
            }
884 885 886
        }
    }

887
    pub(super) fn wrapping_pointer_offset(&self, ptr: PrimVal, pointee_ty: Ty<'tcx>, offset: i64) -> EvalResult<'tcx, PrimVal> {
888 889 890
        // FIXME: assuming here that type size is < i64::max_value()
        let pointee_size = self.type_size(pointee_ty)?.expect("cannot offset a pointer to an unsized type") as i64;
        let offset = offset.overflowing_mul(pointee_size).0;
891
        ptr.wrapping_signed_offset(offset, self.memory.layout)
892 893
    }

894
    pub(super) fn pointer_offset(&self, ptr: PrimVal, pointee_ty: Ty<'tcx>, offset: i64) -> EvalResult<'tcx, PrimVal> {
R
Ralf Jung 已提交
895 896
        if ptr == PrimVal::from_u128(0) { // rule out NULL pointers
            return Err(EvalError::InvalidPointerMath);
897
        }
898 899
        // FIXME: assuming here that type size is < i64::max_value()
        let pointee_size = self.type_size(pointee_ty)?.expect("cannot offset a pointer to an unsized type") as i64;
900
        return if let Some(offset) = offset.checked_mul(pointee_size) {
901
            let ptr = ptr.signed_offset(offset, self.memory.layout)?;
R
Ralf Jung 已提交
902 903 904 905 906 907
            // Do not do bounds-checking for integers or ZST; they can never alias a normal pointer anyway.
            if let PrimVal::Ptr(ptr) = ptr {
                if !ptr.points_to_zst() {
                    self.memory.check_bounds(ptr, false)?;
                }
            }
908
            Ok(ptr)
909
        } else {
910
            Err(EvalError::OverflowingMath)
911
        }
912 913
    }

914
    pub(super) fn eval_operand_to_primval(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<'tcx, PrimVal> {
915 916 917 918 919
        let value = self.eval_operand(op)?;
        let ty = self.operand_ty(op);
        self.value_to_primval(value, ty)
    }

920
    pub(super) fn eval_operand(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<'tcx, Value> {
921
        use rustc::mir::Operand::*;
922
        match *op {
923
            Consume(ref lvalue) => self.eval_and_read_lvalue(lvalue),
924

D
David Renshaw 已提交
925
            Constant(ref constant) => {
926
                use rustc::mir::Literal;
D
David Renshaw 已提交
927
                let mir::Constant { ref literal, .. } = **constant;
928
                let value = match *literal {
929
                    Literal::Value { ref value } => self.const_to_value(value)?,
930 931

                    Literal::Item { def_id, substs } => {
932 933 934
                        let instance = self.resolve_associated_const(def_id, substs);
                        let cid = GlobalId { instance, promoted: None };
                        self.globals.get(&cid).expect("static/const not cached").value
935 936 937
                    }

                    Literal::Promoted { index } => {
938
                        let cid = GlobalId {
O
Oliver Schneider 已提交
939
                            instance: self.frame().instance,
O
Oliver Schneider 已提交
940
                            promoted: Some(index),
941
                        };
942
                        self.globals.get(&cid).expect("promoted not cached").value
943 944 945 946
                    }
                };

                Ok(value)
947 948 949
            }
        }
    }
S
Scott Olson 已提交
950

951
    pub(super) fn operand_ty(&self, operand: &mir::Operand<'tcx>) -> Ty<'tcx> {
952
        self.monomorphize(operand.ty(self.mir(), self.tcx), self.substs())
953 954
    }

955
    fn copy(&mut self, src: PrimVal, dest: PrimVal, ty: Ty<'tcx>) -> EvalResult<'tcx> {
956 957
        let size = self.type_size(ty)?.expect("cannot copy from an unsized type");
        let align = self.type_align(ty)?;
958
        self.memory.copy(src, dest, size, align)?;
S
Scott Olson 已提交
959 960 961
        Ok(())
    }

962 963 964 965
    pub(super) fn force_allocation(
        &mut self,
        lvalue: Lvalue<'tcx>,
    ) -> EvalResult<'tcx, Lvalue<'tcx>> {
966
        let new_lvalue = match lvalue {
967 968 969
            Lvalue::Local { frame, local, field } => {
                // -1 since we don't store the return value
                match self.stack[frame].locals[local.index() - 1] {
970 971
                    None => return Err(EvalError::DeadLocal),
                    Some(Value::ByRef(ptr)) => {
972 973 974
                        assert!(field.is_none());
                        Lvalue::from_ptr(ptr)
                    },
975
                    Some(val) => {
976
                        let ty = self.stack[frame].mir.local_decls[local].ty;
O
Oliver Schneider 已提交
977 978
                        let ty = self.monomorphize(ty, self.stack[frame].instance.substs);
                        let substs = self.stack[frame].instance.substs;
S
Scott Olson 已提交
979
                        let ptr = self.alloc_ptr_with_substs(ty, substs)?;
980
                        self.stack[frame].locals[local.index() - 1] = Some(Value::ByRef(ptr)); // it stays live
981
                        self.write_value_to_ptr(val, PrimVal::Ptr(ptr), ty)?;
982 983 984 985 986 987
                        let lval = Lvalue::from_ptr(ptr);
                        if let Some((field, field_ty)) = field {
                            self.lvalue_field(lval, field, ty, field_ty)?
                        } else {
                            lval
                        }
988
                    }
989
                }
990 991
            }
            Lvalue::Ptr { .. } => lvalue,
992 993
            Lvalue::Global(cid) => {
                let global_val = *self.globals.get(&cid).expect("global not cached");
994 995
                match global_val.value {
                    Value::ByRef(ptr) => Lvalue::from_ptr(ptr),
996
                    _ => {
O
Oliver Schneider 已提交
997
                        let ptr = self.alloc_ptr_with_substs(global_val.ty, cid.instance.substs)?;
998
                        self.memory.mark_static(ptr.alloc_id);
999
                        self.write_value_to_ptr(global_val.value, PrimVal::Ptr(ptr), global_val.ty)?;
1000 1001
                        // see comment on `initialized` field
                        if global_val.initialized {
1002
                            self.memory.mark_static_initalized(ptr.alloc_id, global_val.mutable)?;
1003
                        }
1004 1005
                        let lval = self.globals.get_mut(&cid).expect("already checked");
                        *lval = Global {
1006
                            value: Value::ByRef(ptr),
1007
                            .. global_val
1008 1009 1010 1011 1012
                        };
                        Lvalue::from_ptr(ptr)
                    },
                }
            }
1013 1014 1015 1016
        };
        Ok(new_lvalue)
    }

1017
    /// ensures this Value is not a ByRef
1018
    pub(super) fn follow_by_ref_value(&mut self, value: Value, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
1019
        match value {
1020 1021 1022 1023 1024
            Value::ByRef(ptr) => self.read_value(ptr, ty),
            other => Ok(other),
        }
    }

1025
    pub(super) fn value_to_primval(&mut self, value: Value, ty: Ty<'tcx>) -> EvalResult<'tcx, PrimVal> {
1026 1027
        match self.follow_by_ref_value(value, ty)? {
            Value::ByRef(_) => bug!("follow_by_ref_value can't result in `ByRef`"),
1028

1029
            Value::ByVal(primval) => {
1030 1031
                self.ensure_valid_value(primval, ty)?;
                Ok(primval)
1032 1033
            }

1034
            Value::ByValPair(..) => bug!("value_to_primval can't work with fat pointers"),
1035 1036 1037
        }
    }

1038
    pub(super) fn write_primval(
1039
        &mut self,
1040
        dest: Lvalue<'tcx>,
1041
        val: PrimVal,
1042
        dest_ty: Ty<'tcx>,
1043
    ) -> EvalResult<'tcx> {
1044
        self.write_value(Value::ByVal(val), dest, dest_ty)
1045 1046
    }

1047
    pub(super) fn write_value(
1048
        &mut self,
1049
        src_val: Value,
1050
        dest: Lvalue<'tcx>,
1051
        dest_ty: Ty<'tcx>,
1052
    ) -> EvalResult<'tcx> {
1053
        match dest {
1054 1055
            Lvalue::Global(cid) => {
                let dest = *self.globals.get_mut(&cid).expect("global should be cached");
1056 1057 1058
                if !dest.mutable {
                    return Err(EvalError::ModifiedConstantMemory);
                }
1059 1060 1061 1062
                let write_dest = |this: &mut Self, val| {
                    *this.globals.get_mut(&cid).expect("already checked") = Global {
                        value: val,
                        ..dest
1063 1064
                    };
                    Ok(())
1065 1066
                };
                self.write_value_possibly_by_val(src_val, write_dest, dest.value, dest_ty)
1067 1068
            },

1069 1070
            Lvalue::Ptr { ptr, extra } => {
                assert_eq!(extra, LvalueExtra::None);
1071
                self.write_value_to_ptr(src_val, ptr, dest_ty)
1072
            }
1073

1074
            Lvalue::Local { frame, local, field } => {
1075
                let dest = self.stack[frame].get_local(local, field.map(|(i, _)| i))?;
1076
                self.write_value_possibly_by_val(
1077
                    src_val,
1078
                    |this, val| this.stack[frame].set_local(local, field.map(|(i, _)| i), val),
1079 1080 1081
                    dest,
                    dest_ty,
                )
1082 1083
            }
        }
1084 1085 1086
    }

    // The cases here can be a bit subtle. Read carefully!
1087
    fn write_value_possibly_by_val<F: FnOnce(&mut Self, Value) -> EvalResult<'tcx>>(
1088 1089 1090
        &mut self,
        src_val: Value,
        write_dest: F,
1091
        old_dest_val: Value,
1092
        dest_ty: Ty<'tcx>,
1093
    ) -> EvalResult<'tcx> {
1094
        if let Value::ByRef(dest_ptr) = old_dest_val {
1095
            // If the value is already `ByRef` (that is, backed by an `Allocation`),
1096 1097 1098 1099 1100
            // then we must write the new value into this allocation, because there may be
            // other pointers into the allocation. These other pointers are logically
            // pointers into the local variable, and must be able to observe the change.
            //
            // Thus, it would be an error to replace the `ByRef` with a `ByVal`, unless we
1101
            // knew for certain that there were no outstanding pointers to this allocation.
1102
            self.write_value_to_ptr(src_val, PrimVal::Ptr(dest_ptr), dest_ty)?;
1103 1104

        } else if let Value::ByRef(src_ptr) = src_val {
1105
            // If the value is not `ByRef`, then we know there are no pointers to it
1106 1107 1108 1109 1110 1111 1112
            // and we can simply overwrite the `Value` in the locals array directly.
            //
            // In this specific case, where the source value is `ByRef`, we must duplicate
            // the allocation, because this is a by-value operation. It would be incorrect
            // if they referred to the same allocation, since then a change to one would
            // implicitly change the other.
            //
1113 1114 1115 1116
            // It is a valid optimization to attempt reading a primitive value out of the
            // source and write that into the destination without making an allocation, so
            // we do so here.
            if let Ok(Some(src_val)) = self.try_read_value(src_ptr, dest_ty) {
1117
                write_dest(self, src_val)?;
1118 1119
            } else {
                let dest_ptr = self.alloc_ptr(dest_ty)?;
1120
                self.copy(PrimVal::Ptr(src_ptr), PrimVal::Ptr(dest_ptr), dest_ty)?;
1121
                write_dest(self, Value::ByRef(dest_ptr))?;
1122
            }
1123 1124 1125

        } else {
            // Finally, we have the simple case where neither source nor destination are
1126
            // `ByRef`. We may simply copy the source value over the the destintion.
1127
            write_dest(self, src_val)?;
1128
        }
1129
        Ok(())
1130 1131
    }

1132
    pub(super) fn write_value_to_ptr(
1133 1134
        &mut self,
        value: Value,
1135
        dest: PrimVal,
1136
        dest_ty: Ty<'tcx>,
1137
    ) -> EvalResult<'tcx> {
1138
        match value {
1139
            Value::ByRef(ptr) => self.copy(PrimVal::Ptr(ptr), dest, dest_ty),
1140
            Value::ByVal(primval) => {
1141 1142
                let size = self.type_size(dest_ty)?.expect("dest type must be sized");
                self.memory.write_primval(dest, primval, size)
1143
            }
1144
            Value::ByValPair(a, b) => self.write_pair_to_ptr(a, b, dest.to_ptr()?, dest_ty),
1145 1146 1147
        }
    }

1148
    pub(super) fn write_pair_to_ptr(
1149 1150 1151 1152
        &mut self,
        a: PrimVal,
        b: PrimVal,
        ptr: Pointer,
1153
        mut ty: Ty<'tcx>
1154
    ) -> EvalResult<'tcx> {
1155 1156 1157
        while self.get_field_count(ty)? == 1 {
            ty = self.get_field_ty(ty, 0)?;
        }
1158
        assert_eq!(self.get_field_count(ty)?, 2);
1159 1160
        let field_0 = self.get_field_offset(ty, 0)?.bytes();
        let field_1 = self.get_field_offset(ty, 1)?.bytes();
1161 1162
        let field_0_ty = self.get_field_ty(ty, 0)?;
        let field_1_ty = self.get_field_ty(ty, 1)?;
1163 1164
        let field_0_size = self.type_size(field_0_ty)?.expect("pair element type must be sized");
        let field_1_size = self.type_size(field_1_ty)?.expect("pair element type must be sized");
1165 1166
        self.memory.write_primval(PrimVal::Ptr(ptr.offset(field_0, self.memory.layout)?), a, field_0_size)?;
        self.memory.write_primval(PrimVal::Ptr(ptr.offset(field_1, self.memory.layout)?), b, field_1_size)?;
1167 1168 1169
        Ok(())
    }

O
Oliver Schneider 已提交
1170
    pub fn ty_to_primval_kind(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, PrimValKind> {
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
        use syntax::ast::FloatTy;

        let kind = match ty.sty {
            ty::TyBool => PrimValKind::Bool,
            ty::TyChar => PrimValKind::Char,

            ty::TyInt(int_ty) => {
                use syntax::ast::IntTy::*;
                let size = match int_ty {
                    I8 => 1,
                    I16 => 2,
                    I32 => 4,
                    I64 => 8,
O
Oliver Schneider 已提交
1184
                    I128 => 16,
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
                    Is => self.memory.pointer_size(),
                };
                PrimValKind::from_int_size(size)
            }

            ty::TyUint(uint_ty) => {
                use syntax::ast::UintTy::*;
                let size = match uint_ty {
                    U8 => 1,
                    U16 => 2,
                    U32 => 4,
                    U64 => 8,
O
Oliver Schneider 已提交
1197
                    U128 => 16,
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
                    Us => self.memory.pointer_size(),
                };
                PrimValKind::from_uint_size(size)
            }

            ty::TyFloat(FloatTy::F32) => PrimValKind::F32,
            ty::TyFloat(FloatTy::F64) => PrimValKind::F64,

            ty::TyFnPtr(_) => PrimValKind::FnPtr,

O
rustup  
Oliver Schneider 已提交
1208 1209 1210
            ty::TyRef(_, ref tam) |
            ty::TyRawPtr(ref tam) if self.type_is_sized(tam.ty) => PrimValKind::Ptr,

O
Oliver Schneider 已提交
1211
            ty::TyAdt(def, _) if def.is_box() => PrimValKind::Ptr,
1212

O
Oliver Schneider 已提交
1213
            ty::TyAdt(def, substs) => {
1214
                use rustc::ty::layout::Layout::*;
1215 1216 1217 1218 1219 1220 1221 1222
                match *self.type_layout(ty)? {
                    CEnum { discr, signed, .. } => {
                        let size = discr.size().bytes();
                        if signed {
                            PrimValKind::from_int_size(size)
                        } else {
                            PrimValKind::from_uint_size(size)
                        }
1223
                    }
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235

                    RawNullablePointer { value, .. } => {
                        use rustc::ty::layout::Primitive::*;
                        match value {
                            // TODO(solson): Does signedness matter here? What should the sign be?
                            Int(int) => PrimValKind::from_uint_size(int.size().bytes()),
                            F32 => PrimValKind::F32,
                            F64 => PrimValKind::F64,
                            Pointer => PrimValKind::Ptr,
                        }
                    }

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
                    // represent single field structs as their single field
                    Univariant { .. } => {
                        // enums with just one variant are no different, but `.struct_variant()` doesn't work for enums
                        let variant = &def.variants[0];
                        // FIXME: also allow structs with only a single non zst field
                        if variant.fields.len() == 1 {
                            return self.ty_to_primval_kind(variant.fields[0].ty(self.tcx, substs));
                        } else {
                            return Err(EvalError::TypeNotPrimitive(ty));
                        }
                    }

1248
                    _ => return Err(EvalError::TypeNotPrimitive(ty)),
1249
                }
1250
            }
1251

1252
            _ => return Err(EvalError::TypeNotPrimitive(ty)),
1253 1254 1255 1256 1257
        };

        Ok(kind)
    }

1258
    fn ensure_valid_value(&self, val: PrimVal, ty: Ty<'tcx>) -> EvalResult<'tcx> {
1259
        match ty.sty {
1260
            ty::TyBool if val.to_bytes()? > 1 => Err(EvalError::InvalidBool),
1261

1262
            ty::TyChar if ::std::char::from_u32(val.to_bytes()? as u32).is_none()
O
Oliver Schneider 已提交
1263
                => Err(EvalError::InvalidChar(val.to_bytes()? as u32 as u128)),
1264 1265 1266 1267 1268

            _ => Ok(()),
        }
    }

1269
    pub(super) fn read_value(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
1270 1271 1272 1273 1274 1275 1276
        if let Some(val) = self.try_read_value(ptr, ty)? {
            Ok(val)
        } else {
            bug!("primitive read failed for type: {:?}", ty);
        }
    }

1277
    pub(crate) fn read_ptr(&self, ptr: Pointer, pointee_ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
O
rustup  
Oliver Schneider 已提交
1278 1279
        let p = self.memory.read_ptr(ptr)?;
        if self.type_is_sized(pointee_ty) {
1280
            Ok(Value::ByVal(p))
O
rustup  
Oliver Schneider 已提交
1281 1282
        } else {
            trace!("reading fat pointer extra of type {}", pointee_ty);
1283
            let extra = ptr.offset(self.memory.pointer_size(), self.memory.layout)?;
O
rustup  
Oliver Schneider 已提交
1284
            let extra = match self.tcx.struct_tail(pointee_ty).sty {
1285
                ty::TyDynamic(..) => self.memory.read_ptr(extra)?,
O
rustup  
Oliver Schneider 已提交
1286 1287 1288 1289
                ty::TySlice(..) |
                ty::TyStr => PrimVal::from_u128(self.memory.read_usize(extra)? as u128),
                _ => bug!("unsized primval ptr read from {:?}", pointee_ty),
            };
1290
            Ok(Value::ByValPair(p, extra))
O
rustup  
Oliver Schneider 已提交
1291 1292 1293
        }
    }

1294
    fn try_read_value(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<'tcx, Option<Value>> {
1295 1296
        use syntax::ast::FloatTy;

S
Scott Olson 已提交
1297
        let val = match ty.sty {
S
Scott Olson 已提交
1298
            ty::TyBool => PrimVal::from_bool(self.memory.read_bool(ptr)?),
S
Scott Olson 已提交
1299
            ty::TyChar => {
O
Oliver Schneider 已提交
1300 1301
                let c = self.memory.read_uint(ptr, 4)? as u32;
                match ::std::char::from_u32(c) {
S
Scott Olson 已提交
1302
                    Some(ch) => PrimVal::from_char(ch),
O
Oliver Schneider 已提交
1303
                    None => return Err(EvalError::InvalidChar(c as u128)),
O
Oliver Schneider 已提交
1304 1305
                }
            }
1306

S
Scott Olson 已提交
1307
            ty::TyInt(int_ty) => {
1308 1309 1310 1311 1312 1313
                use syntax::ast::IntTy::*;
                let size = match int_ty {
                    I8 => 1,
                    I16 => 2,
                    I32 => 4,
                    I64 => 8,
O
Oliver Schneider 已提交
1314
                    I128 => 16,
1315 1316
                    Is => self.memory.pointer_size(),
                };
O
Oliver Schneider 已提交
1317
                PrimVal::from_i128(self.memory.read_int(ptr, size)?)
1318
            }
1319

S
Scott Olson 已提交
1320
            ty::TyUint(uint_ty) => {
1321 1322 1323 1324 1325 1326
                use syntax::ast::UintTy::*;
                let size = match uint_ty {
                    U8 => 1,
                    U16 => 2,
                    U32 => 4,
                    U64 => 8,
O
Oliver Schneider 已提交
1327
                    U128 => 16,
1328 1329
                    Us => self.memory.pointer_size(),
                };
O
Oliver Schneider 已提交
1330
                PrimVal::from_u128(self.memory.read_uint(ptr, size)?)
1331
            }
1332

S
Scott Olson 已提交
1333 1334
            ty::TyFloat(FloatTy::F32) => PrimVal::from_f32(self.memory.read_f32(ptr)?),
            ty::TyFloat(FloatTy::F64) => PrimVal::from_f64(self.memory.read_f64(ptr)?),
1335

1336
            ty::TyFnPtr(_) => self.memory.read_ptr(ptr)?,
O
rustup  
Oliver Schneider 已提交
1337 1338
            ty::TyRef(_, ref tam) |
            ty::TyRawPtr(ref tam) => return self.read_ptr(ptr, tam.ty).map(Some),
1339

O
rustup  
Oliver Schneider 已提交
1340 1341 1342 1343
            ty::TyAdt(def, _) => {
                if def.is_box() {
                    return self.read_ptr(ptr, ty.boxed_ty()).map(Some);
                }
O
Oliver Schneider 已提交
1344
                use rustc::ty::layout::Layout::*;
1345
                if let CEnum { discr, signed, .. } = *self.type_layout(ty)? {
1346
                    let size = discr.size().bytes();
1347
                    if signed {
O
Oliver Schneider 已提交
1348
                        PrimVal::from_i128(self.memory.read_int(ptr, size)?)
1349
                    } else {
O
Oliver Schneider 已提交
1350
                        PrimVal::from_u128(self.memory.read_uint(ptr, size)?)
O
Oliver Schneider 已提交
1351 1352
                    }
                } else {
1353
                    return Ok(None);
O
Oliver Schneider 已提交
1354 1355 1356
                }
            },

1357
            _ => return Ok(None),
1358
        };
S
Scott Olson 已提交
1359

1360
        Ok(Some(Value::ByVal(val)))
1361 1362
    }

1363
    pub(super) fn frame(&self) -> &Frame<'tcx> {
1364 1365
        self.stack.last().expect("no call frames exist")
    }
1366

1367
    pub(super) fn frame_mut(&mut self) -> &mut Frame<'tcx> {
1368 1369
        self.stack.last_mut().expect("no call frames exist")
    }
1370

1371 1372
    pub(super) fn mir(&self) -> &'tcx mir::Mir<'tcx> {
        self.frame().mir
S
Scott Olson 已提交
1373
    }
O
Oliver Schneider 已提交
1374

1375
    pub(super) fn substs(&self) -> &'tcx Substs<'tcx> {
O
Oliver Schneider 已提交
1376
        self.frame().instance.substs
O
Oliver Schneider 已提交
1377
    }
1378

O
rustup  
Oliver Schneider 已提交
1379 1380 1381 1382 1383 1384 1385 1386
    fn unsize_into_ptr(
        &mut self,
        src: Value,
        src_ty: Ty<'tcx>,
        dest: Lvalue<'tcx>,
        dest_ty: Ty<'tcx>,
        sty: Ty<'tcx>,
        dty: Ty<'tcx>,
1387
    ) -> EvalResult<'tcx> {
O
rustup  
Oliver Schneider 已提交
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
        // A<Struct> -> A<Trait> conversion
        let (src_pointee_ty, dest_pointee_ty) = self.tcx.struct_lockstep_tails(sty, dty);

        match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
            (&ty::TyArray(_, length), &ty::TySlice(_)) => {
                let ptr = src.read_ptr(&self.memory)?;
                let len = PrimVal::from_u128(length as u128);
                self.write_value(Value::ByValPair(ptr, len), dest, dest_ty)
            }
            (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
                // For now, upcasts are limited to changes in marker
                // traits, and hence never actually require an actual
                // change to the vtable.
                self.write_value(src, dest, dest_ty)
            },
            (_, &ty::TyDynamic(ref data, _)) => {
                let trait_ref = data.principal().unwrap().with_self_ty(self.tcx, src_pointee_ty);
                let trait_ref = self.tcx.erase_regions(&trait_ref);
O
Oliver Schneider 已提交
1406
                let vtable = self.get_vtable(src_pointee_ty, trait_ref)?;
O
rustup  
Oliver Schneider 已提交
1407 1408 1409 1410 1411 1412 1413 1414 1415
                let ptr = src.read_ptr(&self.memory)?;
                let extra = PrimVal::Ptr(vtable);
                self.write_value(Value::ByValPair(ptr, extra), dest, dest_ty)
            },

            _ => bug!("invalid unsizing {:?} -> {:?}", src_ty, dest_ty),
        }
    }

1416 1417 1418 1419
    fn unsize_into(
        &mut self,
        src: Value,
        src_ty: Ty<'tcx>,
1420
        dest: Lvalue<'tcx>,
1421
        dest_ty: Ty<'tcx>,
1422
    ) -> EvalResult<'tcx> {
1423
        match (&src_ty.sty, &dest_ty.sty) {
O
rustup  
Oliver Schneider 已提交
1424 1425 1426 1427 1428 1429 1430
            (&ty::TyRef(_, ref s), &ty::TyRef(_, ref d)) |
            (&ty::TyRef(_, ref s), &ty::TyRawPtr(ref d)) |
            (&ty::TyRawPtr(ref s), &ty::TyRawPtr(ref d)) => self.unsize_into_ptr(src, src_ty, dest, dest_ty, s.ty, d.ty),
            (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
                if def_a.is_box() || def_b.is_box() {
                    if !def_a.is_box() || !def_b.is_box() {
                        panic!("invalid unsizing between {:?} -> {:?}", src_ty, dest_ty);
1431
                    }
O
rustup  
Oliver Schneider 已提交
1432
                    return self.unsize_into_ptr(src, src_ty, dest, dest_ty, src_ty.boxed_ty(), dest_ty.boxed_ty());
1433
                }
1434 1435 1436 1437 1438
                if self.ty_to_primval_kind(src_ty).is_ok() {
                    let sty = self.get_field_ty(src_ty, 0)?;
                    let dty = self.get_field_ty(dest_ty, 0)?;
                    return self.unsize_into(src, sty, dest, dty);
                }
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
                // unsizing of generic struct with pointer fields
                // Example: `Arc<T>` -> `Arc<Trait>`
                // here we need to increase the size of every &T thin ptr field to a fat ptr

                assert_eq!(def_a, def_b);

                let src_fields = def_a.variants[0].fields.iter();
                let dst_fields = def_b.variants[0].fields.iter();

                //let src = adt::MaybeSizedValue::sized(src);
                //let dst = adt::MaybeSizedValue::sized(dst);
                let src_ptr = match src {
                    Value::ByRef(ptr) => ptr,
O
Oliver Schneider 已提交
1452
                    _ => bug!("expected pointer, got {:?}", src),
1453 1454
                };

1455
                // FIXME(solson)
1456
                let dest = self.force_allocation(dest)?.to_ptr()?;
1457 1458
                let iter = src_fields.zip(dst_fields).enumerate();
                for (i, (src_f, dst_f)) in iter {
1459 1460
                    let src_fty = monomorphize_field_ty(self.tcx, src_f, substs_a);
                    let dst_fty = monomorphize_field_ty(self.tcx, dst_f, substs_b);
1461
                    if self.type_size(dst_fty)? == Some(0) {
1462 1463
                        continue;
                    }
1464 1465
                    let src_field_offset = self.get_field_offset(src_ty, i)?.bytes();
                    let dst_field_offset = self.get_field_offset(dest_ty, i)?.bytes();
1466 1467
                    let src_f_ptr = src_ptr.offset(src_field_offset, self.memory.layout)?;
                    let dst_f_ptr = dest.offset(dst_field_offset, self.memory.layout)?;
1468
                    if src_fty == dst_fty {
1469
                        self.copy(PrimVal::Ptr(src_f_ptr), PrimVal::Ptr(dst_f_ptr), src_fty)?;
1470
                    } else {
1471
                        self.unsize_into(Value::ByRef(src_f_ptr), src_fty, Lvalue::from_ptr(dst_f_ptr), dst_fty)?;
1472 1473
                    }
                }
O
rustup  
Oliver Schneider 已提交
1474
                Ok(())
1475
            }
1476
            _ => bug!("unsize_into: invalid conversion: {:?} -> {:?}", src_ty, dest_ty),
1477 1478
        }
    }
S
Scott Olson 已提交
1479

1480
    pub(super) fn dump_local(&self, lvalue: Lvalue<'tcx>) {
R
Ralf Jung 已提交
1481
        // Debug output
1482
        if let Lvalue::Local { frame, local, field } = lvalue {
S
Scott Olson 已提交
1483 1484
            let mut allocs = Vec::new();
            let mut msg = format!("{:?}", local);
O
Oliver Schneider 已提交
1485
            if let Some((field, _)) = field {
1486 1487
                write!(msg, ".{}", field).unwrap();
            }
S
Scott Olson 已提交
1488 1489 1490 1491 1492 1493
            let last_frame = self.stack.len() - 1;
            if frame != last_frame {
                write!(msg, " ({} frames up)", last_frame - frame).unwrap();
            }
            write!(msg, ":").unwrap();

1494
            match self.stack[frame].get_local(local, field.map(|(i, _)| i)) {
1495 1496 1497 1498 1499 1500 1501
                Err(EvalError::DeadLocal) => {
                    write!(msg, " is dead").unwrap();
                }
                Err(err) => {
                    panic!("Failed to access local: {:?}", err);
                }
                Ok(Value::ByRef(ptr)) => {
R
Ralf Jung 已提交
1502
                    write!(msg, " by ref:").unwrap();
1503 1504
                    allocs.push(ptr.alloc_id);
                }
1505
                Ok(Value::ByVal(val)) => {
S
Scott Olson 已提交
1506
                    write!(msg, " {:?}", val).unwrap();
1507 1508
                    if let PrimVal::Ptr(ptr) = val { allocs.push(ptr.alloc_id); }
                }
1509
                Ok(Value::ByValPair(val1, val2)) => {
S
Scott Olson 已提交
1510
                    write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
1511 1512
                    if let PrimVal::Ptr(ptr) = val1 { allocs.push(ptr.alloc_id); }
                    if let PrimVal::Ptr(ptr) = val2 { allocs.push(ptr.alloc_id); }
1513 1514
                }
            }
1515

S
Scott Olson 已提交
1516 1517 1518
            trace!("{}", msg);
            self.memory.dump_allocs(allocs);
        }
1519
    }
1520

1521
    /// Convenience function to ensure correct usage of globals and code-sharing with locals.
1522
    pub fn modify_global<F>(&mut self, cid: GlobalId<'tcx>, f: F) -> EvalResult<'tcx>
1523 1524
        where F: FnOnce(&mut Self, Value) -> EvalResult<'tcx, Value>,
    {
1525 1526 1527 1528
        let mut val = *self.globals.get(&cid).expect("global not cached");
        if !val.mutable {
            return Err(EvalError::ModifiedConstantMemory);
        }
1529
        val.value = f(self, val.value)?;
1530 1531 1532 1533
        *self.globals.get_mut(&cid).expect("already checked") = val;
        Ok(())
    }

1534 1535
    /// Convenience function to ensure correct usage of locals and code-sharing with globals.
    pub fn modify_local<F>(
1536 1537 1538
        &mut self,
        frame: usize,
        local: mir::Local,
1539
        field: Option<usize>,
1540
        f: F,
1541
    ) -> EvalResult<'tcx>
1542 1543
        where F: FnOnce(&mut Self, Value) -> EvalResult<'tcx, Value>,
    {
1544
        let val = self.stack[frame].get_local(local, field)?;
1545
        let new_val = f(self, val)?;
1546
        self.stack[frame].set_local(local, field, new_val)?;
1547 1548 1549 1550
        // FIXME(solson): Run this when setting to Undef? (See previous version of this code.)
        // if let Value::ByRef(ptr) = self.stack[frame].get_local(local) {
        //     self.memory.deallocate(ptr)?;
        // }
1551 1552
        Ok(())
    }
1553 1554
}

1555
impl<'tcx> Frame<'tcx> {
1556
    pub fn get_local(&self, local: mir::Local, field: Option<usize>) -> EvalResult<'tcx, Value> {
1557
        // Subtract 1 because we don't store a value for the ReturnPointer, the local with index 0.
1558
        if let Some(field) = field {
1559 1560 1561 1562
            Ok(match self.locals[local.index() - 1] {
                None => return Err(EvalError::DeadLocal),
                Some(Value::ByRef(_)) => bug!("can't have lvalue fields for ByRef"),
                Some(val @ Value::ByVal(_)) => {
1563 1564 1565
                    assert_eq!(field, 0);
                    val
                },
1566
                Some(Value::ByValPair(a, b)) => {
1567 1568 1569 1570 1571 1572
                    match field {
                        0 => Value::ByVal(a),
                        1 => Value::ByVal(b),
                        _ => bug!("ByValPair has only two fields, tried to access {}", field),
                    }
                },
1573
            })
1574
        } else {
1575
            self.locals[local.index() - 1].ok_or(EvalError::DeadLocal)
1576
        }
1577 1578
    }

1579
    fn set_local(&mut self, local: mir::Local, field: Option<usize>, value: Value) -> EvalResult<'tcx> {
1580
        // Subtract 1 because we don't store a value for the ReturnPointer, the local with index 0.
1581 1582
        if let Some(field) = field {
            match self.locals[local.index() - 1] {
1583 1584 1585
                None => return Err(EvalError::DeadLocal),
                Some(Value::ByRef(_)) => bug!("can't have lvalue fields for ByRef"),
                Some(Value::ByVal(_)) => {
1586
                    assert_eq!(field, 0);
1587
                    self.set_local(local, None, value)?;
1588
                },
1589
                Some(Value::ByValPair(a, b)) => {
1590 1591 1592 1593 1594 1595
                    let prim = match value {
                        Value::ByRef(_) => bug!("can't set ValPair field to ByRef"),
                        Value::ByVal(val) => val,
                        Value::ByValPair(_, _) => bug!("can't set ValPair field to ValPair"),
                    };
                    match field {
1596 1597
                        0 => self.set_local(local, None, Value::ByValPair(prim, b))?,
                        1 => self.set_local(local, None, Value::ByValPair(a, prim))?,
1598 1599 1600 1601 1602
                        _ => bug!("ByValPair has only two fields, tried to access {}", field),
                    }
                },
            }
        } else {
1603 1604 1605 1606
            match self.locals[local.index() - 1] {
                None => return Err(EvalError::DeadLocal),
                Some(ref mut local) => { *local = value; }
            }
1607
        }
1608 1609 1610
        return Ok(());
    }

1611
    pub fn storage_live(&mut self, local: mir::Local) -> EvalResult<'tcx, Option<Value>> {
1612
        trace!("{:?} is now live", local);
1613 1614 1615 1616

        let old = self.locals[local.index() - 1];
        self.locals[local.index() - 1] = Some(Value::ByVal(PrimVal::Undef)); // StorageLive *always* kills the value that's currently stored
        return Ok(old);
1617 1618 1619 1620 1621 1622 1623 1624 1625
    }

    /// Returns the old value of the local
    pub fn storage_dead(&mut self, local: mir::Local) -> EvalResult<'tcx, Option<Value>> {
        trace!("{:?} is now dead", local);

        let old = self.locals[local.index() - 1];
        self.locals[local.index() - 1] = None;
        return Ok(old);
1626 1627 1628
    }
}

1629 1630
pub fn eval_main<'a, 'tcx: 'a>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
1631 1632
    main_id: DefId,
    start_wrapper: Option<DefId>,
S
Scott Olson 已提交
1633
    limits: ResourceLimits,
1634
) {
1635 1636 1637 1638 1639 1640 1641
    fn run_main<'a, 'tcx: 'a>(
        ecx: &mut EvalContext<'a, 'tcx>,
        main_id: DefId,
        start_wrapper: Option<DefId>,
    ) -> EvalResult<'tcx> {
        let main_instance = ty::Instance::mono(ecx.tcx, main_id);
        let main_mir = ecx.load_mir(main_instance.def)?;
1642
        let mut cleanup_ptr = None; // Pointer to be deallocated when we are done
1643

1644 1645 1646
        if !main_mir.return_ty.is_nil() || main_mir.arg_count != 0 {
            return Err(EvalError::Unimplemented("miri does not support main functions without `fn()` type signatures".to_owned()));
        }
S
Scott Olson 已提交
1647

1648 1649 1650 1651 1652 1653 1654 1655
        if let Some(start_id) = start_wrapper {
            let start_instance = ty::Instance::mono(ecx.tcx, start_id);
            let start_mir = ecx.load_mir(start_instance.def)?;

            if start_mir.arg_count != 3 {
                return Err(EvalError::AbiViolation(format!("'start' lang item should have three arguments, but has {}", start_mir.arg_count)));
            }

1656
            // Return value
1657
            let ret_ptr = ecx.memory.allocate(ecx.tcx.data_layout.pointer_size.bytes(), ecx.tcx.data_layout.pointer_align.abi())?;
1658 1659
            cleanup_ptr = Some(ret_ptr);

1660 1661 1662 1663 1664
            // Push our stack frame
            ecx.push_stack_frame(
                start_instance,
                start_mir.span,
                start_mir,
1665 1666
                Lvalue::from_ptr(ret_ptr),
                StackPopCleanup::Tls(None),
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
            )?;

            let mut args = ecx.frame().mir.args_iter();

            // First argument: pointer to main()
            let main_ptr = ecx.memory.create_fn_alloc(main_instance);
            let dest = ecx.eval_lvalue(&mir::Lvalue::Local(args.next().unwrap()))?;
            let main_ty = main_instance.def.def_ty(ecx.tcx);
            let main_ptr_ty = ecx.tcx.mk_fn_ptr(main_ty.fn_sig());
            ecx.write_value(Value::ByVal(PrimVal::Ptr(main_ptr)), dest, main_ptr_ty)?;

            // Second argument (argc): 0
            let dest = ecx.eval_lvalue(&mir::Lvalue::Local(args.next().unwrap()))?;
            let ty = ecx.tcx.types.isize;
            ecx.write_value(Value::ByVal(PrimVal::Bytes(0)), dest, ty)?;

            // Third argument (argv): 0
            let dest = ecx.eval_lvalue(&mir::Lvalue::Local(args.next().unwrap()))?;
            let ty = ecx.tcx.mk_imm_ptr(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8));
            ecx.write_value(Value::ByVal(PrimVal::Bytes(0)), dest, ty)?;
        } else {
            ecx.push_stack_frame(
                main_instance,
                main_mir.span,
                main_mir,
1692 1693
                Lvalue::zst(),
                StackPopCleanup::Tls(None),
1694 1695 1696
            )?;
        }

R
Ralf Jung 已提交
1697
        while ecx.step()? {}
1698 1699 1700
        if let Some(cleanup_ptr) = cleanup_ptr {
            ecx.memory.deallocate(cleanup_ptr)?;
        }
R
Ralf Jung 已提交
1701
        return Ok(());
1702 1703 1704 1705 1706 1707 1708 1709
    }

    let mut ecx = EvalContext::new(tcx, limits);
    match run_main(&mut ecx, main_id, start_wrapper) {
        Ok(()) => {
            let leaks = ecx.memory.leak_report();
            if leaks != 0 {
                tcx.sess.err("the evaluated program leaked memory");
1710 1711
            }
        }
1712
        Err(e) => {
O
Oliver Schneider 已提交
1713
            report(tcx, &ecx, &e);
1714
        }
1715 1716 1717
    }
}

O
Oliver Schneider 已提交
1718
fn report(tcx: TyCtxt, ecx: &EvalContext, e: &EvalError) {
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
    if let Some(frame) = ecx.stack().last() {
        let block = &frame.mir.basic_blocks()[frame.block];
        let span = if frame.stmt < block.statements.len() {
            block.statements[frame.stmt].source_info.span
        } else {
            block.terminator().source_info.span
        };
        let mut err = tcx.sess.struct_span_err(span, &e.to_string());
        for &Frame { instance, span, .. } in ecx.stack().iter().rev() {
            if tcx.def_key(instance.def_id()).disambiguated_data.data == DefPathData::ClosureExpr {
                err.span_note(span, "inside call to closure");
                continue;
            }
            err.span_note(span, &format!("inside call to {}", instance));
1733
        }
1734 1735 1736
        err.emit();
    } else {
        tcx.sess.err(&e.to_string());
1737 1738
    }
}
1739 1740 1741

// TODO(solson): Upstream these methods into rustc::ty::layout.

1742
pub(super) trait IntegerExt {
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
    fn size(self) -> Size;
}

impl IntegerExt for layout::Integer {
    fn size(self) -> Size {
        use rustc::ty::layout::Integer::*;
        match self {
            I1 | I8 => Size::from_bits(8),
            I16 => Size::from_bits(16),
            I32 => Size::from_bits(32),
            I64 => Size::from_bits(64),
O
Oliver Schneider 已提交
1754
            I128 => Size::from_bits(128),
1755 1756 1757
        }
    }
}
1758 1759


O
rustup  
Oliver Schneider 已提交
1760
pub fn monomorphize_field_ty<'a, 'tcx:'a >(tcx: TyCtxt<'a, 'tcx, 'tcx>, f: &ty::FieldDef, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
S
Scott Olson 已提交
1761
    let substituted = f.ty(tcx, substs);
1762 1763
    tcx.normalize_associated_type(&substituted)
}
1764 1765

pub fn is_inhabited<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
O
rustup  
Oliver Schneider 已提交
1766
    ty.uninhabited_from(&mut HashMap::default(), tcx).is_empty()
1767
}
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785

pub trait IntoValTyPair<'tcx> {
    fn into_val_ty_pair<'a>(self, ecx: &mut EvalContext<'a, 'tcx>) -> EvalResult<'tcx, (Value, Ty<'tcx>)> where 'tcx: 'a;
}

impl<'tcx> IntoValTyPair<'tcx> for (Value, Ty<'tcx>) {
    fn into_val_ty_pair<'a>(self, _: &mut EvalContext<'a, 'tcx>) -> EvalResult<'tcx, (Value, Ty<'tcx>)> where 'tcx: 'a {
        Ok(self)
    }
}

impl<'b, 'tcx: 'b> IntoValTyPair<'tcx> for &'b mir::Operand<'tcx> {
    fn into_val_ty_pair<'a>(self, ecx: &mut EvalContext<'a, 'tcx>) -> EvalResult<'tcx, (Value, Ty<'tcx>)> where 'tcx: 'a {
        let value = ecx.eval_operand(self)?;
        let value_ty = ecx.operand_ty(self);
        Ok((value, value_ty))
    }
}
O
Oliver Schneider 已提交
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862


/// FIXME: expose trans::monomorphize::resolve_closure
pub fn resolve_closure<'a, 'tcx> (
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    def_id: DefId,
    substs: ty::ClosureSubsts<'tcx>,
    requested_kind: ty::ClosureKind,
) -> ty::Instance<'tcx> {
    let actual_kind = tcx.closure_kind(def_id);
    match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
        Ok(true) => fn_once_adapter_instance(tcx, def_id, substs),
        _ => ty::Instance::new(def_id, substs.substs)
    }
}

fn fn_once_adapter_instance<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    closure_did: DefId,
    substs: ty::ClosureSubsts<'tcx>,
) -> ty::Instance<'tcx> {
    debug!("fn_once_adapter_shim({:?}, {:?})",
           closure_did,
           substs);
    let fn_once = tcx.lang_items.fn_once_trait().unwrap();
    let call_once = tcx.associated_items(fn_once)
        .find(|it| it.kind == ty::AssociatedKind::Method)
        .unwrap().def_id;
    let def = ty::InstanceDef::ClosureOnceShim { call_once };

    let self_ty = tcx.mk_closure_from_closure_substs(
        closure_did, substs);

    let sig = tcx.closure_type(closure_did).subst(tcx, substs.substs);
    let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
    assert_eq!(sig.inputs().len(), 1);
    let substs = tcx.mk_substs([
        Kind::from(self_ty),
        Kind::from(sig.inputs()[0]),
    ].iter().cloned());

    debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
    ty::Instance { def, substs }
}

fn needs_fn_once_adapter_shim(actual_closure_kind: ty::ClosureKind,
                              trait_closure_kind: ty::ClosureKind)
                              -> Result<bool, ()>
{
    match (actual_closure_kind, trait_closure_kind) {
        (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
        (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
        (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
            // No adapter needed.
           Ok(false)
        }
        (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
            // The closure fn `llfn` is a `fn(&self, ...)`.  We want a
            // `fn(&mut self, ...)`. In fact, at trans time, these are
            // basically the same thing, so we can just return llfn.
            Ok(false)
        }
        (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
        (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
            // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
            // self, ...)`.  We want a `fn(self, ...)`. We can produce
            // this by doing something like:
            //
            //     fn call_once(self, ...) { call_mut(&self, ...) }
            //     fn call_once(mut self, ...) { call_mut(&mut self, ...) }
            //
            // These are both the same at trans time.
            Ok(true)
        }
        _ => Err(()),
    }
}
O
Oliver Schneider 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923

/// The point where linking happens. Resolve a (def_id, substs)
/// pair to an instance.
pub fn resolve<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    def_id: DefId,
    substs: &'tcx Substs<'tcx>
) -> ty::Instance<'tcx> {
    debug!("resolve(def_id={:?}, substs={:?})",
           def_id, substs);
    let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
        debug!(" => associated item, attempting to find impl");
        let item = tcx.associated_item(def_id);
        resolve_associated_item(tcx, &item, trait_def_id, substs)
    } else {
        let item_type = def_ty(tcx, def_id, substs);
        let def = match item_type.sty {
            ty::TyFnDef(_, _, f) if
                f.abi() == Abi::RustIntrinsic ||
                f.abi() == Abi::PlatformIntrinsic =>
            {
                debug!(" => intrinsic");
                ty::InstanceDef::Intrinsic(def_id)
            }
            _ => {
                if Some(def_id) == tcx.lang_items.drop_in_place_fn() {
                    let ty = substs.type_at(0);
                    if needs_drop_glue(tcx, ty) {
                        debug!(" => nontrivial drop glue");
                        ty::InstanceDef::DropGlue(def_id, Some(ty))
                    } else {
                        debug!(" => trivial drop glue");
                        ty::InstanceDef::DropGlue(def_id, None)
                    }
                } else {
                    debug!(" => free item");
                    ty::InstanceDef::Item(def_id)
                }
            }
        };
        ty::Instance { def, substs }
    };
    debug!("resolve(def_id={:?}, substs={:?}) = {}",
           def_id, substs, result);
    result
}

pub fn needs_drop_glue<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, t: Ty<'tcx>) -> bool {
    assert!(t.is_normalized_for_trans());

    let t = tcx.erase_regions(&t);

    // FIXME (#22815): note that type_needs_drop conservatively
    // approximates in some cases and may say a type expression
    // requires drop glue when it actually does not.
    //
    // (In this case it is not clear whether any harm is done, i.e.
    // erroneously returning `true` in some cases where we could have
    // returned `false` does not appear unsound. The impact on
    // code quality is unknown at this time.)

1924
    let env = ty::ParamEnv::empty(Reveal::All);
1925
    if !t.needs_drop(tcx, env) {
O
Oliver Schneider 已提交
1926 1927 1928 1929 1930
        return false;
    }
    match t.sty {
        ty::TyAdt(def, _) if def.is_box() => {
            let typ = t.boxed_ty();
1931
            if !typ.needs_drop(tcx, env) && type_is_sized(tcx, typ) {
1932 1933 1934
                let layout = t.layout(tcx, ty::ParamEnv::empty(Reveal::All)).unwrap();
                // `Box<ZeroSizeType>` does not allocate.
                layout.size(&tcx.data_layout).bytes() != 0
O
Oliver Schneider 已提交
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
            } else {
                true
            }
        }
        _ => true
    }
}

fn resolve_associated_item<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    trait_item: &ty::AssociatedItem,
    trait_id: DefId,
    rcvr_substs: &'tcx Substs<'tcx>
) -> ty::Instance<'tcx> {
    let def_id = trait_item.def_id;
    debug!("resolve_associated_item(trait_item={:?}, \
                                    trait_id={:?}, \
                                    rcvr_substs={:?})",
           def_id, trait_id, rcvr_substs);

    let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
    let vtbl = fulfill_obligation(tcx, DUMMY_SP, ty::Binder(trait_ref));

    // Now that we know which impl is being used, we can dispatch to
    // the actual function:
    match vtbl {
        ::rustc::traits::VtableImpl(impl_data) => {
            let (def_id, substs) = ::rustc::traits::find_associated_item(
                tcx, trait_item, rcvr_substs, &impl_data);
            let substs = tcx.erase_regions(&substs);
            ty::Instance::new(def_id, substs)
        }
        ::rustc::traits::VtableClosure(closure_data) => {
            let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_id).unwrap();
            resolve_closure(tcx, closure_data.closure_def_id, closure_data.substs,
                            trait_closure_kind)
        }
        ::rustc::traits::VtableFnPointer(ref data) => {
            ty::Instance {
                def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
                substs: rcvr_substs
            }
        }
        ::rustc::traits::VtableObject(ref data) => {
            let index = tcx.get_vtable_index_of_object_method(data, def_id);
            ty::Instance {
                def: ty::InstanceDef::Virtual(def_id, index),
                substs: rcvr_substs
            }
        }
        _ => {
            bug!("static call to invalid vtable: {:?}", vtbl)
        }
    }
}

pub fn def_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                        def_id: DefId,
                        substs: &'tcx Substs<'tcx>)
                        -> Ty<'tcx>
{
1996
    let ty = tcx.type_of(def_id);
O
Oliver Schneider 已提交
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
    apply_param_substs(tcx, substs, &ty)
}

/// Monomorphizes a type from the AST by first applying the in-scope
/// substitutions and then normalizing any associated types.
pub fn apply_param_substs<'a, 'tcx, T>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                       param_substs: &Substs<'tcx>,
                                       value: &T)
                                       -> T
    where T: ::rustc::infer::TransNormalize<'tcx>
{
    debug!("apply_param_substs(param_substs={:?}, value={:?})", param_substs, value);
    let substituted = value.subst(tcx, param_substs);
    let substituted = tcx.erase_regions(&substituted);
    AssociatedTypeNormalizer{ tcx }.fold(&substituted)
}


struct AssociatedTypeNormalizer<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
}

impl<'a, 'tcx> AssociatedTypeNormalizer<'a, 'tcx> {
    fn fold<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
        if !value.has_projection_types() {
            value.clone()
        } else {
            value.fold_with(self)
        }
    }
}

impl<'a, 'tcx> ::rustc::ty::fold::TypeFolder<'tcx, 'tcx> for AssociatedTypeNormalizer<'a, 'tcx> {
    fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
        self.tcx
    }

    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
        if !ty.has_projection_types() {
            ty
        } else {
            self.tcx.normalize_associated_type(&ty)
        }
    }
}

fn type_is_sized<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> bool {
    // generics are weird, don't run this function on a generic
    assert!(!ty.needs_subst());
2046
    ty.is_sized(tcx, ty::ParamEnv::empty(Reveal::All), DUMMY_SP)
O
Oliver Schneider 已提交
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
}

/// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we
/// do not (necessarily) resolve all nested obligations on the impl. Note that type check should
/// guarantee to us that all nested obligations *could be* resolved if we wanted to.
fn fulfill_obligation<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                span: Span,
                                trait_ref: ty::PolyTraitRef<'tcx>)
                                -> traits::Vtable<'tcx, ()>
{
    // Remove any references to regions; this helps improve caching.
    let trait_ref = tcx.erase_regions(&trait_ref);

    debug!("trans::fulfill_obligation(trait_ref={:?}, def_id={:?})",
            trait_ref, trait_ref.def_id());

    // Do the initial selection for the obligation. This yields the
    // shallow result we are looking for -- that is, what specific impl.
2065
    tcx.infer_ctxt().enter(|infcx| {
O
Oliver Schneider 已提交
2066 2067 2068 2069 2070
        let mut selcx = traits::SelectionContext::new(&infcx);

        let obligation_cause = traits::ObligationCause::misc(span,
                                                            ast::DUMMY_NODE_ID);
        let obligation = traits::Obligation::new(obligation_cause,
2071 2072
                                                 ty::ParamEnv::empty(Reveal::All),
                                                 trait_ref.to_poly_trait_predicate());
O
Oliver Schneider 已提交
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107

        let selection = match selcx.select(&obligation) {
            Ok(Some(selection)) => selection,
            Ok(None) => {
                // Ambiguity can happen when monomorphizing during trans
                // expands to some humongo type that never occurred
                // statically -- this humongo type can then overflow,
                // leading to an ambiguous result. So report this as an
                // overflow bug, since I believe this is the only case
                // where ambiguity can result.
                debug!("Encountered ambiguity selecting `{:?}` during trans, \
                        presuming due to overflow",
                        trait_ref);
                tcx.sess.span_fatal(span,
                    "reached the recursion limit during monomorphization \
                        (selection ambiguity)");
            }
            Err(e) => {
                span_bug!(span, "Encountered error `{:?}` selecting `{:?}` during trans",
                            e, trait_ref)
            }
        };

        debug!("fulfill_obligation: selection={:?}", selection);

        // Currently, we use a fulfillment context to completely resolve
        // all nested obligations. This is because they can inform the
        // inference of the impl's type parameters.
        let mut fulfill_cx = traits::FulfillmentContext::new();
        let vtable = selection.map(|predicate| {
            debug!("fulfill_obligation: register_predicate_obligation {:?}", predicate);
            fulfill_cx.register_predicate_obligation(&infcx, predicate);
        });
        let vtable = infcx.drain_fulfillment_cx_or_panic(span, &mut fulfill_cx, &vtable);

O
Oliver Schneider 已提交
2108
        debug!("Cache miss: {:?} => {:?}", trait_ref, vtable);
O
Oliver Schneider 已提交
2109 2110 2111
        vtable
    })
}
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121

pub fn resolve_drop_in_place<'a, 'tcx>(
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    ty: Ty<'tcx>,
) -> ty::Instance<'tcx>
{
    let def_id = tcx.require_lang_item(::rustc::middle::lang_items::DropInPlaceFnLangItem);
    let substs = tcx.intern_substs(&[Kind::from(ty)]);
    resolve(tcx, def_id, substs)
}