]> git.lizzy.rs Git - rust.git/blob - src/stacked_borrows.rs
give up on two-phase borrows
[rust.git] / src / stacked_borrows.rs
1 use std::cell::RefCell;
2 use std::collections::HashSet;
3 use std::rc::Rc;
4 use std::fmt;
5 use std::num::NonZeroU64;
6
7 use rustc::ty::{self, layout::Size};
8 use rustc::hir::{MutMutable, MutImmutable};
9 use rustc::mir::RetagKind;
10
11 use crate::{
12     EvalResult, InterpError, MiriEvalContext, HelpersEvalContextExt, Evaluator, MutValueVisitor,
13     MemoryKind, MiriMemoryKind, RangeMap, Allocation, AllocationExtra,
14     Pointer, Immediate, ImmTy, PlaceTy, MPlaceTy,
15 };
16
17 pub type PtrId = NonZeroU64;
18 pub type CallId = NonZeroU64;
19
20 /// Tracking pointer provenance
21 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
22 pub enum Tag {
23     Tagged(PtrId),
24     Untagged,
25 }
26
27 impl fmt::Display for Tag {
28     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
29         match self {
30             Tag::Tagged(id) => write!(f, "{}", id),
31             Tag::Untagged => write!(f, "<untagged>"),
32         }
33     }
34 }
35
36 /// Indicates which permission is granted (by this item to some pointers)
37 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
38 pub enum Permission {
39     /// Grants unique mutable access.
40     Unique,
41     /// Grants shared mutable access.
42     SharedReadWrite,
43     /// Greants shared read-only access.
44     SharedReadOnly,
45 }
46
47 /// An item in the per-location borrow stack.
48 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
49 pub struct Item {
50     /// The permission this item grants.
51     perm: Permission,
52     /// The pointers the permission is granted to.
53     tag: Tag,
54     /// An optional protector, ensuring the item cannot get popped until `CallId` is over.
55     protector: Option<CallId>,
56 }
57
58 impl fmt::Display for Item {
59     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60         write!(f, "[{:?} for {}", self.perm, self.tag)?;
61         if let Some(call) = self.protector {
62             write!(f, " (call {})", call)?;
63         }
64         write!(f, "]")?;
65         Ok(())
66     }
67 }
68
69 /// Extra per-location state.
70 #[derive(Clone, Debug, PartialEq, Eq)]
71 pub struct Stack {
72     /// Used *mostly* as a stack; never empty.
73     /// Invariants:
74     /// * Above a `SharedReadOnly` there can only be more `SharedReadOnly`.
75     /// * Except for `Untagged`, no tag occurs in the stack more than once.
76     borrows: Vec<Item>,
77 }
78
79
80 /// Extra per-allocation state.
81 #[derive(Clone, Debug)]
82 pub struct Stacks {
83     // Even reading memory can have effects on the stack, so we need a `RefCell` here.
84     stacks: RefCell<RangeMap<Stack>>,
85     // Pointer to global state
86     global: MemoryState,
87 }
88
89 /// Extra global state, available to the memory access hooks.
90 #[derive(Debug)]
91 pub struct GlobalState {
92     next_ptr_id: PtrId,
93     next_call_id: CallId,
94     active_calls: HashSet<CallId>,
95 }
96 pub type MemoryState = Rc<RefCell<GlobalState>>;
97
98 /// Indicates which kind of access is being performed.
99 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
100 pub enum AccessKind {
101     Read,
102     Write,
103 }
104
105 impl fmt::Display for AccessKind {
106     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107         match self {
108             AccessKind::Read => write!(f, "read"),
109             AccessKind::Write => write!(f, "write"),
110         }
111     }
112 }
113
114 /// Indicates which kind of reference is being created.
115 /// Used by high-level `reborrow` to compute which permissions to grant to the
116 /// new pointer.
117 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
118 pub enum RefKind {
119     /// `&mut` and `Box`.
120     Unique { two_phase: bool },
121     /// `&` with or without interior mutability.
122     Shared,
123     /// `*mut`/`*const` (raw pointers).
124     Raw { mutable: bool },
125 }
126
127 impl fmt::Display for RefKind {
128     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129         match self {
130             RefKind::Unique { two_phase: false } => write!(f, "unique"),
131             RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
132             RefKind::Shared => write!(f, "shared"),
133             RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
134             RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
135         }
136     }
137 }
138
139 /// Utilities for initialization and ID generation
140 impl Default for GlobalState {
141     fn default() -> Self {
142         GlobalState {
143             next_ptr_id: NonZeroU64::new(1).unwrap(),
144             next_call_id: NonZeroU64::new(1).unwrap(),
145             active_calls: HashSet::default(),
146         }
147     }
148 }
149
150 impl GlobalState {
151     pub fn new_ptr(&mut self) -> PtrId {
152         let id = self.next_ptr_id;
153         self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
154         id
155     }
156
157     pub fn new_call(&mut self) -> CallId {
158         let id = self.next_call_id;
159         trace!("new_call: Assigning ID {}", id);
160         self.active_calls.insert(id);
161         self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
162         id
163     }
164
165     pub fn end_call(&mut self, id: CallId) {
166         assert!(self.active_calls.remove(&id));
167     }
168
169     fn is_active(&self, id: CallId) -> bool {
170         self.active_calls.contains(&id)
171     }
172 }
173
174 // # Stacked Borrows Core Begin
175
176 /// We need to make at least the following things true:
177 ///
178 /// U1: After creating a `Uniq`, it is at the top.
179 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
180 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
181 ///
182 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
183 /// F2: If a write access happens, it pops the `SharedReadOnly`.  This has three pieces:
184 ///     F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
185 ///          gets popped.
186 ///     F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
187 /// F3: If an access happens with an `&` outside `UnsafeCell`,
188 ///     it requires the `SharedReadOnly` to still be in the stack.
189
190 impl Default for Tag {
191     #[inline(always)]
192     fn default() -> Tag {
193         Tag::Untagged
194     }
195 }
196
197
198 /// Core relation on `Permission` to define which accesses are allowed
199 impl Permission {
200     /// This defines for a given permission, whether it permits the given kind of access.
201     fn grants(self, access: AccessKind) -> bool {
202         // All items grant read access, and except for SharedReadOnly they grant write access.
203         access == AccessKind::Read || self != Permission::SharedReadOnly
204     }
205 }
206
207 /// Core per-location operations: access, dealloc, reborrow.
208 impl<'tcx> Stack {
209     /// Find the item granting the given kind of access to the given tag, and return where
210     /// it is on the stack.
211     fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
212         self.borrows.iter()
213             .enumerate() // we also need to know *where* in the stack
214             .rev() // search top-to-bottom
215             // Return permission of first item that grants access.
216             // We require a permission with the right tag, ensuring U3 and F3.
217             .find_map(|(idx, item)|
218                 if tag == item.tag && item.perm.grants(access) {
219                     Some(idx)
220                 } else {
221                     None
222                 }
223             )
224     }
225
226     /// Find the first write-incompatible item above the given one -- 
227     /// i.e, find the heigh to which the stack will be truncated when writing to `granting`.
228     fn find_first_write_incompaible(&self, granting: usize) -> usize {
229         let perm = self.borrows[granting].perm;
230         match perm {
231             Permission::SharedReadOnly =>
232                 bug!("Cannot use SharedReadOnly for writing"),
233             Permission::Unique =>
234                 // On a write, everything above us is incompatible.
235                 granting+1,
236             Permission::SharedReadWrite => {
237                 // The SharedReadWrite *just* above us are compatible, to skip those.
238                 let mut idx = granting+1;
239                 while let Some(item) = self.borrows.get(idx) {
240                     if item.perm == Permission::SharedReadWrite {
241                         // Go on.
242                         idx += 1;
243                     } else {
244                         // Found first incompatible!
245                         break;
246                     }
247                 }
248                 idx
249             }
250         }
251     }
252
253     /// Remove the given item, enforcing barriers.
254     /// `tag` is just used for the error message.
255     fn remove(&mut self, idx: usize, tag: Option<Tag>, global: &GlobalState) -> EvalResult<'tcx> {
256         let item = self.borrows.remove(idx);
257         if let Some(call) = item.protector {
258             if global.is_active(call) {
259                 if let Some(tag) = tag {
260                     return err!(MachineError(format!(
261                         "not granting access to tag {} because incompatible item is protected: {}",
262                         tag, item
263                     )));
264                 } else {
265                     return err!(MachineError(format!(
266                         "deallocating while item is protected: {}", item
267                     )));
268                 }
269             }
270         }
271         trace!("access: removing item {}", item);
272         Ok(())
273     }
274
275     /// Test if a memory `access` using pointer tagged `tag` is granted.
276     /// If yes, return the index of the item that granted it.
277     fn access(
278         &mut self,
279         access: AccessKind,
280         tag: Tag,
281         global: &GlobalState,
282     ) -> EvalResult<'tcx> {
283         // Two main steps: Find granting item, remove incompatible items above.
284
285         // Step 1: Find granting item.
286         let granting_idx = self.find_granting(access, tag)
287             .ok_or_else(|| InterpError::MachineError(format!(
288                 "no item granting {} access to tag {} found in borrow stack",
289                 access, tag,
290             )))?;
291
292         // Step 2: Remove incompatible items above them.  Make sure we do not remove protected
293         // items.  Behavior differs for reads and writes.
294         if access == AccessKind::Write {
295             // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
296             // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
297             let first_incompatible_idx = self.find_first_write_incompaible(granting_idx);
298             for idx in (first_incompatible_idx..self.borrows.len()).rev() {
299                 self.remove(idx, Some(tag), global)?;
300             }
301         } else {
302             // On a read, remove all `Unique` above the granting item.  This ensures U2 for read accesses.
303             // The reason this is not following the stack discipline is that in
304             // `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
305             // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
306             // `SharedReadWrite` for `raw`.
307             // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
308             // reference and use that.
309             for idx in (granting_idx+1 .. self.borrows.len()).rev() {
310                 if self.borrows[idx].perm == Permission::Unique {
311                     self.remove(idx, Some(tag), global)?;
312                 }
313             }
314         }
315
316         // Done.
317         Ok(())
318     }
319
320     /// Deallocate a location: Like a write access, but also there must be no
321     /// active protectors at all because we will remove all items.
322     fn dealloc(
323         &mut self,
324         tag: Tag,
325         global: &GlobalState,
326     ) -> EvalResult<'tcx> {
327         // Step 1: Find granting item.
328         self.find_granting(AccessKind::Write, tag)
329             .ok_or_else(|| InterpError::MachineError(format!(
330                 "no item granting write access for deallocation to tag {} found in borrow stack",
331                 tag,
332             )))?;
333
334         // Step 2: Remove all items.  Also checks for protectors.
335         for idx in (0..self.borrows.len()).rev() {
336             self.remove(idx, None, global)?;
337         }
338
339         Ok(())
340     }
341
342     /// `reborrow` helper function: test that the stack invariants are still maintained.
343     fn test_invariants(&self) {
344         let mut saw_shared_read_only = false;
345         for item in self.borrows.iter() {
346             match item.perm {
347                 Permission::SharedReadOnly => {
348                     saw_shared_read_only = true;
349                 }
350                 // Otherwise, if we saw one before, that's a bug.
351                 perm if saw_shared_read_only => {
352                     bug!("Found {:?} on top of a SharedReadOnly!", perm);
353                 }
354                 _ => {}
355             }
356         }
357     }
358
359     /// Derived a new pointer from one with the given tag.
360     /// `weak` controls whether this operation is weak or strong: weak granting does not act as
361     /// an access, and they add the new item directly on top of the one it is derived
362     /// from instead of all the way at the top of the stack.
363     fn grant(
364         &mut self,
365         derived_from: Tag,
366         new: Item,
367         global: &GlobalState,
368     ) -> EvalResult<'tcx> {
369         // Figure out which access `perm` corresponds to.
370         let access = if new.perm.grants(AccessKind::Write) {
371             AccessKind::Write
372         } else {
373             AccessKind::Read
374         };
375         // Now we figure out which item grants our parent (`derived_from`) this kind of access.
376         // We use that to determine where to put the new item.
377         let granting_idx = self.find_granting(access, derived_from)
378             .ok_or_else(|| InterpError::MachineError(format!(
379                 "no item to reborrow for {:?} from tag {} found in borrow stack", new.perm, derived_from,
380             )))?;
381
382         // Compute where to put the new item.
383         // Either way, we ensure that we insert the new item in a way such that between
384         // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
385         let new_idx = if new.perm == Permission::SharedReadWrite {
386             assert!(access == AccessKind::Write, "this case only makes sense for stack-like accesses");
387             // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
388             // access.  Instead of popping the stack, we insert the item at the place the stack would
389             // be popped to (i.e., we insert it above all the write-compatible items).
390             // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
391             self.find_first_write_incompaible(granting_idx)
392         } else {
393             // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
394             // Here, creating a reference actually counts as an access.
395             // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
396             self.access(access, derived_from, global)?;
397
398             // We insert "as far up as possible": We know only compatible items are remaining
399             // on top of `derived_from`, and we want the new item at the top so that we
400             // get the strongest possible guarantees.
401             // This ensures U1 and F1.
402             self.borrows.len()
403         };
404
405         // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
406         if self.borrows[new_idx-1] == new || self.borrows.get(new_idx) == Some(&new) {
407             // Optimization applies, done.
408             trace!("reborrow: avoiding adding redundant item {}", new);
409         } else {
410             trace!("reborrow: adding item {}", new);
411             self.borrows.insert(new_idx, new);
412         }
413
414         // Make sure that after all this, the stack's invariant is still maintained.
415         if cfg!(debug_assertions) {
416             self.test_invariants();
417         }
418
419         Ok(())
420     }
421 }
422 // # Stacked Borrows Core End
423
424 /// Map per-stack operations to higher-level per-location-range operations.
425 impl<'tcx> Stacks {
426     /// Creates new stack with initial tag.
427     pub(crate) fn new(
428         size: Size,
429         tag: Tag,
430         extra: MemoryState,
431     ) -> Self {
432         let item = Item { perm: Permission::Unique, tag, protector: None };
433         let stack = Stack {
434             borrows: vec![item],
435         };
436         Stacks {
437             stacks: RefCell::new(RangeMap::new(size, stack)),
438             global: extra,
439         }
440     }
441
442     /// Call `f` on every stack in the range.
443     fn for_each(
444         &self,
445         ptr: Pointer<Tag>,
446         size: Size,
447         f: impl Fn(&mut Stack, &GlobalState) -> EvalResult<'tcx>,
448     ) -> EvalResult<'tcx> {
449         let global = self.global.borrow();
450         let mut stacks = self.stacks.borrow_mut();
451         for stack in stacks.iter_mut(ptr.offset, size) {
452             f(stack, &*global)?;
453         }
454         Ok(())
455     }
456 }
457
458 /// Glue code to connect with Miri Machine Hooks
459 impl Stacks {
460     pub fn new_allocation(
461         size: Size,
462         extra: &MemoryState,
463         kind: MemoryKind<MiriMemoryKind>,
464     ) -> (Self, Tag) {
465         let tag = match kind {
466             MemoryKind::Stack => {
467                 // New unique borrow. This `Uniq` is not accessible by the program,
468                 // so it will only ever be used when using the local directly (i.e.,
469                 // not through a pointer). That is, whenever we directly use a local, this will pop
470                 // everything else off the stack, invalidating all previous pointers,
471                 // and in particular, *all* raw pointers. This subsumes the explicit
472                 // `reset` which the blog post [1] says to perform when accessing a local.
473                 //
474                 // [1]: <https://www.ralfj.de/blog/2018/08/07/stacked-borrows.html>
475                 Tag::Tagged(extra.borrow_mut().new_ptr())
476             }
477             _ => {
478                 Tag::Untagged
479             }
480         };
481         let stack = Stacks::new(size, tag, Rc::clone(extra));
482         (stack, tag)
483     }
484 }
485
486 impl AllocationExtra<Tag> for Stacks {
487     #[inline(always)]
488     fn memory_read<'tcx>(
489         alloc: &Allocation<Tag, Stacks>,
490         ptr: Pointer<Tag>,
491         size: Size,
492     ) -> EvalResult<'tcx> {
493         trace!("read access with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
494         alloc.extra.for_each(ptr, size, |stack, global| {
495             stack.access(AccessKind::Read, ptr.tag, global)?;
496             Ok(())
497         })
498     }
499
500     #[inline(always)]
501     fn memory_written<'tcx>(
502         alloc: &mut Allocation<Tag, Stacks>,
503         ptr: Pointer<Tag>,
504         size: Size,
505     ) -> EvalResult<'tcx> {
506         trace!("write access with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
507         alloc.extra.for_each(ptr, size, |stack, global| {
508             stack.access(AccessKind::Write, ptr.tag, global)?;
509             Ok(())
510         })
511     }
512
513     #[inline(always)]
514     fn memory_deallocated<'tcx>(
515         alloc: &mut Allocation<Tag, Stacks>,
516         ptr: Pointer<Tag>,
517         size: Size,
518     ) -> EvalResult<'tcx> {
519         trace!("deallocation with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
520         alloc.extra.for_each(ptr, size, |stack, global| {
521             stack.dealloc(ptr.tag, global)
522         })
523     }
524 }
525
526 /// Retagging/reborrowing.  There is some policy in here, such as which permissions
527 /// to grant for which references, and when to add protectors.
528 impl<'a, 'mir, 'tcx> EvalContextPrivExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
529 trait EvalContextPrivExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
530     fn reborrow(
531         &mut self,
532         place: MPlaceTy<'tcx, Tag>,
533         size: Size,
534         kind: RefKind,
535         new_tag: Tag,
536         protect: bool,
537     ) -> EvalResult<'tcx> {
538         let this = self.eval_context_mut();
539         let protector = if protect { Some(this.frame().extra) } else { None };
540         let ptr = place.ptr.to_ptr()?;
541         trace!("reborrow: {:?} reference {} derived from {} (pointee {}): {:?}, size {}",
542             kind, new_tag, ptr.tag, place.layout.ty, ptr, size.bytes());
543
544         // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
545         let alloc = this.memory().get(ptr.alloc_id)?;
546         alloc.check_bounds(this, ptr, size)?;
547         // Update the stacks.
548         // Make sure that raw pointers and mutable shared references are reborrowed "weak":
549         // There could be existing unique pointers reborrowed from them that should remain valid!
550         let perm = match kind {
551             RefKind::Unique { two_phase: false } => Permission::Unique,
552             RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
553             RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
554             RefKind::Shared | RefKind::Raw { mutable: false } => {
555                 // Shared references and *const are a whole different kind of game, the
556                 // permission is not uniform across the entire range!
557                 // We need a frozen-sensitive reborrow.
558                 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
559                     // We are only ever `SharedReadOnly` inside the frozen bits.
560                     let perm = if frozen { Permission::SharedReadOnly } else { Permission::SharedReadWrite };
561                     let item = Item { perm, tag: new_tag, protector };
562                     alloc.extra.for_each(cur_ptr, size, |stack, global| {
563                         stack.grant(cur_ptr.tag, item, global)
564                     })
565                 });
566             }
567         };
568         let item = Item { perm, tag: new_tag, protector };
569         alloc.extra.for_each(ptr, size, |stack, global| {
570             stack.grant(ptr.tag, item, global)
571         })
572     }
573
574     /// Retags an indidual pointer, returning the retagged version.
575     /// `mutbl` can be `None` to make this a raw pointer.
576     fn retag_reference(
577         &mut self,
578         val: ImmTy<'tcx, Tag>,
579         kind: RefKind,
580         protect: bool,
581     ) -> EvalResult<'tcx, Immediate<Tag>> {
582         let this = self.eval_context_mut();
583         // We want a place for where the ptr *points to*, so we get one.
584         let place = this.ref_to_mplace(val)?;
585         let size = this.size_and_align_of_mplace(place)?
586             .map(|(size, _)| size)
587             .unwrap_or_else(|| place.layout.size);
588         if size == Size::ZERO {
589             // Nothing to do for ZSTs.
590             return Ok(*val);
591         }
592
593         // Compute new borrow.
594         let new_tag = match kind {
595             RefKind::Raw { .. } => Tag::Untagged,
596             _ => Tag::Tagged(this.memory().extra.borrow_mut().new_ptr()),
597         };
598
599         // Reborrow.
600         this.reborrow(place, size, kind, new_tag, protect)?;
601         let new_place = place.replace_tag(new_tag);
602
603         // Return new pointer.
604         Ok(new_place.to_ref())
605     }
606 }
607
608 impl<'a, 'mir, 'tcx> EvalContextExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
609 pub trait EvalContextExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
610     fn retag(
611         &mut self,
612         kind: RetagKind,
613         place: PlaceTy<'tcx, Tag>
614     ) -> EvalResult<'tcx> {
615         let this = self.eval_context_mut();
616         // Determine mutability and whether to add a protector.
617         // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
618         // making it useless.
619         fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
620             match ty.sty {
621                 // References are simple.
622                 ty::Ref(_, _, MutMutable) =>
623                     Some((RefKind::Unique { two_phase: kind == RetagKind::TwoPhase}, kind == RetagKind::FnEntry)),
624                 ty::Ref(_, _, MutImmutable) =>
625                     Some((RefKind::Shared, kind == RetagKind::FnEntry)),
626                 // Raw pointers need to be enabled.
627                 ty::RawPtr(tym) if kind == RetagKind::Raw =>
628                     Some((RefKind::Raw { mutable: tym.mutbl == MutMutable }, false)),
629                 // Boxes do not get a protector: protectors reflect that references outlive the call
630                 // they were passed in to; that's just not the case for boxes.
631                 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
632                 _ => None,
633             }
634         }
635
636         // We need a visitor to visit all references. However, that requires
637         // a `MemPlace`, so we have a fast path for reference types that
638         // avoids allocating.
639         if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
640             // Fast path.
641             let val = this.read_immediate(this.place_to_op(place)?)?;
642             let val = this.retag_reference(val, mutbl, protector)?;
643             this.write_immediate(val, place)?;
644             return Ok(());
645         }
646         let place = this.force_allocation(place)?;
647
648         let mut visitor = RetagVisitor { ecx: this, kind };
649         visitor.visit_value(place)?;
650
651         // The actual visitor.
652         struct RetagVisitor<'ecx, 'a, 'mir, 'tcx> {
653             ecx: &'ecx mut MiriEvalContext<'a, 'mir, 'tcx>,
654             kind: RetagKind,
655         }
656         impl<'ecx, 'a, 'mir, 'tcx>
657             MutValueVisitor<'a, 'mir, 'tcx, Evaluator<'tcx>>
658         for
659             RetagVisitor<'ecx, 'a, 'mir, 'tcx>
660         {
661             type V = MPlaceTy<'tcx, Tag>;
662
663             #[inline(always)]
664             fn ecx(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
665                 &mut self.ecx
666             }
667
668             // Primitives of reference type, that is the one thing we are interested in.
669             fn visit_primitive(&mut self, place: MPlaceTy<'tcx, Tag>) -> EvalResult<'tcx>
670             {
671                 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
672                 // making it useless.
673                 if let Some((mutbl, protector)) = qualify(place.layout.ty, self.kind) {
674                     let val = self.ecx.read_immediate(place.into())?;
675                     let val = self.ecx.retag_reference(
676                         val,
677                         mutbl,
678                         protector
679                     )?;
680                     self.ecx.write_immediate(val, place.into())?;
681                 }
682                 Ok(())
683             }
684         }
685
686         Ok(())
687     }
688 }