rustc_data_structures/
tagged_ptr.rs

1//! This module implements tagged pointers. In order to utilize the pointer
2//! packing, you must have a tag type implementing the [`Tag`] trait.
3//!
4//! We assert that the tag and the reference type is compatible at compile
5//! time.
6
7use std::fmt;
8use std::hash::{Hash, Hasher};
9use std::marker::PhantomData;
10use std::num::NonZero;
11use std::ops::Deref;
12use std::ptr::NonNull;
13
14use crate::aligned::Aligned;
15use crate::stable_hasher::{HashStable, StableHasher};
16
17/// This describes tags that the [`TaggedRef`] struct can hold.
18///
19/// # Safety
20///
21/// - The [`BITS`] constant must be correct.
22/// - No more than [`BITS`] least-significant bits may be set in the returned usize.
23/// - [`Eq`] and [`Hash`] must be implementable with the returned `usize` from `into_usize`.
24///
25/// [`BITS`]: Tag::BITS
26pub unsafe trait Tag: Copy {
27    /// Number of least-significant bits in the return value of [`into_usize`]
28    /// which may be non-zero. In other words this is the bit width of the
29    /// value.
30    ///
31    /// [`into_usize`]: Tag::into_usize
32    const BITS: u32;
33
34    /// Turns this tag into an integer.
35    ///
36    /// The inverse of this function is [`from_usize`].
37    ///
38    /// This function guarantees that only the least-significant [`Self::BITS`]
39    /// bits can be non-zero.
40    ///
41    /// [`from_usize`]: Tag::from_usize
42    /// [`Self::BITS`]: Tag::BITS
43    fn into_usize(self) -> usize;
44
45    /// Re-creates the tag from the integer returned by [`into_usize`].
46    ///
47    /// # Safety
48    ///
49    /// The passed `tag` must be returned from [`into_usize`].
50    ///
51    /// [`into_usize`]: Tag::into_usize
52    unsafe fn from_usize(tag: usize) -> Self;
53}
54
55/// Returns the number of bits available for use for tags in a pointer to `T`
56/// (this is based on `T`'s alignment).
57pub const fn bits_for<T: ?Sized + Aligned>() -> u32 {
58    crate::aligned::align_of::<T>().as_nonzero().trailing_zeros()
59}
60
61/// Returns the correct [`Tag::BITS`] constant for a set of tag values.
62pub const fn bits_for_tags(mut tags: &[usize]) -> u32 {
63    let mut bits = 0;
64
65    while let &[tag, ref rest @ ..] = tags {
66        tags = rest;
67
68        // bits required to represent `tag`,
69        // position of the most significant 1
70        let b = usize::BITS - tag.leading_zeros();
71        if b > bits {
72            bits = b;
73        }
74    }
75
76    bits
77}
78
79/// A covariant [`Copy`] tagged borrow. This is essentially `{ pointer: &'a P, tag: T }` packed
80/// in a single reference.
81pub struct TaggedRef<'a, Pointee: Aligned + ?Sized, T: Tag> {
82    /// This is semantically a pair of `pointer: &'a P` and `tag: T` fields,
83    /// however we pack them in a single pointer, to save space.
84    ///
85    /// We pack the tag into the **most**-significant bits of the pointer to
86    /// ease retrieval of the value. A left shift is a multiplication and
87    /// those are embeddable in instruction encoding, for example:
88    ///
89    /// ```asm
90    /// // (<https://godbolt.org/z/jqcYPWEr3>)
91    /// example::shift_read3:
92    ///     mov     eax, dword ptr [8*rdi]
93    ///     ret
94    ///
95    /// example::mask_read3:
96    ///     and     rdi, -8
97    ///     mov     eax, dword ptr [rdi]
98    ///     ret
99    /// ```
100    ///
101    /// This is ASM outputted by rustc for reads of values behind tagged
102    /// pointers for different approaches of tagging:
103    /// - `shift_read3` uses `<< 3` (the tag is in the most-significant bits)
104    /// - `mask_read3` uses `& !0b111` (the tag is in the least-significant bits)
105    ///
106    /// The shift approach thus produces less instructions and is likely faster
107    /// (see <https://godbolt.org/z/Y913sMdWb>).
108    ///
109    /// Encoding diagram:
110    /// ```text
111    /// [ packed.addr                     ]
112    /// [ tag ] [ pointer.addr >> T::BITS ] <-- usize::BITS - T::BITS bits
113    ///    ^
114    ///    |
115    /// T::BITS bits
116    /// ```
117    ///
118    /// The tag can be retrieved by `packed.addr() >> T::BITS` and the pointer
119    /// can be retrieved by `packed.map_addr(|addr| addr << T::BITS)`.
120    packed: NonNull<Pointee>,
121    tag_pointer_ghost: PhantomData<(&'a Pointee, T)>,
122}
123
124impl<'a, P, T> TaggedRef<'a, P, T>
125where
126    P: Aligned + ?Sized,
127    T: Tag,
128{
129    /// Tags `pointer` with `tag`.
130    ///
131    /// [`TaggedRef`]: crate::tagged_ptr::TaggedRef
132    #[inline]
133    pub fn new(pointer: &'a P, tag: T) -> Self {
134        Self { packed: Self::pack(NonNull::from(pointer), tag), tag_pointer_ghost: PhantomData }
135    }
136
137    /// Retrieves the pointer.
138    #[inline]
139    pub fn pointer(self) -> &'a P {
140        // SAFETY: pointer_raw returns the original pointer
141        unsafe { self.pointer_raw().as_ref() }
142    }
143
144    /// Retrieves the tag.
145    #[inline]
146    pub fn tag(&self) -> T {
147        // Unpack the tag, according to the `self.packed` encoding scheme
148        let tag = self.packed.addr().get() >> Self::TAG_BIT_SHIFT;
149
150        // Safety:
151        // The shift retrieves the original value from `T::into_usize`,
152        // satisfying `T::from_usize`'s preconditions.
153        unsafe { T::from_usize(tag) }
154    }
155
156    /// Sets the tag to a new value.
157    #[inline]
158    pub fn set_tag(&mut self, tag: T) {
159        self.packed = Self::pack(self.pointer_raw(), tag);
160    }
161
162    const TAG_BIT_SHIFT: u32 = usize::BITS - T::BITS;
163    const ASSERTION: () = { assert!(T::BITS <= bits_for::<P>()) };
164
165    /// Pack pointer `ptr` with a `tag`, according to `self.packed` encoding scheme.
166    #[inline]
167    fn pack(ptr: NonNull<P>, tag: T) -> NonNull<P> {
168        // Trigger assert!
169        let () = Self::ASSERTION;
170
171        let packed_tag = tag.into_usize() << Self::TAG_BIT_SHIFT;
172
173        ptr.map_addr(|addr| {
174            // Safety:
175            // - The pointer is `NonNull` => it's address is `NonZero<usize>`
176            // - `P::BITS` least significant bits are always zero (`Pointer` contract)
177            // - `T::BITS <= P::BITS` (from `Self::ASSERTION`)
178            //
179            // Thus `addr >> T::BITS` is guaranteed to be non-zero.
180            //
181            // `{non_zero} | packed_tag` can't make the value zero.
182
183            let packed = (addr.get() >> T::BITS) | packed_tag;
184            unsafe { NonZero::new_unchecked(packed) }
185        })
186    }
187
188    /// Retrieves the original raw pointer from `self.packed`.
189    #[inline]
190    pub(super) fn pointer_raw(&self) -> NonNull<P> {
191        self.packed.map_addr(|addr| unsafe { NonZero::new_unchecked(addr.get() << T::BITS) })
192    }
193}
194
195impl<P, T> Copy for TaggedRef<'_, P, T>
196where
197    P: Aligned + ?Sized,
198    T: Tag,
199{
200}
201
202impl<P, T> Clone for TaggedRef<'_, P, T>
203where
204    P: Aligned + ?Sized,
205    T: Tag,
206{
207    #[inline]
208    fn clone(&self) -> Self {
209        *self
210    }
211}
212
213impl<P, T> Deref for TaggedRef<'_, P, T>
214where
215    P: Aligned + ?Sized,
216    T: Tag,
217{
218    type Target = P;
219
220    #[inline]
221    fn deref(&self) -> &Self::Target {
222        self.pointer()
223    }
224}
225
226impl<P, T> fmt::Debug for TaggedRef<'_, P, T>
227where
228    P: Aligned + fmt::Debug + ?Sized,
229    T: Tag + fmt::Debug,
230{
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        f.debug_struct("TaggedRef")
233            .field("pointer", &self.pointer())
234            .field("tag", &self.tag())
235            .finish()
236    }
237}
238
239impl<P, T> PartialEq for TaggedRef<'_, P, T>
240where
241    P: Aligned + ?Sized,
242    T: Tag,
243{
244    #[inline]
245    #[allow(ambiguous_wide_pointer_comparisons)]
246    fn eq(&self, other: &Self) -> bool {
247        self.packed == other.packed
248    }
249}
250
251impl<P, T: Tag> Eq for TaggedRef<'_, P, T> {}
252
253impl<P, T: Tag> Hash for TaggedRef<'_, P, T> {
254    #[inline]
255    fn hash<H: Hasher>(&self, state: &mut H) {
256        self.packed.hash(state);
257    }
258}
259
260impl<'a, P, T, HCX> HashStable<HCX> for TaggedRef<'a, P, T>
261where
262    P: HashStable<HCX> + Aligned + ?Sized,
263    T: Tag + HashStable<HCX>,
264{
265    fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
266        self.pointer().hash_stable(hcx, hasher);
267        self.tag().hash_stable(hcx, hasher);
268    }
269}
270
271// Safety:
272// `TaggedRef<P, T, ..>` is semantically just `{ ptr: P, tag: T }`, as such
273// it's ok to implement `Sync` as long as `P: Sync, T: Sync`
274unsafe impl<P, T> Sync for TaggedRef<'_, P, T>
275where
276    P: Sync + Aligned + ?Sized,
277    T: Sync + Tag,
278{
279}
280
281// Safety:
282// `TaggedRef<P, T, ..>` is semantically just `{ ptr: P, tag: T }`, as such
283// it's ok to implement `Send` as long as `P: Send, T: Send`
284unsafe impl<P, T> Send for TaggedRef<'_, P, T>
285where
286    P: Sync + Aligned + ?Sized,
287    T: Send + Tag,
288{
289}
290
291#[cfg(test)]
292mod tests;