]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/place.rs
Remove deprecated unstable attribute `#[simd]`
[rust.git] / src / librustc_mir / interpret / place.rs
1 use rustc::mir;
2 use rustc::ty::{self, Ty};
3 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
4 use rustc_data_structures::indexed_vec::Idx;
5
6 use rustc::mir::interpret::{GlobalId, Value, PrimVal, EvalResult, Pointer, MemoryPointer};
7 use super::{EvalContext, Machine, ValTy};
8 use interpret::memory::HasMemory;
9
10 #[derive(Copy, Clone, Debug)]
11 pub enum Place {
12     /// An place referring to a value allocated in the `Memory` system.
13     Ptr {
14         /// An place may have an invalid (integral or undef) pointer,
15         /// since it might be turned back into a reference
16         /// before ever being dereferenced.
17         ptr: Pointer,
18         align: Align,
19         extra: PlaceExtra,
20     },
21
22     /// An place referring to a value on the stack. Represented by a stack frame index paired with
23     /// a Mir local index.
24     Local { frame: usize, local: mir::Local },
25 }
26
27 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
28 pub enum PlaceExtra {
29     None,
30     Length(u64),
31     Vtable(MemoryPointer),
32     DowncastVariant(usize),
33 }
34
35 impl<'tcx> Place {
36     /// Produces an Place that will error if attempted to be read from
37     pub fn undef() -> Self {
38         Self::from_primval_ptr(PrimVal::Undef.into(), Align::from_bytes(1, 1).unwrap())
39     }
40
41     pub fn from_primval_ptr(ptr: Pointer, align: Align) -> Self {
42         Place::Ptr {
43             ptr,
44             align,
45             extra: PlaceExtra::None,
46         }
47     }
48
49     pub fn from_ptr(ptr: MemoryPointer, align: Align) -> Self {
50         Self::from_primval_ptr(ptr.into(), align)
51     }
52
53     pub fn to_ptr_align_extra(self) -> (Pointer, Align, PlaceExtra) {
54         match self {
55             Place::Ptr { ptr, align, extra } => (ptr, align, extra),
56             _ => bug!("to_ptr_and_extra: expected Place::Ptr, got {:?}", self),
57
58         }
59     }
60
61     pub fn to_ptr_align(self) -> (Pointer, Align) {
62         let (ptr, align, _extra) = self.to_ptr_align_extra();
63         (ptr, align)
64     }
65
66     pub fn to_ptr(self) -> EvalResult<'tcx, MemoryPointer> {
67         // At this point, we forget about the alignment information -- the place has been turned into a reference,
68         // and no matter where it came from, it now must be aligned.
69         self.to_ptr_align().0.to_ptr()
70     }
71
72     pub(super) fn elem_ty_and_len(self, ty: Ty<'tcx>) -> (Ty<'tcx>, u64) {
73         match ty.sty {
74             ty::TyArray(elem, n) => (elem, n.val.to_const_int().unwrap().to_u64().unwrap() as u64),
75
76             ty::TySlice(elem) => {
77                 match self {
78                     Place::Ptr { extra: PlaceExtra::Length(len), .. } => (elem, len),
79                     _ => {
80                         bug!(
81                             "elem_ty_and_len of a TySlice given non-slice place: {:?}",
82                             self
83                         )
84                     }
85                 }
86             }
87
88             _ => bug!("elem_ty_and_len expected array or slice, got {:?}", ty),
89         }
90     }
91 }
92
93 impl<'a, 'tcx, M: Machine<'tcx>> EvalContext<'a, 'tcx, M> {
94     /// Reads a value from the place without going through the intermediate step of obtaining
95     /// a `miri::Place`
96     pub fn try_read_place(
97         &mut self,
98         place: &mir::Place<'tcx>,
99     ) -> EvalResult<'tcx, Option<Value>> {
100         use rustc::mir::Place::*;
101         match *place {
102             // Might allow this in the future, right now there's no way to do this from Rust code anyway
103             Local(mir::RETURN_PLACE) => err!(ReadFromReturnPointer),
104             // Directly reading a local will always succeed
105             Local(local) => self.frame().get_local(local).map(Some),
106             // Directly reading a static will always succeed
107             Static(ref static_) => {
108                 let instance = ty::Instance::mono(self.tcx, static_.def_id);
109                 Ok(Some(self.read_global_as_value(GlobalId {
110                     instance,
111                     promoted: None,
112                 }, self.layout_of(self.place_ty(place))?)))
113             }
114             Projection(ref proj) => self.try_read_place_projection(proj),
115         }
116     }
117
118     fn try_read_place_projection(
119         &mut self,
120         proj: &mir::PlaceProjection<'tcx>,
121     ) -> EvalResult<'tcx, Option<Value>> {
122         use rustc::mir::ProjectionElem::*;
123         let base = match self.try_read_place(&proj.base)? {
124             Some(base) => base,
125             None => return Ok(None),
126         };
127         let base_ty = self.place_ty(&proj.base);
128         match proj.elem {
129             Field(field, _) => {
130                 let base_layout = self.layout_of(base_ty)?;
131                 let field_index = field.index();
132                 let field = base_layout.field(&self, field_index)?;
133                 let offset = base_layout.fields.offset(field_index);
134                 match base {
135                     // the field covers the entire type
136                     Value::ByValPair(..) |
137                     Value::ByVal(_) if offset.bytes() == 0 && field.size == base_layout.size => Ok(Some(base)),
138                     // split fat pointers, 2 element tuples, ...
139                     Value::ByValPair(a, b) if base_layout.fields.count() == 2 => {
140                         let val = [a, b][field_index];
141                         Ok(Some(Value::ByVal(val)))
142                     },
143                     _ => Ok(None),
144                 }
145             },
146             // The NullablePointer cases should work fine, need to take care for normal enums
147             Downcast(..) |
148             Subslice { .. } |
149             // reading index 0 or index 1 from a ByVal or ByVal pair could be optimized
150             ConstantIndex { .. } | Index(_) |
151             // No way to optimize this projection any better than the normal place path
152             Deref => Ok(None),
153         }
154     }
155
156     /// Returns a value and (in case of a ByRef) if we are supposed to use aligned accesses.
157     pub(super) fn eval_and_read_place(
158         &mut self,
159         place: &mir::Place<'tcx>,
160     ) -> EvalResult<'tcx, Value> {
161         // Shortcut for things like accessing a fat pointer's field,
162         // which would otherwise (in the `eval_place` path) require moving a `ByValPair` to memory
163         // and returning an `Place::Ptr` to it
164         if let Some(val) = self.try_read_place(place)? {
165             return Ok(val);
166         }
167         let place = self.eval_place(place)?;
168         self.read_place(place)
169     }
170
171     pub fn read_place(&self, place: Place) -> EvalResult<'tcx, Value> {
172         match place {
173             Place::Ptr { ptr, align, extra } => {
174                 assert_eq!(extra, PlaceExtra::None);
175                 Ok(Value::ByRef(ptr, align))
176             }
177             Place::Local { frame, local } => self.stack[frame].get_local(local),
178         }
179     }
180
181     pub fn eval_place(&mut self, mir_place: &mir::Place<'tcx>) -> EvalResult<'tcx, Place> {
182         use rustc::mir::Place::*;
183         let place = match *mir_place {
184             Local(mir::RETURN_PLACE) => self.frame().return_place,
185             Local(local) => Place::Local {
186                 frame: self.cur_frame(),
187                 local,
188             },
189
190             Static(ref static_) => {
191                 let instance = ty::Instance::mono(self.tcx, static_.def_id);
192                 let gid = GlobalId {
193                     instance,
194                     promoted: None,
195                 };
196                 let layout = self.layout_of(self.place_ty(mir_place))?;
197                 let alloc = self.tcx.interpret_interner.borrow().get_cached(gid).expect("uncached global");
198                 Place::Ptr {
199                     ptr: MemoryPointer::new(alloc, 0).into(),
200                     align: layout.align,
201                     extra: PlaceExtra::None,
202                 }
203             }
204
205             Projection(ref proj) => {
206                 let ty = self.place_ty(&proj.base);
207                 let place = self.eval_place(&proj.base)?;
208                 return self.eval_place_projection(place, ty, &proj.elem);
209             }
210         };
211
212         if log_enabled!(::log::LogLevel::Trace) {
213             self.dump_local(place);
214         }
215
216         Ok(place)
217     }
218
219     pub fn place_field(
220         &mut self,
221         base: Place,
222         field: mir::Field,
223         mut base_layout: TyLayout<'tcx>,
224     ) -> EvalResult<'tcx, (Place, TyLayout<'tcx>)> {
225         match base {
226             Place::Ptr { extra: PlaceExtra::DowncastVariant(variant_index), .. } => {
227                 base_layout = base_layout.for_variant(&self, variant_index);
228             }
229             _ => {}
230         }
231         let field_index = field.index();
232         let field = base_layout.field(&self, field_index)?;
233         let offset = base_layout.fields.offset(field_index);
234
235         // Do not allocate in trivial cases
236         let (base_ptr, base_align, base_extra) = match base {
237             Place::Ptr { ptr, align, extra } => (ptr, align, extra),
238             Place::Local { frame, local } => {
239                 match (&self.stack[frame].get_local(local)?, &base_layout.abi) {
240                     // in case the field covers the entire type, just return the value
241                     (&Value::ByVal(_), &layout::Abi::Scalar(_)) |
242                     (&Value::ByValPair(..), &layout::Abi::ScalarPair(..))
243                         if offset.bytes() == 0 && field.size == base_layout.size =>
244                     {
245                         return Ok((base, field));
246                     }
247                     _ => self.force_allocation(base)?.to_ptr_align_extra(),
248                 }
249             }
250         };
251
252         let offset = match base_extra {
253             PlaceExtra::Vtable(tab) => {
254                 let (_, align) = self.size_and_align_of_dst(
255                     base_layout.ty,
256                     base_ptr.to_value_with_vtable(tab),
257                 )?;
258                 offset.abi_align(align).bytes()
259             }
260             _ => offset.bytes(),
261         };
262
263         let ptr = base_ptr.offset(offset, &self)?;
264         let align = base_align.min(base_layout.align).min(field.align);
265         let extra = if !field.is_unsized() {
266             PlaceExtra::None
267         } else {
268             match base_extra {
269                 PlaceExtra::None => bug!("expected fat pointer"),
270                 PlaceExtra::DowncastVariant(..) => {
271                     bug!("Rust doesn't support unsized fields in enum variants")
272                 }
273                 PlaceExtra::Vtable(_) |
274                 PlaceExtra::Length(_) => {}
275             }
276             base_extra
277         };
278
279         Ok((Place::Ptr { ptr, align, extra }, field))
280     }
281
282     pub fn val_to_place(&self, val: Value, ty: Ty<'tcx>) -> EvalResult<'tcx, Place> {
283         let layout = self.layout_of(ty)?;
284         Ok(match self.tcx.struct_tail(ty).sty {
285             ty::TyDynamic(..) => {
286                 let (ptr, vtable) = self.into_ptr_vtable_pair(val)?;
287                 Place::Ptr {
288                     ptr,
289                     align: layout.align,
290                     extra: PlaceExtra::Vtable(vtable),
291                 }
292             }
293             ty::TyStr | ty::TySlice(_) => {
294                 let (ptr, len) = self.into_slice(val)?;
295                 Place::Ptr {
296                     ptr,
297                     align: layout.align,
298                     extra: PlaceExtra::Length(len),
299                 }
300             }
301             _ => Place::from_primval_ptr(self.into_ptr(val)?, layout.align),
302         })
303     }
304
305     pub fn place_index(
306         &mut self,
307         base: Place,
308         outer_ty: Ty<'tcx>,
309         n: u64,
310     ) -> EvalResult<'tcx, Place> {
311         // Taking the outer type here may seem odd; it's needed because for array types, the outer type gives away the length.
312         let base = self.force_allocation(base)?;
313         let (base_ptr, align) = base.to_ptr_align();
314
315         let (elem_ty, len) = base.elem_ty_and_len(outer_ty);
316         let elem_size = self.layout_of(elem_ty)?.size.bytes();
317         assert!(
318             n < len,
319             "Tried to access element {} of array/slice with length {}",
320             n,
321             len
322         );
323         let ptr = base_ptr.offset(n * elem_size, &*self)?;
324         Ok(Place::Ptr {
325             ptr,
326             align,
327             extra: PlaceExtra::None,
328         })
329     }
330
331     pub(super) fn place_downcast(
332         &mut self,
333         base: Place,
334         variant: usize,
335     ) -> EvalResult<'tcx, Place> {
336         // FIXME(solson)
337         let base = self.force_allocation(base)?;
338         let (ptr, align) = base.to_ptr_align();
339         let extra = PlaceExtra::DowncastVariant(variant);
340         Ok(Place::Ptr { ptr, align, extra })
341     }
342
343     pub fn eval_place_projection(
344         &mut self,
345         base: Place,
346         base_ty: Ty<'tcx>,
347         proj_elem: &mir::ProjectionElem<'tcx, mir::Local, Ty<'tcx>>,
348     ) -> EvalResult<'tcx, Place> {
349         use rustc::mir::ProjectionElem::*;
350         match *proj_elem {
351             Field(field, _) => {
352                 let layout = self.layout_of(base_ty)?;
353                 Ok(self.place_field(base, field, layout)?.0)
354             }
355
356             Downcast(_, variant) => {
357                 self.place_downcast(base, variant)
358             }
359
360             Deref => {
361                 let val = self.read_place(base)?;
362
363                 let pointee_type = match base_ty.sty {
364                     ty::TyRawPtr(ref tam) |
365                     ty::TyRef(_, ref tam) => tam.ty,
366                     ty::TyAdt(def, _) if def.is_box() => base_ty.boxed_ty(),
367                     _ => bug!("can only deref pointer types"),
368                 };
369
370                 trace!("deref to {} on {:?}", pointee_type, val);
371
372                 self.val_to_place(val, pointee_type)
373             }
374
375             Index(local) => {
376                 let value = self.frame().get_local(local)?;
377                 let ty = self.tcx.types.usize;
378                 let n = self.value_to_primval(ValTy { value, ty })?.to_u64()?;
379                 self.place_index(base, base_ty, n)
380             }
381
382             ConstantIndex {
383                 offset,
384                 min_length,
385                 from_end,
386             } => {
387                 // FIXME(solson)
388                 let base = self.force_allocation(base)?;
389                 let (base_ptr, align) = base.to_ptr_align();
390
391                 let (elem_ty, n) = base.elem_ty_and_len(base_ty);
392                 let elem_size = self.layout_of(elem_ty)?.size.bytes();
393                 assert!(n >= min_length as u64);
394
395                 let index = if from_end {
396                     n - u64::from(offset)
397                 } else {
398                     u64::from(offset)
399                 };
400
401                 let ptr = base_ptr.offset(index * elem_size, &self)?;
402                 Ok(Place::Ptr { ptr, align, extra: PlaceExtra::None })
403             }
404
405             Subslice { from, to } => {
406                 // FIXME(solson)
407                 let base = self.force_allocation(base)?;
408                 let (base_ptr, align) = base.to_ptr_align();
409
410                 let (elem_ty, n) = base.elem_ty_and_len(base_ty);
411                 let elem_size = self.layout_of(elem_ty)?.size.bytes();
412                 assert!(u64::from(from) <= n - u64::from(to));
413                 let ptr = base_ptr.offset(u64::from(from) * elem_size, &self)?;
414                 // sublicing arrays produces arrays
415                 let extra = if self.type_is_sized(base_ty) {
416                     PlaceExtra::None
417                 } else {
418                     PlaceExtra::Length(n - u64::from(to) - u64::from(from))
419                 };
420                 Ok(Place::Ptr { ptr, align, extra })
421             }
422         }
423     }
424
425     pub fn place_ty(&self, place: &mir::Place<'tcx>) -> Ty<'tcx> {
426         self.monomorphize(
427             place.ty(self.mir(), self.tcx).to_ty(self.tcx),
428             self.substs(),
429         )
430     }
431 }