]> git.lizzy.rs Git - rust.git/blob - src/interpreter/mod.rs
move constants stack to stackframe
[rust.git] / src / interpreter / mod.rs
1 use rustc::middle::const_val;
2 use rustc::hir::def_id::DefId;
3 use rustc::mir::mir_map::MirMap;
4 use rustc::mir::repr as mir;
5 use rustc::traits::{self, ProjectionMode};
6 use rustc::ty::fold::TypeFoldable;
7 use rustc::ty::layout::{self, Layout, Size};
8 use rustc::ty::subst::{self, Subst, Substs};
9 use rustc::ty::{self, Ty, TyCtxt};
10 use rustc::util::nodemap::DefIdMap;
11 use std::cell::RefCell;
12 use std::ops::{Deref, DerefMut};
13 use std::rc::Rc;
14 use std::{iter, mem};
15 use syntax::ast;
16 use syntax::attr;
17 use syntax::codemap::{self, DUMMY_SP, Span};
18
19 use error::{EvalError, EvalResult};
20 use memory::{Memory, Pointer};
21 use primval::{self, PrimVal};
22
23 use std::collections::HashMap;
24
25 mod stepper;
26
27 struct GlobalEvalContext<'a, 'tcx: 'a> {
28     /// The results of the type checker, from rustc.
29     tcx: TyCtxt<'a, 'tcx, 'tcx>,
30
31     /// A mapping from NodeIds to Mir, from rustc. Only contains MIR for crate-local items.
32     mir_map: &'a MirMap<'tcx>,
33
34     /// A local cache from DefIds to Mir for non-crate-local items.
35     mir_cache: RefCell<DefIdMap<Rc<mir::Mir<'tcx>>>>,
36
37     /// The virtual memory system.
38     memory: Memory,
39
40     /// Precomputed statics and constants
41     statics: DefIdMap<Pointer>,
42 }
43
44 struct FnEvalContext<'a, 'b: 'a + 'mir, 'mir, 'tcx: 'b> {
45     gecx: &'a mut GlobalEvalContext<'b, 'tcx>,
46
47     /// The virtual call stack.
48     stack: Vec<Frame<'mir, 'tcx>>,
49 }
50
51 impl<'a, 'b, 'mir, 'tcx> Deref for FnEvalContext<'a, 'b, 'mir, 'tcx> {
52     type Target = GlobalEvalContext<'b, 'tcx>;
53     fn deref(&self) -> &Self::Target {
54         self.gecx
55     }
56 }
57
58 impl<'a, 'b, 'mir, 'tcx> DerefMut for FnEvalContext<'a, 'b, 'mir, 'tcx> {
59     fn deref_mut(&mut self) -> &mut Self::Target {
60         self.gecx
61     }
62 }
63
64 /// A stack frame.
65 struct Frame<'a, 'tcx: 'a> {
66     /// The def_id of the current function
67     def_id: DefId,
68
69     /// The span of the call site
70     span: codemap::Span,
71
72     /// type substitutions for the current function invocation
73     substs: &'tcx Substs<'tcx>,
74
75     /// The MIR for the function called on this frame.
76     mir: CachedMir<'a, 'tcx>,
77
78     /// The block that is currently executed (or will be executed after the above call stacks return)
79     next_block: mir::BasicBlock,
80
81     /// A pointer for writing the return value of the current call if it's not a diverging call.
82     return_ptr: Option<Pointer>,
83
84     /// The list of locals for the current function, stored in order as
85     /// `[arguments..., variables..., temporaries...]`. The variables begin at `self.var_offset`
86     /// and the temporaries at `self.temp_offset`.
87     locals: Vec<Pointer>,
88
89     /// The offset of the first variable in `self.locals`.
90     var_offset: usize,
91
92     /// The offset of the first temporary in `self.locals`.
93     temp_offset: usize,
94
95     /// List of precomputed promoted constants
96     promoted: HashMap<usize, Pointer>,
97
98     /// The index of the currently evaluated statment
99     stmt: usize,
100
101     // Constants that need to be evaluated before the next statement can be evaluated
102     constants: Vec<(ConstantId<'tcx>, Span, Pointer, CachedMir<'a, 'tcx>)>,
103 }
104
105 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
106 struct Lvalue {
107     ptr: Pointer,
108     extra: LvalueExtra,
109 }
110
111 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
112 enum LvalueExtra {
113     None,
114     Length(u64),
115     // TODO(solson): Vtable(memory::AllocId),
116     DowncastVariant(usize),
117 }
118
119 #[derive(Clone)]
120 enum CachedMir<'mir, 'tcx: 'mir> {
121     Ref(&'mir mir::Mir<'tcx>),
122     Owned(Rc<mir::Mir<'tcx>>)
123 }
124
125 /// Represents the action to be taken in the main loop as a result of executing a terminator.
126 enum TerminatorTarget {
127     /// Make a local jump to the next block
128     Block,
129
130     /// Start executing from the new current frame. (For function calls.)
131     Call,
132
133     /// Stop executing the current frame and resume the previous frame.
134     Return,
135 }
136
137 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
138 enum ConstantId<'tcx> {
139     Promoted { index: usize },
140     Static { def_id: DefId, substs: &'tcx Substs<'tcx> },
141 }
142
143
144 impl<'a, 'tcx> GlobalEvalContext<'a, 'tcx> {
145     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, mir_map: &'a MirMap<'tcx>) -> Self {
146         GlobalEvalContext {
147             tcx: tcx,
148             mir_map: mir_map,
149             mir_cache: RefCell::new(DefIdMap()),
150             memory: Memory::new(tcx.sess
151                                    .target
152                                    .uint_type
153                                    .bit_width()
154                                    .expect("Session::target::uint_type was usize")/8),
155             statics: DefIdMap(),
156         }
157     }
158
159     fn call(&mut self, mir: &mir::Mir<'tcx>, def_id: DefId) -> EvalResult<Option<Pointer>> {
160         let substs = self.tcx.mk_substs(subst::Substs::empty());
161
162         let mut nested_fecx = FnEvalContext::new(self);
163
164         nested_fecx.push_stack_frame(def_id, mir.span, CachedMir::Ref(mir), substs, None);
165         let return_ptr = nested_fecx.alloc_ret_ptr(mir.return_ty);
166         nested_fecx.frame_mut().return_ptr = return_ptr;
167
168         nested_fecx.run()?;
169         Ok(return_ptr)
170     }
171 }
172
173 impl<'a, 'b, 'mir, 'tcx> FnEvalContext<'a, 'b, 'mir, 'tcx> {
174     fn new(gecx: &'a mut GlobalEvalContext<'b, 'tcx>) -> Self {
175         FnEvalContext {
176             gecx: gecx,
177             stack: Vec::new(),
178         }
179     }
180
181     fn alloc_ret_ptr(&mut self, ty: ty::FnOutput<'tcx>) -> Option<Pointer> {
182         match ty {
183             ty::FnConverging(ty) => {
184                 let size = self.type_size(ty);
185                 Some(self.memory.allocate(size))
186             }
187             ty::FnDiverging => None,
188         }
189     }
190
191     fn maybe_report<T>(&self, span: codemap::Span, r: EvalResult<T>) -> EvalResult<T> {
192         if let Err(ref e) = r {
193             let mut err = self.tcx.sess.struct_span_err(span, &e.to_string());
194             for &Frame{ def_id, substs, span, .. } in self.stack.iter().rev() {
195                 // FIXME(solson): Find a way to do this without this Display impl hack.
196                 use rustc::util::ppaux;
197                 use std::fmt;
198                 struct Instance<'tcx>(DefId, &'tcx Substs<'tcx>);
199                 impl<'tcx> fmt::Display for Instance<'tcx> {
200                     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
201                         ppaux::parameterized(f, self.1, self.0, ppaux::Ns::Value, &[],
202                             |tcx| tcx.lookup_item_type(self.0).generics)
203                     }
204                 }
205                 err.span_note(span, &format!("inside call to {}", Instance(def_id, substs)));
206             }
207             err.emit();
208         }
209         r
210     }
211
212     fn run(&mut self) -> EvalResult<()> {
213         let mut stepper = stepper::Stepper::new(self);
214         'outer: loop {
215             use self::stepper::Event::*;
216             trace!("// {:?}", stepper.block());
217
218             loop {
219                 match stepper.step()? {
220                     Constant => trace!("next statement requires the computation of a constant"),
221                     Assignment => trace!("{:?}", stepper.stmt()),
222                     Terminator => {
223                         trace!("{:?}", stepper.term().kind);
224                         continue 'outer;
225                     },
226                     Done => return Ok(()),
227                 }
228             }
229         }
230     }
231
232     fn push_stack_frame(&mut self, def_id: DefId, span: codemap::Span, mir: CachedMir<'mir, 'tcx>, substs: &'tcx Substs<'tcx>,
233         return_ptr: Option<Pointer>)
234     {
235         let arg_tys = mir.arg_decls.iter().map(|a| a.ty);
236         let var_tys = mir.var_decls.iter().map(|v| v.ty);
237         let temp_tys = mir.temp_decls.iter().map(|t| t.ty);
238
239         let num_args = mir.arg_decls.len();
240         let num_vars = mir.var_decls.len();
241
242         ::log_settings::settings().indentation += 1;
243
244         self.stack.push(Frame {
245             mir: mir.clone(),
246             next_block: mir::START_BLOCK,
247             return_ptr: return_ptr,
248             locals: Vec::new(),
249             var_offset: num_args,
250             temp_offset: num_args + num_vars,
251             promoted: HashMap::new(),
252             span: span,
253             def_id: def_id,
254             substs: substs,
255             stmt: 0,
256             constants: Vec::new(),
257         });
258
259         let locals: Vec<Pointer> = arg_tys.chain(var_tys).chain(temp_tys).map(|ty| {
260             let size = self.type_size(ty);
261             self.memory.allocate(size)
262         }).collect();
263
264         self.frame_mut().locals = locals;
265     }
266
267     fn pop_stack_frame(&mut self) {
268         ::log_settings::settings().indentation -= 1;
269         let _frame = self.stack.pop().expect("tried to pop a stack frame, but there were none");
270         // TODO(solson): Deallocate local variables.
271     }
272
273     fn eval_terminator(&mut self, terminator: &mir::Terminator<'tcx>)
274             -> EvalResult<TerminatorTarget> {
275         use rustc::mir::repr::TerminatorKind::*;
276         let target = match terminator.kind {
277             Return => TerminatorTarget::Return,
278
279             Goto { target } => {
280                 self.frame_mut().next_block = target;
281                 TerminatorTarget::Block
282             },
283
284             If { ref cond, targets: (then_target, else_target) } => {
285                 let cond_ptr = self.eval_operand(cond)?;
286                 let cond_val = self.memory.read_bool(cond_ptr)?;
287                 self.frame_mut().next_block = if cond_val { then_target } else { else_target };
288                 TerminatorTarget::Block
289             }
290
291             SwitchInt { ref discr, ref values, ref targets, .. } => {
292                 let discr_ptr = self.eval_lvalue(discr)?.to_ptr();
293                 let discr_size = self
294                     .type_layout(self.lvalue_ty(discr))
295                     .size(&self.tcx.data_layout)
296                     .bytes() as usize;
297                 let discr_val = self.memory.read_uint(discr_ptr, discr_size)?;
298
299                 // Branch to the `otherwise` case by default, if no match is found.
300                 let mut target_block = targets[targets.len() - 1];
301
302                 for (index, val_const) in values.iter().enumerate() {
303                     let ptr = self.const_to_ptr(val_const)?;
304                     let val = self.memory.read_uint(ptr, discr_size)?;
305                     if discr_val == val {
306                         target_block = targets[index];
307                         break;
308                     }
309                 }
310
311                 self.frame_mut().next_block = target_block;
312                 TerminatorTarget::Block
313             }
314
315             Switch { ref discr, ref targets, adt_def } => {
316                 let adt_ptr = self.eval_lvalue(discr)?.to_ptr();
317                 let adt_ty = self.lvalue_ty(discr);
318                 let discr_val = self.read_discriminant_value(adt_ptr, adt_ty)?;
319                 let matching = adt_def.variants.iter()
320                     .position(|v| discr_val == v.disr_val.to_u64_unchecked());
321
322                 match matching {
323                     Some(i) => {
324                         self.frame_mut().next_block = targets[i];
325                         TerminatorTarget::Block
326                     },
327                     None => return Err(EvalError::InvalidDiscriminant),
328                 }
329             }
330
331             Call { ref func, ref args, ref destination, .. } => {
332                 let mut return_ptr = None;
333                 if let Some((ref lv, target)) = *destination {
334                     self.frame_mut().next_block = target;
335                     return_ptr = Some(self.eval_lvalue(lv)?.to_ptr());
336                 }
337
338                 let func_ty = self.operand_ty(func);
339                 match func_ty.sty {
340                     ty::TyFnDef(def_id, substs, fn_ty) => {
341                         use syntax::abi::Abi;
342                         match fn_ty.abi {
343                             Abi::RustIntrinsic => {
344                                 let name = self.tcx.item_name(def_id).as_str();
345                                 match fn_ty.sig.0.output {
346                                     ty::FnConverging(ty) => {
347                                         let size = self.type_size(ty);
348                                         let ret = return_ptr.unwrap();
349                                         self.call_intrinsic(&name, substs, args, ret, size)?
350                                     }
351                                     ty::FnDiverging => unimplemented!(),
352                                 }
353                             }
354
355                             Abi::C => {
356                                 match fn_ty.sig.0.output {
357                                     ty::FnConverging(ty) => {
358                                         let size = self.type_size(ty);
359                                         self.call_c_abi(def_id, args, return_ptr.unwrap(), size)?
360                                     }
361                                     ty::FnDiverging => unimplemented!(),
362                                 }
363                             }
364
365                             Abi::Rust | Abi::RustCall => {
366                                 // TODO(solson): Adjust the first argument when calling a Fn or
367                                 // FnMut closure via FnOnce::call_once.
368
369                                 // Only trait methods can have a Self parameter.
370                                 let (resolved_def_id, resolved_substs) = if substs.self_ty().is_some() {
371                                     self.trait_method(def_id, substs)
372                                 } else {
373                                     (def_id, substs)
374                                 };
375
376                                 let mut arg_srcs = Vec::new();
377                                 for arg in args {
378                                     let src = self.eval_operand(arg)?;
379                                     let src_ty = self.operand_ty(arg);
380                                     arg_srcs.push((src, src_ty));
381                                 }
382
383                                 if fn_ty.abi == Abi::RustCall && !args.is_empty() {
384                                     arg_srcs.pop();
385                                     let last_arg = args.last().unwrap();
386                                     let last = self.eval_operand(last_arg)?;
387                                     let last_ty = self.operand_ty(last_arg);
388                                     let last_layout = self.type_layout(last_ty);
389                                     match (&last_ty.sty, last_layout) {
390                                         (&ty::TyTuple(fields),
391                                          &Layout::Univariant { ref variant, .. }) => {
392                                             let offsets = iter::once(0)
393                                                 .chain(variant.offset_after_field.iter()
394                                                     .map(|s| s.bytes()));
395                                             for (offset, ty) in offsets.zip(fields) {
396                                                 let src = last.offset(offset as isize);
397                                                 arg_srcs.push((src, ty));
398                                             }
399                                         }
400                                         ty => panic!("expected tuple as last argument in function with 'rust-call' ABI, got {:?}", ty),
401                                     }
402                                 }
403
404                                 let mir = self.load_mir(resolved_def_id);
405                                 self.push_stack_frame(def_id, terminator.span, mir, resolved_substs, return_ptr);
406
407                                 for (i, (src, src_ty)) in arg_srcs.into_iter().enumerate() {
408                                     let dest = self.frame().locals[i];
409                                     self.move_(src, dest, src_ty)?;
410                                 }
411
412                                 TerminatorTarget::Call
413                             }
414
415                             abi => return Err(EvalError::Unimplemented(format!("can't handle function with {:?} ABI", abi))),
416                         }
417                     }
418
419                     _ => return Err(EvalError::Unimplemented(format!("can't handle callee of type {:?}", func_ty))),
420                 }
421             }
422
423             Drop { ref value, target, .. } => {
424                 let ptr = self.eval_lvalue(value)?.to_ptr();
425                 let ty = self.lvalue_ty(value);
426                 self.drop(ptr, ty)?;
427                 self.frame_mut().next_block = target;
428                 TerminatorTarget::Block
429             }
430
431             Resume => unimplemented!(),
432         };
433
434         Ok(target)
435     }
436
437     fn drop(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<()> {
438         if !self.type_needs_drop(ty) {
439             debug!("no need to drop {:?}", ty);
440             return Ok(());
441         }
442         trace!("-need to drop {:?}", ty);
443
444         // TODO(solson): Call user-defined Drop::drop impls.
445
446         match ty.sty {
447             ty::TyBox(contents_ty) => {
448                 match self.memory.read_ptr(ptr) {
449                     Ok(contents_ptr) => {
450                         self.drop(contents_ptr, contents_ty)?;
451                         trace!("-deallocating box");
452                         self.memory.deallocate(contents_ptr)?;
453                     }
454                     Err(EvalError::ReadBytesAsPointer) => {
455                         let size = self.memory.pointer_size;
456                         let possible_drop_fill = self.memory.read_bytes(ptr, size)?;
457                         if possible_drop_fill.iter().all(|&b| b == mem::POST_DROP_U8) {
458                             return Ok(());
459                         } else {
460                             return Err(EvalError::ReadBytesAsPointer);
461                         }
462                     }
463                     Err(e) => return Err(e),
464                 }
465             }
466
467             // TODO(solson): Implement drop for other relevant types (e.g. aggregates).
468             _ => {}
469         }
470
471         // Filling drop.
472         // FIXME(solson): Trait objects (with no static size) probably get filled, too.
473         let size = self.type_size(ty);
474         self.memory.drop_fill(ptr, size)?;
475
476         Ok(())
477     }
478
479     fn read_discriminant_value(&self, adt_ptr: Pointer, adt_ty: Ty<'tcx>) -> EvalResult<u64> {
480         use rustc::ty::layout::Layout::*;
481         let adt_layout = self.type_layout(adt_ty);
482
483         let discr_val = match *adt_layout {
484             General { discr, .. } | CEnum { discr, .. } => {
485                 let discr_size = discr.size().bytes();
486                 self.memory.read_uint(adt_ptr, discr_size as usize)?
487             }
488
489             RawNullablePointer { nndiscr, .. } => {
490                 self.read_nonnull_discriminant_value(adt_ptr, nndiscr)?
491             }
492
493             StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
494                 let offset = self.nonnull_offset(adt_ty, nndiscr, discrfield)?;
495                 let nonnull = adt_ptr.offset(offset.bytes() as isize);
496                 self.read_nonnull_discriminant_value(nonnull, nndiscr)?
497             }
498
499             // The discriminant_value intrinsic returns 0 for non-sum types.
500             Array { .. } | FatPointer { .. } | Scalar { .. } | Univariant { .. } |
501             Vector { .. } => 0,
502         };
503
504         Ok(discr_val)
505     }
506
507     fn read_nonnull_discriminant_value(&self, ptr: Pointer, nndiscr: u64) -> EvalResult<u64> {
508         let not_null = match self.memory.read_usize(ptr) {
509             Ok(0) => false,
510             Ok(_) | Err(EvalError::ReadPointerAsBytes) => true,
511             Err(e) => return Err(e),
512         };
513         assert!(nndiscr == 0 || nndiscr == 1);
514         Ok(if not_null { nndiscr } else { 1 - nndiscr })
515     }
516
517     fn call_intrinsic(
518         &mut self,
519         name: &str,
520         substs: &'tcx Substs<'tcx>,
521         args: &[mir::Operand<'tcx>],
522         dest: Pointer,
523         dest_size: usize
524     ) -> EvalResult<TerminatorTarget> {
525         let args_res: EvalResult<Vec<Pointer>> = args.iter()
526             .map(|arg| self.eval_operand(arg))
527             .collect();
528         let args = args_res?;
529
530         match name {
531             // FIXME(solson): Handle different integer types correctly.
532             "add_with_overflow" => {
533                 let ty = *substs.types.get(subst::FnSpace, 0);
534                 let size = self.type_size(ty);
535                 let left = self.memory.read_int(args[0], size)?;
536                 let right = self.memory.read_int(args[1], size)?;
537                 let (n, overflowed) = unsafe {
538                     ::std::intrinsics::add_with_overflow::<i64>(left, right)
539                 };
540                 self.memory.write_int(dest, n, size)?;
541                 self.memory.write_bool(dest.offset(size as isize), overflowed)?;
542             }
543
544             "assume" => {}
545
546             "copy_nonoverlapping" => {
547                 let elem_ty = *substs.types.get(subst::FnSpace, 0);
548                 let elem_size = self.type_size(elem_ty);
549                 let src = self.memory.read_ptr(args[0])?;
550                 let dest = self.memory.read_ptr(args[1])?;
551                 let count = self.memory.read_isize(args[2])?;
552                 self.memory.copy(src, dest, count as usize * elem_size)?;
553             }
554
555             "discriminant_value" => {
556                 let ty = *substs.types.get(subst::FnSpace, 0);
557                 let adt_ptr = self.memory.read_ptr(args[0])?;
558                 let discr_val = self.read_discriminant_value(adt_ptr, ty)?;
559                 self.memory.write_uint(dest, discr_val, dest_size)?;
560             }
561
562             "forget" => {
563                 let arg_ty = *substs.types.get(subst::FnSpace, 0);
564                 let arg_size = self.type_size(arg_ty);
565                 self.memory.drop_fill(args[0], arg_size)?;
566             }
567
568             "init" => self.memory.write_repeat(dest, 0, dest_size)?,
569
570             "min_align_of" => {
571                 self.memory.write_int(dest, 1, dest_size)?;
572             }
573
574             "move_val_init" => {
575                 let ty = *substs.types.get(subst::FnSpace, 0);
576                 let ptr = self.memory.read_ptr(args[0])?;
577                 self.move_(args[1], ptr, ty)?;
578             }
579
580             // FIXME(solson): Handle different integer types correctly.
581             "mul_with_overflow" => {
582                 let ty = *substs.types.get(subst::FnSpace, 0);
583                 let size = self.type_size(ty);
584                 let left = self.memory.read_int(args[0], size)?;
585                 let right = self.memory.read_int(args[1], size)?;
586                 let (n, overflowed) = unsafe {
587                     ::std::intrinsics::mul_with_overflow::<i64>(left, right)
588                 };
589                 self.memory.write_int(dest, n, size)?;
590                 self.memory.write_bool(dest.offset(size as isize), overflowed)?;
591             }
592
593             "offset" => {
594                 let pointee_ty = *substs.types.get(subst::FnSpace, 0);
595                 let pointee_size = self.type_size(pointee_ty) as isize;
596                 let ptr_arg = args[0];
597                 let offset = self.memory.read_isize(args[1])?;
598
599                 match self.memory.read_ptr(ptr_arg) {
600                     Ok(ptr) => {
601                         let result_ptr = ptr.offset(offset as isize * pointee_size);
602                         self.memory.write_ptr(dest, result_ptr)?;
603                     }
604                     Err(EvalError::ReadBytesAsPointer) => {
605                         let addr = self.memory.read_isize(ptr_arg)?;
606                         let result_addr = addr + offset * pointee_size as i64;
607                         self.memory.write_isize(dest, result_addr)?;
608                     }
609                     Err(e) => return Err(e),
610                 }
611             }
612
613             // FIXME(solson): Handle different integer types correctly. Use primvals?
614             "overflowing_sub" => {
615                 let ty = *substs.types.get(subst::FnSpace, 0);
616                 let size = self.type_size(ty);
617                 let left = self.memory.read_int(args[0], size)?;
618                 let right = self.memory.read_int(args[1], size)?;
619                 let n = left.wrapping_sub(right);
620                 self.memory.write_int(dest, n, size)?;
621             }
622
623             "size_of" => {
624                 let ty = *substs.types.get(subst::FnSpace, 0);
625                 let size = self.type_size(ty) as u64;
626                 self.memory.write_uint(dest, size, dest_size)?;
627             }
628
629             "size_of_val" => {
630                 let ty = *substs.types.get(subst::FnSpace, 0);
631                 if self.type_is_sized(ty) {
632                     let size = self.type_size(ty) as u64;
633                     self.memory.write_uint(dest, size, dest_size)?;
634                 } else {
635                     match ty.sty {
636                         ty::TySlice(_) | ty::TyStr => {
637                             let elem_ty = ty.sequence_element_type(self.tcx);
638                             let elem_size = self.type_size(elem_ty) as u64;
639                             let ptr_size = self.memory.pointer_size as isize;
640                             let n = self.memory.read_usize(args[0].offset(ptr_size))?;
641                             self.memory.write_uint(dest, n * elem_size, dest_size)?;
642                         }
643
644                         _ => return Err(EvalError::Unimplemented(format!("unimplemented: size_of_val::<{:?}>", ty))),
645                     }
646                 }
647             }
648
649             "transmute" => {
650                 let ty = *substs.types.get(subst::FnSpace, 0);
651                 self.move_(args[0], dest, ty)?;
652             }
653             "uninit" => self.memory.mark_definedness(dest, dest_size, false)?,
654
655             name => return Err(EvalError::Unimplemented(format!("unimplemented intrinsic: {}", name))),
656         }
657
658         // Since we pushed no stack frame, the main loop will act
659         // as if the call just completed and it's returning to the
660         // current frame.
661         Ok(TerminatorTarget::Call)
662     }
663
664     fn call_c_abi(
665         &mut self,
666         def_id: DefId,
667         args: &[mir::Operand<'tcx>],
668         dest: Pointer,
669         dest_size: usize,
670     ) -> EvalResult<TerminatorTarget> {
671         let name = self.tcx.item_name(def_id);
672         let attrs = self.tcx.get_attrs(def_id);
673         let link_name = match attr::first_attr_value_str_by_name(&attrs, "link_name") {
674             Some(ln) => ln.clone(),
675             None => name.as_str(),
676         };
677
678         let args_res: EvalResult<Vec<Pointer>> = args.iter()
679             .map(|arg| self.eval_operand(arg))
680             .collect();
681         let args = args_res?;
682
683         match &link_name[..] {
684             "__rust_allocate" => {
685                 let size = self.memory.read_usize(args[0])?;
686                 let ptr = self.memory.allocate(size as usize);
687                 self.memory.write_ptr(dest, ptr)?;
688             }
689
690             "__rust_reallocate" => {
691                 let ptr = self.memory.read_ptr(args[0])?;
692                 let size = self.memory.read_usize(args[2])?;
693                 self.memory.reallocate(ptr, size as usize)?;
694                 self.memory.write_ptr(dest, ptr)?;
695             }
696
697             "memcmp" => {
698                 let left = self.memory.read_ptr(args[0])?;
699                 let right = self.memory.read_ptr(args[1])?;
700                 let n = self.memory.read_usize(args[2])? as usize;
701
702                 let result = {
703                     let left_bytes = self.memory.read_bytes(left, n)?;
704                     let right_bytes = self.memory.read_bytes(right, n)?;
705
706                     use std::cmp::Ordering::*;
707                     match left_bytes.cmp(right_bytes) {
708                         Less => -1,
709                         Equal => 0,
710                         Greater => 1,
711                     }
712                 };
713
714                 self.memory.write_int(dest, result, dest_size)?;
715             }
716
717             _ => return Err(EvalError::Unimplemented(format!("can't call C ABI function: {}", link_name))),
718         }
719
720         // Since we pushed no stack frame, the main loop will act
721         // as if the call just completed and it's returning to the
722         // current frame.
723         Ok(TerminatorTarget::Call)
724     }
725
726     fn assign_fields<I: IntoIterator<Item = u64>>(
727         &mut self,
728         dest: Pointer,
729         offsets: I,
730         operands: &[mir::Operand<'tcx>],
731     ) -> EvalResult<()> {
732         for (offset, operand) in offsets.into_iter().zip(operands) {
733             let src = self.eval_operand(operand)?;
734             let src_ty = self.operand_ty(operand);
735             let field_dest = dest.offset(offset as isize);
736             self.move_(src, field_dest, src_ty)?;
737         }
738         Ok(())
739     }
740
741     fn eval_assignment(&mut self, lvalue: &mir::Lvalue<'tcx>, rvalue: &mir::Rvalue<'tcx>)
742         -> EvalResult<()>
743     {
744         let dest = self.eval_lvalue(lvalue)?.to_ptr();
745         let dest_ty = self.lvalue_ty(lvalue);
746         let dest_layout = self.type_layout(dest_ty);
747
748         use rustc::mir::repr::Rvalue::*;
749         match *rvalue {
750             Use(ref operand) => {
751                 let src = self.eval_operand(operand)?;
752                 self.move_(src, dest, dest_ty)?;
753             }
754
755             BinaryOp(bin_op, ref left, ref right) => {
756                 let left_ptr = self.eval_operand(left)?;
757                 let left_ty = self.operand_ty(left);
758                 let left_val = self.read_primval(left_ptr, left_ty)?;
759
760                 let right_ptr = self.eval_operand(right)?;
761                 let right_ty = self.operand_ty(right);
762                 let right_val = self.read_primval(right_ptr, right_ty)?;
763
764                 let val = primval::binary_op(bin_op, left_val, right_val)?;
765                 self.memory.write_primval(dest, val)?;
766             }
767
768             UnaryOp(un_op, ref operand) => {
769                 let ptr = self.eval_operand(operand)?;
770                 let ty = self.operand_ty(operand);
771                 let val = self.read_primval(ptr, ty)?;
772                 self.memory.write_primval(dest, primval::unary_op(un_op, val)?)?;
773             }
774
775             Aggregate(ref kind, ref operands) => {
776                 use rustc::ty::layout::Layout::*;
777                 match *dest_layout {
778                     Univariant { ref variant, .. } => {
779                         let offsets = iter::once(0)
780                             .chain(variant.offset_after_field.iter().map(|s| s.bytes()));
781                         self.assign_fields(dest, offsets, operands)?;
782                     }
783
784                     Array { .. } => {
785                         let elem_size = match dest_ty.sty {
786                             ty::TyArray(elem_ty, _) => self.type_size(elem_ty) as u64,
787                             _ => panic!("tried to assign {:?} to non-array type {:?}",
788                                         kind, dest_ty),
789                         };
790                         let offsets = (0..).map(|i| i * elem_size);
791                         self.assign_fields(dest, offsets, operands)?;
792                     }
793
794                     General { discr, ref variants, .. } => {
795                         if let mir::AggregateKind::Adt(adt_def, variant, _) = *kind {
796                             let discr_val = adt_def.variants[variant].disr_val.to_u64_unchecked();
797                             let discr_size = discr.size().bytes() as usize;
798                             self.memory.write_uint(dest, discr_val, discr_size)?;
799
800                             let offsets = variants[variant].offset_after_field.iter()
801                                 .map(|s| s.bytes());
802                             self.assign_fields(dest, offsets, operands)?;
803                         } else {
804                             panic!("tried to assign {:?} to Layout::General", kind);
805                         }
806                     }
807
808                     RawNullablePointer { nndiscr, .. } => {
809                         if let mir::AggregateKind::Adt(_, variant, _) = *kind {
810                             if nndiscr == variant as u64 {
811                                 assert_eq!(operands.len(), 1);
812                                 let operand = &operands[0];
813                                 let src = self.eval_operand(operand)?;
814                                 let src_ty = self.operand_ty(operand);
815                                 self.move_(src, dest, src_ty)?;
816                             } else {
817                                 assert_eq!(operands.len(), 0);
818                                 self.memory.write_isize(dest, 0)?;
819                             }
820                         } else {
821                             panic!("tried to assign {:?} to Layout::RawNullablePointer", kind);
822                         }
823                     }
824
825                     StructWrappedNullablePointer { nndiscr, ref nonnull, ref discrfield } => {
826                         if let mir::AggregateKind::Adt(_, variant, _) = *kind {
827                             if nndiscr == variant as u64 {
828                                 let offsets = iter::once(0)
829                                     .chain(nonnull.offset_after_field.iter().map(|s| s.bytes()));
830                                 try!(self.assign_fields(dest, offsets, operands));
831                             } else {
832                                 assert_eq!(operands.len(), 0);
833                                 let offset = self.nonnull_offset(dest_ty, nndiscr, discrfield)?;
834                                 let dest = dest.offset(offset.bytes() as isize);
835                                 try!(self.memory.write_isize(dest, 0));
836                             }
837                         } else {
838                             panic!("tried to assign {:?} to Layout::RawNullablePointer", kind);
839                         }
840                     }
841
842                     CEnum { discr, signed, .. } => {
843                         assert_eq!(operands.len(), 0);
844                         if let mir::AggregateKind::Adt(adt_def, variant, _) = *kind {
845                             let val = adt_def.variants[variant].disr_val.to_u64_unchecked();
846                             let size = discr.size().bytes() as usize;
847
848                             if signed {
849                                 self.memory.write_int(dest, val as i64, size)?;
850                             } else {
851                                 self.memory.write_uint(dest, val, size)?;
852                             }
853                         } else {
854                             panic!("tried to assign {:?} to Layout::CEnum", kind);
855                         }
856                     }
857
858                     _ => return Err(EvalError::Unimplemented(format!("can't handle destination layout {:?} when assigning {:?}", dest_layout, kind))),
859                 }
860             }
861
862             Repeat(ref operand, _) => {
863                 let (elem_size, length) = match dest_ty.sty {
864                     ty::TyArray(elem_ty, n) => (self.type_size(elem_ty), n),
865                     _ => panic!("tried to assign array-repeat to non-array type {:?}", dest_ty),
866                 };
867
868                 let src = self.eval_operand(operand)?;
869                 for i in 0..length {
870                     let elem_dest = dest.offset((i * elem_size) as isize);
871                     self.memory.copy(src, elem_dest, elem_size)?;
872                 }
873             }
874
875             Len(ref lvalue) => {
876                 let src = self.eval_lvalue(lvalue)?;
877                 let ty = self.lvalue_ty(lvalue);
878                 let len = match ty.sty {
879                     ty::TyArray(_, n) => n as u64,
880                     ty::TySlice(_) => if let LvalueExtra::Length(n) = src.extra {
881                         n
882                     } else {
883                         panic!("Rvalue::Len of a slice given non-slice pointer: {:?}", src);
884                     },
885                     _ => panic!("Rvalue::Len expected array or slice, got {:?}", ty),
886                 };
887                 self.memory.write_usize(dest, len)?;
888             }
889
890             Ref(_, _, ref lvalue) => {
891                 let lv = self.eval_lvalue(lvalue)?;
892                 self.memory.write_ptr(dest, lv.ptr)?;
893                 match lv.extra {
894                     LvalueExtra::None => {},
895                     LvalueExtra::Length(len) => {
896                         let len_ptr = dest.offset(self.memory.pointer_size as isize);
897                         self.memory.write_usize(len_ptr, len)?;
898                     }
899                     LvalueExtra::DowncastVariant(..) =>
900                         panic!("attempted to take a reference to an enum downcast lvalue"),
901                 }
902             }
903
904             Box(ty) => {
905                 let size = self.type_size(ty);
906                 let ptr = self.memory.allocate(size);
907                 self.memory.write_ptr(dest, ptr)?;
908             }
909
910             Cast(kind, ref operand, dest_ty) => {
911                 let src = self.eval_operand(operand)?;
912                 let src_ty = self.operand_ty(operand);
913
914                 use rustc::mir::repr::CastKind::*;
915                 match kind {
916                     Unsize => {
917                         self.move_(src, dest, src_ty)?;
918                         let src_pointee_ty = pointee_type(src_ty).unwrap();
919                         let dest_pointee_ty = pointee_type(dest_ty).unwrap();
920
921                         match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
922                             (&ty::TyArray(_, length), &ty::TySlice(_)) => {
923                                 let len_ptr = dest.offset(self.memory.pointer_size as isize);
924                                 self.memory.write_usize(len_ptr, length as u64)?;
925                             }
926
927                             _ => return Err(EvalError::Unimplemented(format!("can't handle cast: {:?}", rvalue))),
928                         }
929                     }
930
931                     Misc => {
932                         // FIXME(solson): Wrong for almost everything.
933                         let size = dest_layout.size(&self.tcx.data_layout).bytes() as usize;
934                         self.memory.copy(src, dest, size)?;
935                     }
936
937                     _ => return Err(EvalError::Unimplemented(format!("can't handle cast: {:?}", rvalue))),
938                 }
939             }
940
941             Slice { .. } => unimplemented!(),
942             InlineAsm { .. } => unimplemented!(),
943         }
944
945         Ok(())
946     }
947
948     fn nonnull_offset(&self, ty: Ty<'tcx>, nndiscr: u64, discrfield: &[u32]) -> EvalResult<Size> {
949         // Skip the constant 0 at the start meant for LLVM GEP.
950         let mut path = discrfield.iter().skip(1).map(|&i| i as usize);
951
952         // Handle the field index for the outer non-null variant.
953         let inner_ty = match ty.sty {
954             ty::TyEnum(adt_def, substs) => {
955                 let variant = &adt_def.variants[nndiscr as usize];
956                 let index = path.next().unwrap();
957                 let field = &variant.fields[index];
958                 field.ty(self.tcx, substs)
959             }
960             _ => panic!(
961                 "non-enum for StructWrappedNullablePointer: {}",
962                 ty,
963             ),
964         };
965
966         self.field_path_offset(inner_ty, path)
967     }
968
969     fn field_path_offset<I: Iterator<Item = usize>>(&self, mut ty: Ty<'tcx>, path: I) -> EvalResult<Size> {
970         let mut offset = Size::from_bytes(0);
971
972         // Skip the initial 0 intended for LLVM GEP.
973         for field_index in path {
974             let field_offset = self.get_field_offset(ty, field_index)?;
975             ty = self.get_field_ty(ty, field_index)?;
976             offset = offset.checked_add(field_offset, &self.tcx.data_layout).unwrap();
977         }
978
979         Ok(offset)
980     }
981
982     fn get_field_ty(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<Ty<'tcx>> {
983         match ty.sty {
984             ty::TyStruct(adt_def, substs) => {
985                 Ok(adt_def.struct_variant().fields[field_index].ty(self.tcx, substs))
986             }
987
988             ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
989             ty::TyRawPtr(ty::TypeAndMut { ty, .. }) |
990             ty::TyBox(ty) => {
991                 assert_eq!(field_index, 0);
992                 Ok(ty)
993             }
994             _ => Err(EvalError::Unimplemented(format!("can't handle type: {:?}", ty))),
995         }
996     }
997
998     fn get_field_offset(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<Size> {
999         let layout = self.type_layout(ty);
1000
1001         use rustc::ty::layout::Layout::*;
1002         match *layout {
1003             Univariant { .. } => {
1004                 assert_eq!(field_index, 0);
1005                 Ok(Size::from_bytes(0))
1006             }
1007             FatPointer { .. } => {
1008                 let bytes = layout::FAT_PTR_ADDR * self.memory.pointer_size;
1009                 Ok(Size::from_bytes(bytes as u64))
1010             }
1011             _ => Err(EvalError::Unimplemented(format!("can't handle type: {:?}, with layout: {:?}", ty, layout))),
1012         }
1013     }
1014
1015     fn eval_operand(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<Pointer> {
1016         use rustc::mir::repr::Operand::*;
1017         match *op {
1018             Consume(ref lvalue) => Ok(self.eval_lvalue(lvalue)?.to_ptr()),
1019             Constant(mir::Constant { ref literal, .. }) => {
1020                 use rustc::mir::repr::Literal::*;
1021                 match *literal {
1022                     Value { ref value } => Ok(self.const_to_ptr(value)?),
1023                     Item { def_id, substs } => {
1024                         let item_ty = self.tcx.lookup_item_type(def_id).subst(self.tcx, substs);
1025                         if item_ty.ty.is_fn() {
1026                             Err(EvalError::Unimplemented("unimplemented: mentions of function items".to_string()))
1027                         } else {
1028                             Ok(*self.statics.get(&def_id).expect("static should have been cached (rvalue)"))
1029                         }
1030                     },
1031                     Promoted { index } => Ok(*self.frame().promoted.get(&index).expect("a promoted constant hasn't been precomputed")),
1032                 }
1033             }
1034         }
1035     }
1036
1037     fn eval_lvalue(&mut self, lvalue: &mir::Lvalue<'tcx>) -> EvalResult<Lvalue> {
1038         use rustc::mir::repr::Lvalue::*;
1039         let ptr = match *lvalue {
1040             ReturnPointer => self.frame().return_ptr
1041                 .expect("ReturnPointer used in a function with no return value"),
1042             Arg(i) => self.frame().locals[i as usize],
1043             Var(i) => self.frame().locals[self.frame().var_offset + i as usize],
1044             Temp(i) => self.frame().locals[self.frame().temp_offset + i as usize],
1045
1046             Static(def_id) => *self.gecx.statics.get(&def_id).expect("static should have been cached (lvalue)"),
1047
1048             Projection(ref proj) => {
1049                 let base = self.eval_lvalue(&proj.base)?;
1050                 let base_ty = self.lvalue_ty(&proj.base);
1051                 let base_layout = self.type_layout(base_ty);
1052
1053                 use rustc::mir::repr::ProjectionElem::*;
1054                 match proj.elem {
1055                     Field(field, _) => {
1056                         use rustc::ty::layout::Layout::*;
1057                         let variant = match *base_layout {
1058                             Univariant { ref variant, .. } => variant,
1059                             General { ref variants, .. } => {
1060                                 if let LvalueExtra::DowncastVariant(variant_idx) = base.extra {
1061                                     &variants[variant_idx]
1062                                 } else {
1063                                     panic!("field access on enum had no variant index");
1064                                 }
1065                             }
1066                             RawNullablePointer { .. } => {
1067                                 assert_eq!(field.index(), 0);
1068                                 return Ok(base);
1069                             }
1070                             StructWrappedNullablePointer { ref nonnull, .. } => nonnull,
1071                             _ => panic!("field access on non-product type: {:?}", base_layout),
1072                         };
1073
1074                         let offset = variant.field_offset(field.index()).bytes();
1075                         base.ptr.offset(offset as isize)
1076                     },
1077
1078                     Downcast(_, variant) => {
1079                         use rustc::ty::layout::Layout::*;
1080                         match *base_layout {
1081                             General { discr, .. } => {
1082                                 return Ok(Lvalue {
1083                                     ptr: base.ptr.offset(discr.size().bytes() as isize),
1084                                     extra: LvalueExtra::DowncastVariant(variant),
1085                                 });
1086                             }
1087                             RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
1088                                 return Ok(base);
1089                             }
1090                             _ => panic!("variant downcast on non-aggregate: {:?}", base_layout),
1091                         }
1092                     },
1093
1094                     Deref => {
1095                         let pointee_ty = pointee_type(base_ty).expect("Deref of non-pointer");
1096                         let ptr = self.memory.read_ptr(base.ptr)?;
1097                         let extra = match pointee_ty.sty {
1098                             ty::TySlice(_) | ty::TyStr => {
1099                                 let len_ptr = base.ptr.offset(self.memory.pointer_size as isize);
1100                                 let len = self.memory.read_usize(len_ptr)?;
1101                                 LvalueExtra::Length(len)
1102                             }
1103                             ty::TyTrait(_) => unimplemented!(),
1104                             _ => LvalueExtra::None,
1105                         };
1106                         return Ok(Lvalue { ptr: ptr, extra: extra });
1107                     }
1108
1109                     Index(ref operand) => {
1110                         let elem_size = match base_ty.sty {
1111                             ty::TyArray(elem_ty, _) |
1112                             ty::TySlice(elem_ty) => self.type_size(elem_ty),
1113                             _ => panic!("indexing expected an array or slice, got {:?}", base_ty),
1114                         };
1115                         let n_ptr = self.eval_operand(operand)?;
1116                         let n = self.memory.read_usize(n_ptr)?;
1117                         base.ptr.offset(n as isize * elem_size as isize)
1118                     }
1119
1120                     ConstantIndex { .. } => unimplemented!(),
1121                 }
1122             }
1123         };
1124
1125         Ok(Lvalue { ptr: ptr, extra: LvalueExtra::None })
1126     }
1127
1128     // TODO(solson): Try making const_to_primval instead.
1129     fn const_to_ptr(&mut self, const_val: &const_val::ConstVal) -> EvalResult<Pointer> {
1130         use rustc::middle::const_val::ConstVal::*;
1131         match *const_val {
1132             Float(_f) => unimplemented!(),
1133             Integral(int) => {
1134                 // TODO(solson): Check int constant type.
1135                 let ptr = self.memory.allocate(8);
1136                 self.memory.write_uint(ptr, int.to_u64_unchecked(), 8)?;
1137                 Ok(ptr)
1138             }
1139             Str(ref s) => {
1140                 let psize = self.memory.pointer_size;
1141                 let static_ptr = self.memory.allocate(s.len());
1142                 let ptr = self.memory.allocate(psize * 2);
1143                 self.memory.write_bytes(static_ptr, s.as_bytes())?;
1144                 self.memory.write_ptr(ptr, static_ptr)?;
1145                 self.memory.write_usize(ptr.offset(psize as isize), s.len() as u64)?;
1146                 Ok(ptr)
1147             }
1148             ByteStr(ref bs) => {
1149                 let psize = self.memory.pointer_size;
1150                 let static_ptr = self.memory.allocate(bs.len());
1151                 let ptr = self.memory.allocate(psize);
1152                 self.memory.write_bytes(static_ptr, bs)?;
1153                 self.memory.write_ptr(ptr, static_ptr)?;
1154                 Ok(ptr)
1155             }
1156             Bool(b) => {
1157                 let ptr = self.memory.allocate(1);
1158                 self.memory.write_bool(ptr, b)?;
1159                 Ok(ptr)
1160             }
1161             Char(_c)          => unimplemented!(),
1162             Struct(_node_id)  => unimplemented!(),
1163             Tuple(_node_id)   => unimplemented!(),
1164             Function(_def_id) => unimplemented!(),
1165             Array(_, _)       => unimplemented!(),
1166             Repeat(_, _)      => unimplemented!(),
1167             Dummy             => unimplemented!(),
1168         }
1169     }
1170
1171     fn lvalue_ty(&self, lvalue: &mir::Lvalue<'tcx>) -> Ty<'tcx> {
1172         self.monomorphize(self.mir().lvalue_ty(self.tcx, lvalue).to_ty(self.tcx))
1173     }
1174
1175     fn operand_ty(&self, operand: &mir::Operand<'tcx>) -> Ty<'tcx> {
1176         self.monomorphize(self.mir().operand_ty(self.tcx, operand))
1177     }
1178
1179     fn monomorphize(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1180         let substituted = ty.subst(self.tcx, self.substs());
1181         self.tcx.normalize_associated_type(&substituted)
1182     }
1183
1184     fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
1185         self.tcx.type_needs_drop_given_env(ty, &self.tcx.empty_parameter_environment())
1186     }
1187
1188     fn move_(&mut self, src: Pointer, dest: Pointer, ty: Ty<'tcx>) -> EvalResult<()> {
1189         let size = self.type_size(ty);
1190         self.memory.copy(src, dest, size)?;
1191         if self.type_needs_drop(ty) {
1192             self.memory.drop_fill(src, size)?;
1193         }
1194         Ok(())
1195     }
1196
1197     fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
1198         ty.is_sized(self.tcx, &self.tcx.empty_parameter_environment(), DUMMY_SP)
1199     }
1200
1201     fn type_size(&self, ty: Ty<'tcx>) -> usize {
1202         self.type_layout(ty).size(&self.tcx.data_layout).bytes() as usize
1203     }
1204
1205     fn type_layout(&self, ty: Ty<'tcx>) -> &'tcx Layout {
1206         // TODO(solson): Is this inefficient? Needs investigation.
1207         let ty = self.monomorphize(ty);
1208
1209         self.tcx.normalizing_infer_ctxt(ProjectionMode::Any).enter(|infcx| {
1210             // TODO(solson): Report this error properly.
1211             ty.layout(&infcx).unwrap()
1212         })
1213     }
1214
1215     pub fn read_primval(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<PrimVal> {
1216         use syntax::ast::{IntTy, UintTy};
1217         let val = match (self.memory.pointer_size, &ty.sty) {
1218             (_, &ty::TyBool)              => PrimVal::Bool(self.memory.read_bool(ptr)?),
1219             (_, &ty::TyInt(IntTy::I8))    => PrimVal::I8(self.memory.read_int(ptr, 1)? as i8),
1220             (2, &ty::TyInt(IntTy::Is)) |
1221             (_, &ty::TyInt(IntTy::I16))   => PrimVal::I16(self.memory.read_int(ptr, 2)? as i16),
1222             (4, &ty::TyInt(IntTy::Is)) |
1223             (_, &ty::TyInt(IntTy::I32))   => PrimVal::I32(self.memory.read_int(ptr, 4)? as i32),
1224             (8, &ty::TyInt(IntTy::Is)) |
1225             (_, &ty::TyInt(IntTy::I64))   => PrimVal::I64(self.memory.read_int(ptr, 8)? as i64),
1226             (_, &ty::TyUint(UintTy::U8))  => PrimVal::U8(self.memory.read_uint(ptr, 1)? as u8),
1227             (2, &ty::TyUint(UintTy::Us)) |
1228             (_, &ty::TyUint(UintTy::U16)) => PrimVal::U16(self.memory.read_uint(ptr, 2)? as u16),
1229             (4, &ty::TyUint(UintTy::Us)) |
1230             (_, &ty::TyUint(UintTy::U32)) => PrimVal::U32(self.memory.read_uint(ptr, 4)? as u32),
1231             (8, &ty::TyUint(UintTy::Us)) |
1232             (_, &ty::TyUint(UintTy::U64)) => PrimVal::U64(self.memory.read_uint(ptr, 8)? as u64),
1233
1234             (_, &ty::TyRef(_, ty::TypeAndMut { ty, .. })) |
1235             (_, &ty::TyRawPtr(ty::TypeAndMut { ty, .. })) => {
1236                 if self.type_is_sized(ty) {
1237                     match self.memory.read_ptr(ptr) {
1238                         Ok(p) => PrimVal::AbstractPtr(p),
1239                         Err(EvalError::ReadBytesAsPointer) => {
1240                             PrimVal::IntegerPtr(self.memory.read_usize(ptr)?)
1241                         }
1242                         Err(e) => return Err(e),
1243                     }
1244                 } else {
1245                     return Err(EvalError::Unimplemented(format!("unimplemented: primitive read of fat pointer type: {:?}", ty)));
1246                 }
1247             }
1248
1249             _ => panic!("primitive read of non-primitive type: {:?}", ty),
1250         };
1251         Ok(val)
1252     }
1253
1254     fn frame(&self) -> &Frame<'mir, 'tcx> {
1255         self.stack.last().expect("no call frames exist")
1256     }
1257
1258     fn basic_block(&self) -> &mir::BasicBlockData<'tcx> {
1259         let frame = self.frame();
1260         frame.mir.basic_block_data(frame.next_block)
1261     }
1262
1263     fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx> {
1264         self.stack.last_mut().expect("no call frames exist")
1265     }
1266
1267     fn mir(&self) -> CachedMir<'mir, 'tcx> {
1268         self.frame().mir.clone()
1269     }
1270
1271     fn substs(&self) -> &'tcx Substs<'tcx> {
1272         self.frame().substs
1273     }
1274
1275     fn load_mir(&self, def_id: DefId) -> CachedMir<'mir, 'tcx> {
1276         match self.tcx.map.as_local_node_id(def_id) {
1277             Some(node_id) => CachedMir::Ref(self.mir_map.map.get(&node_id).unwrap()),
1278             None => {
1279                 let mut mir_cache = self.mir_cache.borrow_mut();
1280                 if let Some(mir) = mir_cache.get(&def_id) {
1281                     return CachedMir::Owned(mir.clone());
1282                 }
1283
1284                 let cs = &self.tcx.sess.cstore;
1285                 let mir = cs.maybe_get_item_mir(self.tcx, def_id).unwrap_or_else(|| {
1286                     panic!("no mir for {:?}", def_id);
1287                 });
1288                 let cached = Rc::new(mir);
1289                 mir_cache.insert(def_id, cached.clone());
1290                 CachedMir::Owned(cached)
1291             }
1292         }
1293     }
1294
1295     fn fulfill_obligation(&self, trait_ref: ty::PolyTraitRef<'tcx>) -> traits::Vtable<'tcx, ()> {
1296         // Do the initial selection for the obligation. This yields the shallow result we are
1297         // looking for -- that is, what specific impl.
1298         self.tcx.normalizing_infer_ctxt(ProjectionMode::Any).enter(|infcx| {
1299             let mut selcx = traits::SelectionContext::new(&infcx);
1300
1301             let obligation = traits::Obligation::new(
1302                 traits::ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID),
1303                 trait_ref.to_poly_trait_predicate(),
1304             );
1305             let selection = selcx.select(&obligation).unwrap().unwrap();
1306
1307             // Currently, we use a fulfillment context to completely resolve all nested obligations.
1308             // This is because they can inform the inference of the impl's type parameters.
1309             let mut fulfill_cx = traits::FulfillmentContext::new();
1310             let vtable = selection.map(|predicate| {
1311                 fulfill_cx.register_predicate_obligation(&infcx, predicate);
1312             });
1313             infcx.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &vtable)
1314         })
1315     }
1316
1317     /// Trait method, which has to be resolved to an impl method.
1318     pub fn trait_method(
1319         &self,
1320         def_id: DefId,
1321         substs: &'tcx Substs<'tcx>
1322     ) -> (DefId, &'tcx Substs<'tcx>) {
1323         let method_item = self.tcx.impl_or_trait_item(def_id);
1324         let trait_id = method_item.container().id();
1325         let trait_ref = ty::Binder(substs.to_trait_ref(self.tcx, trait_id));
1326         match self.fulfill_obligation(trait_ref) {
1327             traits::VtableImpl(vtable_impl) => {
1328                 let impl_did = vtable_impl.impl_def_id;
1329                 let mname = self.tcx.item_name(def_id);
1330                 // Create a concatenated set of substitutions which includes those from the impl
1331                 // and those from the method:
1332                 let impl_substs = vtable_impl.substs.with_method_from(substs);
1333                 let substs = self.tcx.mk_substs(impl_substs);
1334                 let mth = get_impl_method(self.tcx, impl_did, substs, mname);
1335
1336                 (mth.method.def_id, mth.substs)
1337             }
1338
1339             traits::VtableClosure(vtable_closure) =>
1340                 (vtable_closure.closure_def_id, vtable_closure.substs.func_substs),
1341
1342             traits::VtableFnPointer(_fn_ty) => {
1343                 let _trait_closure_kind = self.tcx.lang_items.fn_trait_kind(trait_id).unwrap();
1344                 unimplemented!()
1345                 // let llfn = trans_fn_pointer_shim(ccx, trait_closure_kind, fn_ty);
1346
1347                 // let method_ty = def_ty(tcx, def_id, substs);
1348                 // let fn_ptr_ty = match method_ty.sty {
1349                 //     ty::TyFnDef(_, _, fty) => tcx.mk_ty(ty::TyFnPtr(fty)),
1350                 //     _ => unreachable!("expected fn item type, found {}",
1351                 //                       method_ty)
1352                 // };
1353                 // Callee::ptr(immediate_rvalue(llfn, fn_ptr_ty))
1354             }
1355
1356             traits::VtableObject(ref _data) => {
1357                 unimplemented!()
1358                 // Callee {
1359                 //     data: Virtual(traits::get_vtable_index_of_object_method(
1360                 //                   tcx, data, def_id)),
1361                 //                   ty: def_ty(tcx, def_id, substs)
1362                 // }
1363             }
1364             vtable => unreachable!("resolved vtable bad vtable {:?} in trans", vtable),
1365         }
1366     }
1367 }
1368
1369 fn pointee_type(ptr_ty: ty::Ty) -> Option<ty::Ty> {
1370     match ptr_ty.sty {
1371         ty::TyRef(_, ty::TypeAndMut { ty, .. }) |
1372         ty::TyRawPtr(ty::TypeAndMut { ty, .. }) |
1373         ty::TyBox(ty) => {
1374             Some(ty)
1375         }
1376         _ => None,
1377     }
1378 }
1379
1380 impl Lvalue {
1381     fn to_ptr(self) -> Pointer {
1382         assert_eq!(self.extra, LvalueExtra::None);
1383         self.ptr
1384     }
1385 }
1386
1387 impl<'mir, 'tcx: 'mir> Deref for CachedMir<'mir, 'tcx> {
1388     type Target = mir::Mir<'tcx>;
1389     fn deref(&self) -> &mir::Mir<'tcx> {
1390         match *self {
1391             CachedMir::Ref(r) => r,
1392             CachedMir::Owned(ref rc) => rc,
1393         }
1394     }
1395 }
1396
1397 #[derive(Debug)]
1398 pub struct ImplMethod<'tcx> {
1399     pub method: Rc<ty::Method<'tcx>>,
1400     pub substs: &'tcx Substs<'tcx>,
1401     pub is_provided: bool,
1402 }
1403
1404 /// Locates the applicable definition of a method, given its name.
1405 pub fn get_impl_method<'a, 'tcx>(
1406     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1407     impl_def_id: DefId,
1408     substs: &'tcx Substs<'tcx>,
1409     name: ast::Name,
1410 ) -> ImplMethod<'tcx> {
1411     assert!(!substs.types.needs_infer());
1412
1413     let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
1414     let trait_def = tcx.lookup_trait_def(trait_def_id);
1415
1416     match trait_def.ancestors(impl_def_id).fn_defs(tcx, name).next() {
1417         Some(node_item) => {
1418             let substs = tcx.normalizing_infer_ctxt(ProjectionMode::Any).enter(|infcx| {
1419                 let substs = traits::translate_substs(&infcx, impl_def_id,
1420                                                       substs, node_item.node);
1421                 tcx.lift(&substs).unwrap_or_else(|| {
1422                     bug!("trans::meth::get_impl_method: translate_substs \
1423                           returned {:?} which contains inference types/regions",
1424                          substs);
1425                 })
1426             });
1427             ImplMethod {
1428                 method: node_item.item,
1429                 substs: substs,
1430                 is_provided: node_item.node.is_from_trait(),
1431             }
1432         }
1433         None => {
1434             bug!("method {:?} not found in {:?}", name, impl_def_id)
1435         }
1436     }
1437 }
1438
1439 pub fn interpret_start_points<'a, 'tcx>(
1440     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1441     mir_map: &MirMap<'tcx>,
1442 ) {
1443     let initial_indentation = ::log_settings::settings().indentation;
1444     for (&id, mir) in &mir_map.map {
1445         for attr in tcx.map.attrs(id) {
1446             use syntax::attr::AttrMetaMethods;
1447             if attr.check_name("miri_run") {
1448                 let item = tcx.map.expect_item(id);
1449
1450                 ::log_settings::settings().indentation = initial_indentation;
1451
1452                 debug!("Interpreting: {}", item.name);
1453
1454                 let mut gecx = GlobalEvalContext::new(tcx, mir_map);
1455                 match gecx.call(mir, tcx.map.local_def_id(id)) {
1456                     Ok(Some(return_ptr)) => if log_enabled!(::log::LogLevel::Debug) {
1457                         gecx.memory.dump(return_ptr.alloc_id);
1458                     },
1459                     Ok(None) => warn!("diverging function returned"),
1460                     Err(_e) => {
1461                         // TODO(solson): Detect whether the error was already reported or not.
1462                         // tcx.sess.err(&e.to_string());
1463                     }
1464                 }
1465             }
1466         }
1467     }
1468 }
1469
1470 // TODO(solson): Upstream these methods into rustc::ty::layout.
1471
1472 trait IntegerExt {
1473     fn size(self) -> Size;
1474 }
1475
1476 impl IntegerExt for layout::Integer {
1477     fn size(self) -> Size {
1478         use rustc::ty::layout::Integer::*;
1479         match self {
1480             I1 | I8 => Size::from_bits(8),
1481             I16 => Size::from_bits(16),
1482             I32 => Size::from_bits(32),
1483             I64 => Size::from_bits(64),
1484         }
1485     }
1486 }
1487
1488 trait StructExt {
1489     fn field_offset(&self, index: usize) -> Size;
1490 }
1491
1492 impl StructExt for layout::Struct {
1493     fn field_offset(&self, index: usize) -> Size {
1494         if index == 0 {
1495             Size::from_bytes(0)
1496         } else {
1497             self.offset_after_field[index - 1]
1498         }
1499     }
1500 }