]> git.lizzy.rs Git - rust.git/blob - src/stacked_borrows.rs
make writes act stack-like
[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     /// We sometimes push into the middle but never remove from the middle.
74     /// The same tag may occur multiple times, e.g. from a two-phase borrow.
75     /// Invariants:
76     /// * Above a `SharedReadOnly` there can only be more `SharedReadOnly`.
77     borrows: Vec<Item>,
78 }
79
80
81 /// Extra per-allocation state.
82 #[derive(Clone, Debug)]
83 pub struct Stacks {
84     // Even reading memory can have effects on the stack, so we need a `RefCell` here.
85     stacks: RefCell<RangeMap<Stack>>,
86     // Pointer to global state
87     global: MemoryState,
88 }
89
90 /// Extra global state, available to the memory access hooks.
91 #[derive(Debug)]
92 pub struct GlobalState {
93     next_ptr_id: PtrId,
94     next_call_id: CallId,
95     active_calls: HashSet<CallId>,
96 }
97 pub type MemoryState = Rc<RefCell<GlobalState>>;
98
99 /// Indicates which kind of access is being performed.
100 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
101 pub enum AccessKind {
102     Read,
103     Write,
104 }
105
106 impl fmt::Display for AccessKind {
107     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108         match self {
109             AccessKind::Read => write!(f, "read"),
110             AccessKind::Write => write!(f, "write"),
111         }
112     }
113 }
114
115 /// Indicates which kind of reference is being created.
116 /// Used by high-level `reborrow` to compute which permissions to grant to the
117 /// new pointer.
118 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
119 pub enum RefKind {
120     /// `&mut` and `Box`.
121     Unique,
122     /// `&` with or without interior mutability.
123     Shared,
124     /// `*mut`/`*const` (raw pointers).
125     Raw { mutable: bool },
126 }
127
128 impl fmt::Display for RefKind {
129     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
130         match self {
131             RefKind::Unique => write!(f, "unique"),
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 /// Core relations on `Permission` define which accesses are allowed:
198 /// On every access, we try to find a *granting* item, and then we remove all
199 /// *incompatible* items above it.
200 impl Permission {
201     /// This defines for a given permission, whether it permits the given kind of access.
202     fn grants(self, access: AccessKind) -> bool {
203         match (self, access) {
204             // Unique and SharedReadWrite allow any kind of access.
205             (Permission::Unique, _) |
206             (Permission::SharedReadWrite, _) =>
207                 true,
208             // SharedReadOnly only permits read access.
209             (Permission::SharedReadOnly, AccessKind::Read) =>
210                 true,
211             (Permission::SharedReadOnly, AccessKind::Write) =>
212                 false,
213         }
214     }
215
216     /// This defines for a given permission, which other permissions it can tolerate "above" itself
217     /// for which kinds of accesses.
218     /// If true, then `other` is allowed to remain on top of `self` when `access` happens.
219     fn compatible_with(self, access: AccessKind, other: Permission) -> bool {
220         use self::Permission::*;
221
222         match (self, access, other) {
223             // Some cases are impossible.
224             (SharedReadOnly, _, SharedReadWrite) |
225             (SharedReadOnly, _, Unique) =>
226                 bug!("There can never be a SharedReadWrite or a Unique on top of a SharedReadOnly"),
227             // When `other` is `SharedReadOnly`, that is NEVER compatible with
228             // write accesses.
229             // This makes sure read-only pointers become invalid on write accesses (ensures F2a).
230             (_, AccessKind::Write, SharedReadOnly) =>
231                 false,
232             // When `other` is `Unique`, that is compatible with nothing.
233             // This makes sure unique pointers become invalid on incompatible accesses (ensures U2).
234             (_, _, Unique) =>
235                 false,
236             // When we are unique and this is a write/dealloc, we tolerate nothing.
237             // This makes sure we re-assert uniqueness ("being on top") on write accesses.
238             // (This is particularily important such that when a new mutable ref gets created, it gets
239             // pushed onto the right item -- this behaves like a write and we assert uniqueness of the
240             // pointer from which this comes, *if* it was a unique pointer.)
241             (Unique, AccessKind::Write, _) =>
242                 false,
243             // `SharedReadWrite` items can tolerate any other akin items for any kind of access.
244             (SharedReadWrite, _, SharedReadWrite) =>
245                 true,
246             // Any item can tolerate read accesses for shared items.
247             // This includes unique items!  Reads from unique pointers do not invalidate
248             // other pointers.
249             (_, AccessKind::Read, SharedReadWrite) |
250             (_, AccessKind::Read, SharedReadOnly) =>
251                 true,
252             // That's it.
253         }
254     }
255 }
256
257 /// Core per-location operations: access, dealloc, reborrow.
258 impl<'tcx> Stack {
259     /// Find the item granting the given kind of access to the given tag, and where
260     /// *the first incompatible item above it* is on the stack.
261     fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<(Permission, usize)> {
262         let (perm, idx) = self.borrows.iter()
263             .enumerate() // we also need to know *where* in the stack
264             .rev() // search top-to-bottom
265             // Return permission of first item that grants access.
266             // We require a permission with the right tag, ensuring U3 and F3.
267             .find_map(|(idx, item)|
268                 if item.perm.grants(access) && tag == item.tag {
269                     Some((item.perm, idx))
270                 } else {
271                     None
272                 }
273             )?;
274
275         let mut first_incompatible_idx = idx+1;
276         while let Some(item) = self.borrows.get(first_incompatible_idx) {
277             if perm.compatible_with(access, item.perm) {
278                 // Keep this, check next.
279                 first_incompatible_idx += 1;
280             } else {
281                 // Found it!
282                 break;
283             }
284         }
285         return Some((perm, first_incompatible_idx));
286     }
287
288     /// Test if a memory `access` using pointer tagged `tag` is granted.
289     /// If yes, return the index of the item that granted it.
290     fn access(
291         &mut self,
292         access: AccessKind,
293         tag: Tag,
294         global: &GlobalState,
295     ) -> EvalResult<'tcx> {
296         // Two main steps: Find granting item, remove all incompatible items above.
297
298         // Step 1: Find granting item.
299         let (granting_perm, first_incompatible_idx) = self.find_granting(access, tag)
300             .ok_or_else(|| InterpError::MachineError(format!(
301                 "no item granting {} access to tag {} found in borrow stack",
302                 access, tag,
303             )))?;
304
305         // Step 2: Remove everything incompatible above them.  Make sure we do not remove protected
306         // items.
307         // For writes, this is a simple stack. For reads, however, it is not:
308         // in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement would pop the `Unique`
309         // from the reborrow of the first statement, and subsequently also pop the `SharedReadWrite` for `raw`.
310         // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
311         // reference and use that.
312         {
313             // Implemented with indices because there does not seem to be a nice iterator and range-based
314             // API for this.
315             let mut cur = first_incompatible_idx;
316             while let Some(item) = self.borrows.get(cur) {
317                 // If this is a read, we double-check if we really want to kill this.
318                 if access == AccessKind::Read && granting_perm.compatible_with(access, item.perm) {
319                     // Keep this, check next.
320                     cur += 1;
321                 } else {
322                     // Aha! This is a bad one, remove it, and make sure it is not protected.
323                     let item = self.borrows.remove(cur);
324                     if let Some(call) = item.protector {
325                         if global.is_active(call) {
326                             return err!(MachineError(format!(
327                                 "not granting {} access to tag {} because incompatible item {} is protected",
328                                 access, tag, item
329                             )));
330                         }
331                     }
332                     trace!("access: removing item {}", item);
333                 }
334             }
335         }
336
337         // Done.
338         Ok(())
339     }
340
341     /// Deallocate a location: Like a write access, but also there must be no
342     /// active protectors at all.
343     fn dealloc(
344         &mut self,
345         tag: Tag,
346         global: &GlobalState,
347     ) -> EvalResult<'tcx> {
348         // Step 1: Find granting item.
349         self.find_granting(AccessKind::Write, tag)
350             .ok_or_else(|| InterpError::MachineError(format!(
351                 "no item granting write access for deallocation to tag {} found in borrow stack",
352                 tag,
353             )))?;
354
355         // We must make sure there are no protected items remaining on the stack.
356         // Also clear the stack, no more accesses are possible.
357         for item in self.borrows.drain(..) {
358             if let Some(call) = item.protector {
359                 if global.is_active(call) {
360                     return err!(MachineError(format!(
361                         "deallocating with active protector ({})", call
362                     )))
363                 }
364             }
365         }
366
367         Ok(())
368     }
369
370     /// `reborrow` helper function: test that the stack invariants are still maintained.
371     fn test_invariants(&self) {
372         let mut saw_shared_read_only = false;
373         for item in self.borrows.iter() {
374             match item.perm {
375                 Permission::SharedReadOnly => {
376                     saw_shared_read_only = true;
377                 }
378                 // Otherwise, if we saw one before, that's a bug.
379                 perm if saw_shared_read_only => {
380                     bug!("Found {:?} on top of a SharedReadOnly!", perm);
381                 }
382                 _ => {}
383             }
384         }
385     }
386
387     /// Derived a new pointer from one with the given tag.
388     /// `weak` controls whether this operation is weak or strong: weak granting does not act as
389     /// an access, and they add the new item directly on top of the one it is derived
390     /// from instead of all the way at the top of the stack.
391     fn grant(
392         &mut self,
393         derived_from: Tag,
394         weak: bool,
395         new: Item,
396         global: &GlobalState,
397     ) -> EvalResult<'tcx> {
398         // Figure out which access `perm` corresponds to.
399         let access = if new.perm.grants(AccessKind::Write) {
400             AccessKind::Write
401         } else {
402             AccessKind::Read
403         };
404         // Now we figure out which item grants our parent (`derived_from`) this kind of access.
405         // We use that to determine where to put the new item.
406         let (_, first_incompatible_idx) = self.find_granting(access, derived_from)
407             .ok_or_else(|| InterpError::MachineError(format!(
408                 "no item to reborrow for {:?} from tag {} found in borrow stack", new.perm, derived_from,
409             )))?;
410
411         // Compute where to put the new item.
412         // Either way, we ensure that we insert the new item in a way that between
413         // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
414         let new_idx = if weak {
415             // A weak SharedReadOnly reborrow might be added below other items, violating the
416             // invariant that only SharedReadOnly can sit on top of SharedReadOnly.
417             assert!(new.perm != Permission::SharedReadOnly, "Weak SharedReadOnly reborrows don't work");
418             // A very liberal reborrow because the new pointer does not expect any kind of aliasing guarantee.
419             // Just insert new permission as child of old permission, and maintain everything else.
420             // This inserts "as far down as possible", which is good because it makes this pointer as
421             // long-lived as possible *and* we want all the items that are incompatible with this
422             // to actually get removed from the stack.  If we pushed a `SharedReadWrite` on top of
423             // a `SharedReadOnly`, we'd violate the invariant that `SaredReadOnly` are at the top
424             // and we'd allow write access without invalidating frozen shared references!
425             // This ensures F2b for `SharedReadWrite` by adding the new item below any
426             // potentially existing `SharedReadOnly`.
427             first_incompatible_idx
428         } else {
429             // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
430             // Here, creating a reference actually counts as an access, and pops incompatible
431             // stuff off the stack.
432             // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
433             self.access(access, derived_from, global)?;
434             if access == AccessKind::Write {
435                 // For write accesses, the position is the same as what it would have been weakly!
436                 assert_eq!(first_incompatible_idx, self.borrows.len());
437             }
438
439             // We insert "as far up as possible": We know only compatible items are remaining
440             // on top of `derived_from`, and we want the new item at the top so that we
441             // get the strongest possible guarantees.
442             // This ensures U1 and F1.
443             self.borrows.len()
444         };
445
446         // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
447         if self.borrows[new_idx-1] == new || self.borrows.get(new_idx) == Some(&new) {
448             // Optimization applies, done.
449             trace!("reborrow: avoiding adding redundant item {}", new);
450         } else {
451             trace!("reborrow: adding item {}", new);
452             self.borrows.insert(new_idx, new);
453         }
454
455         // Make sure that after all this, the stack's invariant is still maintained.
456         if cfg!(debug_assertions) {
457             self.test_invariants();
458         }
459
460         Ok(())
461     }
462 }
463 // # Stacked Borrows Core End
464
465 /// Map per-stack operations to higher-level per-location-range operations.
466 impl<'tcx> Stacks {
467     /// Creates new stack with initial tag.
468     pub(crate) fn new(
469         size: Size,
470         tag: Tag,
471         extra: MemoryState,
472     ) -> Self {
473         let item = Item { perm: Permission::Unique, tag, protector: None };
474         let stack = Stack {
475             borrows: vec![item],
476         };
477         Stacks {
478             stacks: RefCell::new(RangeMap::new(size, stack)),
479             global: extra,
480         }
481     }
482
483     /// Call `f` on every stack in the range.
484     fn for_each(
485         &self,
486         ptr: Pointer<Tag>,
487         size: Size,
488         f: impl Fn(&mut Stack, &GlobalState) -> EvalResult<'tcx>,
489     ) -> EvalResult<'tcx> {
490         let global = self.global.borrow();
491         let mut stacks = self.stacks.borrow_mut();
492         for stack in stacks.iter_mut(ptr.offset, size) {
493             f(stack, &*global)?;
494         }
495         Ok(())
496     }
497 }
498
499 /// Glue code to connect with Miri Machine Hooks
500 impl Stacks {
501     pub fn new_allocation(
502         size: Size,
503         extra: &MemoryState,
504         kind: MemoryKind<MiriMemoryKind>,
505     ) -> (Self, Tag) {
506         let tag = match kind {
507             MemoryKind::Stack => {
508                 // New unique borrow. This `Uniq` is not accessible by the program,
509                 // so it will only ever be used when using the local directly (i.e.,
510                 // not through a pointer). That is, whenever we directly use a local, this will pop
511                 // everything else off the stack, invalidating all previous pointers,
512                 // and in particular, *all* raw pointers. This subsumes the explicit
513                 // `reset` which the blog post [1] says to perform when accessing a local.
514                 //
515                 // [1]: <https://www.ralfj.de/blog/2018/08/07/stacked-borrows.html>
516                 Tag::Tagged(extra.borrow_mut().new_ptr())
517             }
518             _ => {
519                 Tag::Untagged
520             }
521         };
522         let stack = Stacks::new(size, tag, Rc::clone(extra));
523         (stack, tag)
524     }
525 }
526
527 impl AllocationExtra<Tag> for Stacks {
528     #[inline(always)]
529     fn memory_read<'tcx>(
530         alloc: &Allocation<Tag, Stacks>,
531         ptr: Pointer<Tag>,
532         size: Size,
533     ) -> EvalResult<'tcx> {
534         trace!("read access with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
535         alloc.extra.for_each(ptr, size, |stack, global| {
536             stack.access(AccessKind::Read, ptr.tag, global)?;
537             Ok(())
538         })
539     }
540
541     #[inline(always)]
542     fn memory_written<'tcx>(
543         alloc: &mut Allocation<Tag, Stacks>,
544         ptr: Pointer<Tag>,
545         size: Size,
546     ) -> EvalResult<'tcx> {
547         trace!("write access with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
548         alloc.extra.for_each(ptr, size, |stack, global| {
549             stack.access(AccessKind::Write, ptr.tag, global)?;
550             Ok(())
551         })
552     }
553
554     #[inline(always)]
555     fn memory_deallocated<'tcx>(
556         alloc: &mut Allocation<Tag, Stacks>,
557         ptr: Pointer<Tag>,
558         size: Size,
559     ) -> EvalResult<'tcx> {
560         trace!("deallocation with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
561         alloc.extra.for_each(ptr, size, |stack, global| {
562             stack.dealloc(ptr.tag, global)
563         })
564     }
565 }
566
567 /// Retagging/reborrowing.  There is some policy in here, such as which permissions
568 /// to grant for which references, when to add protectors, and how to realize two-phase
569 /// borrows in terms of the primitives above.
570 impl<'a, 'mir, 'tcx> EvalContextPrivExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
571 trait EvalContextPrivExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
572     fn reborrow(
573         &mut self,
574         place: MPlaceTy<'tcx, Tag>,
575         size: Size,
576         kind: RefKind,
577         new_tag: Tag,
578         force_weak: bool,
579         protect: bool,
580     ) -> EvalResult<'tcx> {
581         let this = self.eval_context_mut();
582         let protector = if protect { Some(this.frame().extra) } else { None };
583         let ptr = place.ptr.to_ptr()?;
584         trace!("reborrow: {:?} reference {} derived from {} (pointee {}): {:?}, size {}",
585             kind, new_tag, ptr.tag, place.layout.ty, ptr, size.bytes());
586
587         // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
588         let alloc = this.memory().get(ptr.alloc_id)?;
589         alloc.check_bounds(this, ptr, size)?;
590         // Update the stacks.
591         // Make sure that raw pointers and mutable shared references are reborrowed "weak":
592         // There could be existing unique pointers reborrowed from them that should remain valid!
593         let perm = match kind {
594             RefKind::Unique => Permission::Unique,
595             RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
596             RefKind::Shared | RefKind::Raw { mutable: false } => {
597                 // Shared references and *const are a whole different kind of game, the
598                 // permission is not uniform across the entire range!
599                 // We need a frozen-sensitive reborrow.
600                 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
601                     // We are only ever `SharedReadOnly` inside the frozen bits.
602                     let perm = if frozen { Permission::SharedReadOnly } else { Permission::SharedReadWrite };
603                     let weak = perm == Permission::SharedReadWrite;
604                     let item = Item { perm, tag: new_tag, protector };
605                     alloc.extra.for_each(cur_ptr, size, |stack, global| {
606                         stack.grant(cur_ptr.tag, force_weak || weak, item, global)
607                     })
608                 });
609             }
610         };
611         debug_assert_ne!(perm, Permission::SharedReadOnly, "SharedReadOnly must be used frozen-sensitive");
612         let weak = perm == Permission::SharedReadWrite;
613         let item = Item { perm, tag: new_tag, protector };
614         alloc.extra.for_each(ptr, size, |stack, global| {
615             stack.grant(ptr.tag, force_weak || weak, item, global)
616         })
617     }
618
619     /// Retags an indidual pointer, returning the retagged version.
620     /// `mutbl` can be `None` to make this a raw pointer.
621     fn retag_reference(
622         &mut self,
623         val: ImmTy<'tcx, Tag>,
624         kind: RefKind,
625         protect: bool,
626         two_phase: bool,
627     ) -> EvalResult<'tcx, Immediate<Tag>> {
628         let this = self.eval_context_mut();
629         // We want a place for where the ptr *points to*, so we get one.
630         let place = this.ref_to_mplace(val)?;
631         let size = this.size_and_align_of_mplace(place)?
632             .map(|(size, _)| size)
633             .unwrap_or_else(|| place.layout.size);
634         if size == Size::ZERO {
635             // Nothing to do for ZSTs.
636             return Ok(*val);
637         }
638
639         // Compute new borrow.
640         let new_tag = match kind {
641             RefKind::Raw { .. } => Tag::Untagged,
642             _ => Tag::Tagged(this.memory().extra.borrow_mut().new_ptr()),
643         };
644
645         // Reborrow.
646         // TODO: With `two_phase == true`, this performs a weak reborrow for a `Unique`. That
647         // can lead to some possibly surprising effects, if the parent permission is
648         // `SharedReadWrite` then we now have a `Unique` in the middle of them, which "splits"
649         // them in terms of what remains valid when the `Unique` gets used.  Is that really
650         // what we want?
651         this.reborrow(place, size, kind, new_tag, /*force_weak:*/ two_phase, protect)?;
652         let new_place = place.replace_tag(new_tag);
653         // Handle two-phase borrows.
654         if two_phase {
655             assert!(kind == RefKind::Unique, "two-phase shared borrows make no sense");
656             // Grant read access *to the parent pointer* with the old tag *derived from the new tag* (`new_place`). 
657             // This means the old pointer has multiple items in the stack now, which otherwise cannot happen
658             // for unique references -- but in this case it precisely expresses the semantics we want.
659             let old_tag = place.ptr.to_ptr().unwrap().tag;
660             this.reborrow(new_place, size, RefKind::Shared, old_tag, /*force_weak:*/ false, /*protect:*/ false)?;
661         }
662
663         // Return new pointer.
664         Ok(new_place.to_ref())
665     }
666 }
667
668 impl<'a, 'mir, 'tcx> EvalContextExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
669 pub trait EvalContextExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
670     fn retag(
671         &mut self,
672         kind: RetagKind,
673         place: PlaceTy<'tcx, Tag>
674     ) -> EvalResult<'tcx> {
675         let this = self.eval_context_mut();
676         // Determine mutability and whether to add a protector.
677         // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
678         // making it useless.
679         fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
680             match ty.sty {
681                 // References are simple.
682                 ty::Ref(_, _, MutMutable) =>
683                     Some((RefKind::Unique, kind == RetagKind::FnEntry)),
684                 ty::Ref(_, _, MutImmutable) =>
685                     Some((RefKind::Shared, kind == RetagKind::FnEntry)),
686                 // Raw pointers need to be enabled.
687                 ty::RawPtr(tym) if kind == RetagKind::Raw =>
688                     Some((RefKind::Raw { mutable: tym.mutbl == MutMutable }, false)),
689                 // Boxes do not get a protector: protectors reflect that references outlive the call
690                 // they were passed in to; that's just not the case for boxes.
691                 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique, false)),
692                 _ => None,
693             }
694         }
695
696         // We need a visitor to visit all references. However, that requires
697         // a `MemPlace`, so we have a fast path for reference types that
698         // avoids allocating.
699         if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
700             // Fast path.
701             let val = this.read_immediate(this.place_to_op(place)?)?;
702             let val = this.retag_reference(val, mutbl, protector, kind == RetagKind::TwoPhase)?;
703             this.write_immediate(val, place)?;
704             return Ok(());
705         }
706         let place = this.force_allocation(place)?;
707
708         let mut visitor = RetagVisitor { ecx: this, kind };
709         visitor.visit_value(place)?;
710
711         // The actual visitor.
712         struct RetagVisitor<'ecx, 'a, 'mir, 'tcx> {
713             ecx: &'ecx mut MiriEvalContext<'a, 'mir, 'tcx>,
714             kind: RetagKind,
715         }
716         impl<'ecx, 'a, 'mir, 'tcx>
717             MutValueVisitor<'a, 'mir, 'tcx, Evaluator<'tcx>>
718         for
719             RetagVisitor<'ecx, 'a, 'mir, 'tcx>
720         {
721             type V = MPlaceTy<'tcx, Tag>;
722
723             #[inline(always)]
724             fn ecx(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
725                 &mut self.ecx
726             }
727
728             // Primitives of reference type, that is the one thing we are interested in.
729             fn visit_primitive(&mut self, place: MPlaceTy<'tcx, Tag>) -> EvalResult<'tcx>
730             {
731                 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
732                 // making it useless.
733                 if let Some((mutbl, protector)) = qualify(place.layout.ty, self.kind) {
734                     let val = self.ecx.read_immediate(place.into())?;
735                     let val = self.ecx.retag_reference(
736                         val,
737                         mutbl,
738                         protector,
739                         self.kind == RetagKind::TwoPhase
740                     )?;
741                     self.ecx.write_immediate(val, place.into())?;
742                 }
743                 Ok(())
744             }
745         }
746
747         Ok(())
748     }
749 }