]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/interpret/allocation.rs
Auto merge of #86213 - jhpratt:stabilize-const-from_utf8_unchecked, r=JohnTitor
[rust.git] / compiler / rustc_middle / src / mir / interpret / allocation.rs
1 //! The virtual memory representation of the MIR interpreter.
2
3 use std::borrow::Cow;
4 use std::convert::TryFrom;
5 use std::iter;
6 use std::ops::{Deref, DerefMut, Range};
7 use std::ptr;
8
9 use rustc_ast::Mutability;
10 use rustc_data_structures::sorted_map::SortedMap;
11 use rustc_span::DUMMY_SP;
12 use rustc_target::abi::{Align, HasDataLayout, Size};
13
14 use super::{
15     read_target_uint, write_target_uint, AllocId, InterpError, InterpResult, Pointer,
16     ResourceExhaustionInfo, Scalar, ScalarMaybeUninit, UndefinedBehaviorInfo, UninitBytesAccess,
17     UnsupportedOpInfo,
18 };
19 use crate::ty;
20
21 /// This type represents an Allocation in the Miri/CTFE core engine.
22 ///
23 /// Its public API is rather low-level, working directly with allocation offsets and a custom error
24 /// type to account for the lack of an AllocId on this level. The Miri/CTFE core engine `memory`
25 /// module provides higher-level access.
26 #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
27 #[derive(HashStable)]
28 pub struct Allocation<Tag = (), Extra = ()> {
29     /// The actual bytes of the allocation.
30     /// Note that the bytes of a pointer represent the offset of the pointer.
31     bytes: Vec<u8>,
32     /// Maps from byte addresses to extra data for each pointer.
33     /// Only the first byte of a pointer is inserted into the map; i.e.,
34     /// every entry in this map applies to `pointer_size` consecutive bytes starting
35     /// at the given offset.
36     relocations: Relocations<Tag>,
37     /// Denotes which part of this allocation is initialized.
38     init_mask: InitMask,
39     /// The alignment of the allocation to detect unaligned reads.
40     /// (`Align` guarantees that this is a power of two.)
41     pub align: Align,
42     /// `true` if the allocation is mutable.
43     /// Also used by codegen to determine if a static should be put into mutable memory,
44     /// which happens for `static mut` and `static` with interior mutability.
45     pub mutability: Mutability,
46     /// Extra state for the machine.
47     pub extra: Extra,
48 }
49
50 /// We have our own error type that does not know about the `AllocId`; that information
51 /// is added when converting to `InterpError`.
52 #[derive(Debug)]
53 pub enum AllocError {
54     /// Encountered a pointer where we needed raw bytes.
55     ReadPointerAsBytes,
56     /// Using uninitialized data where it is not allowed.
57     InvalidUninitBytes(Option<UninitBytesAccess>),
58 }
59 pub type AllocResult<T = ()> = Result<T, AllocError>;
60
61 impl AllocError {
62     pub fn to_interp_error<'tcx>(self, alloc_id: AllocId) -> InterpError<'tcx> {
63         match self {
64             AllocError::ReadPointerAsBytes => {
65                 InterpError::Unsupported(UnsupportedOpInfo::ReadPointerAsBytes)
66             }
67             AllocError::InvalidUninitBytes(info) => InterpError::UndefinedBehavior(
68                 UndefinedBehaviorInfo::InvalidUninitBytes(info.map(|b| (alloc_id, b))),
69             ),
70         }
71     }
72 }
73
74 /// The information that makes up a memory access: offset and size.
75 #[derive(Copy, Clone, Debug)]
76 pub struct AllocRange {
77     pub start: Size,
78     pub size: Size,
79 }
80
81 /// Free-starting constructor for less syntactic overhead.
82 #[inline(always)]
83 pub fn alloc_range(start: Size, size: Size) -> AllocRange {
84     AllocRange { start, size }
85 }
86
87 impl AllocRange {
88     #[inline(always)]
89     pub fn end(self) -> Size {
90         self.start + self.size // This does overflow checking.
91     }
92
93     /// Returns the `subrange` within this range; panics if it is not a subrange.
94     #[inline]
95     pub fn subrange(self, subrange: AllocRange) -> AllocRange {
96         let sub_start = self.start + subrange.start;
97         let range = alloc_range(sub_start, subrange.size);
98         assert!(range.end() <= self.end(), "access outside the bounds for given AllocRange");
99         range
100     }
101 }
102
103 // The constructors are all without extra; the extra gets added by a machine hook later.
104 impl<Tag> Allocation<Tag> {
105     /// Creates an allocation initialized by the given bytes
106     pub fn from_bytes<'a>(
107         slice: impl Into<Cow<'a, [u8]>>,
108         align: Align,
109         mutability: Mutability,
110     ) -> Self {
111         let bytes = slice.into().into_owned();
112         let size = Size::from_bytes(bytes.len());
113         Self {
114             bytes,
115             relocations: Relocations::new(),
116             init_mask: InitMask::new(size, true),
117             align,
118             mutability,
119             extra: (),
120         }
121     }
122
123     pub fn from_bytes_byte_aligned_immutable<'a>(slice: impl Into<Cow<'a, [u8]>>) -> Self {
124         Allocation::from_bytes(slice, Align::ONE, Mutability::Not)
125     }
126
127     /// Try to create an Allocation of `size` bytes, failing if there is not enough memory
128     /// available to the compiler to do so.
129     pub fn uninit(size: Size, align: Align, panic_on_fail: bool) -> InterpResult<'static, Self> {
130         let mut bytes = Vec::new();
131         bytes.try_reserve(size.bytes_usize()).map_err(|_| {
132             // This results in an error that can happen non-deterministically, since the memory
133             // available to the compiler can change between runs. Normally queries are always
134             // deterministic. However, we can be non-determinstic here because all uses of const
135             // evaluation (including ConstProp!) will make compilation fail (via hard error
136             // or ICE) upon encountering a `MemoryExhausted` error.
137             if panic_on_fail {
138                 panic!("Allocation::uninit called with panic_on_fail had allocation failure")
139             }
140             ty::tls::with(|tcx| {
141                 tcx.sess.delay_span_bug(DUMMY_SP, "exhausted memory during interpreation")
142             });
143             InterpError::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted)
144         })?;
145         bytes.resize(size.bytes_usize(), 0);
146         Ok(Allocation {
147             bytes,
148             relocations: Relocations::new(),
149             init_mask: InitMask::new(size, false),
150             align,
151             mutability: Mutability::Mut,
152             extra: (),
153         })
154     }
155 }
156
157 impl Allocation<()> {
158     /// Add Tag and Extra fields
159     pub fn with_tags_and_extra<T, E>(
160         self,
161         mut tagger: impl FnMut(AllocId) -> T,
162         extra: E,
163     ) -> Allocation<T, E> {
164         Allocation {
165             bytes: self.bytes,
166             relocations: Relocations::from_presorted(
167                 self.relocations
168                     .iter()
169                     // The allocations in the relocations (pointers stored *inside* this allocation)
170                     // all get the base pointer tag.
171                     .map(|&(offset, ((), alloc))| {
172                         let tag = tagger(alloc);
173                         (offset, (tag, alloc))
174                     })
175                     .collect(),
176             ),
177             init_mask: self.init_mask,
178             align: self.align,
179             mutability: self.mutability,
180             extra,
181         }
182     }
183 }
184
185 /// Raw accessors. Provide access to otherwise private bytes.
186 impl<Tag, Extra> Allocation<Tag, Extra> {
187     pub fn len(&self) -> usize {
188         self.bytes.len()
189     }
190
191     pub fn size(&self) -> Size {
192         Size::from_bytes(self.len())
193     }
194
195     /// Looks at a slice which may describe uninitialized bytes or describe a relocation. This differs
196     /// from `get_bytes_with_uninit_and_ptr` in that it does no relocation checks (even on the
197     /// edges) at all.
198     /// This must not be used for reads affecting the interpreter execution.
199     pub fn inspect_with_uninit_and_ptr_outside_interpreter(&self, range: Range<usize>) -> &[u8] {
200         &self.bytes[range]
201     }
202
203     /// Returns the mask indicating which bytes are initialized.
204     pub fn init_mask(&self) -> &InitMask {
205         &self.init_mask
206     }
207
208     /// Returns the relocation list.
209     pub fn relocations(&self) -> &Relocations<Tag> {
210         &self.relocations
211     }
212 }
213
214 /// Byte accessors.
215 impl<Tag: Copy, Extra> Allocation<Tag, Extra> {
216     /// The last argument controls whether we error out when there are uninitialized
217     /// or pointer bytes. You should never call this, call `get_bytes` or
218     /// `get_bytes_with_uninit_and_ptr` instead,
219     ///
220     /// This function also guarantees that the resulting pointer will remain stable
221     /// even when new allocations are pushed to the `HashMap`. `copy_repeatedly` relies
222     /// on that.
223     ///
224     /// It is the caller's responsibility to check bounds and alignment beforehand.
225     fn get_bytes_internal(
226         &self,
227         cx: &impl HasDataLayout,
228         range: AllocRange,
229         check_init_and_ptr: bool,
230     ) -> AllocResult<&[u8]> {
231         if check_init_and_ptr {
232             self.check_init(range)?;
233             self.check_relocations(cx, range)?;
234         } else {
235             // We still don't want relocations on the *edges*.
236             self.check_relocation_edges(cx, range)?;
237         }
238
239         Ok(&self.bytes[range.start.bytes_usize()..range.end().bytes_usize()])
240     }
241
242     /// Checks that these bytes are initialized and not pointer bytes, and then return them
243     /// as a slice.
244     ///
245     /// It is the caller's responsibility to check bounds and alignment beforehand.
246     /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods
247     /// on `InterpCx` instead.
248     #[inline]
249     pub fn get_bytes(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult<&[u8]> {
250         self.get_bytes_internal(cx, range, true)
251     }
252
253     /// It is the caller's responsibility to handle uninitialized and pointer bytes.
254     /// However, this still checks that there are no relocations on the *edges*.
255     ///
256     /// It is the caller's responsibility to check bounds and alignment beforehand.
257     #[inline]
258     pub fn get_bytes_with_uninit_and_ptr(
259         &self,
260         cx: &impl HasDataLayout,
261         range: AllocRange,
262     ) -> AllocResult<&[u8]> {
263         self.get_bytes_internal(cx, range, false)
264     }
265
266     /// Just calling this already marks everything as defined and removes relocations,
267     /// so be sure to actually put data there!
268     ///
269     /// It is the caller's responsibility to check bounds and alignment beforehand.
270     /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods
271     /// on `InterpCx` instead.
272     pub fn get_bytes_mut(&mut self, cx: &impl HasDataLayout, range: AllocRange) -> &mut [u8] {
273         self.mark_init(range, true);
274         self.clear_relocations(cx, range);
275
276         &mut self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]
277     }
278
279     /// A raw pointer variant of `get_bytes_mut` that avoids invalidating existing aliases into this memory.
280     pub fn get_bytes_mut_ptr(&mut self, cx: &impl HasDataLayout, range: AllocRange) -> *mut [u8] {
281         self.mark_init(range, true);
282         self.clear_relocations(cx, range);
283
284         assert!(range.end().bytes_usize() <= self.bytes.len()); // need to do our own bounds-check
285         let begin_ptr = self.bytes.as_mut_ptr().wrapping_add(range.start.bytes_usize());
286         let len = range.end().bytes_usize() - range.start.bytes_usize();
287         ptr::slice_from_raw_parts_mut(begin_ptr, len)
288     }
289 }
290
291 /// Reading and writing.
292 impl<Tag: Copy, Extra> Allocation<Tag, Extra> {
293     /// Validates that `ptr.offset` and `ptr.offset + size` do not point to the middle of a
294     /// relocation. If `allow_uninit_and_ptr` is `false`, also enforces that the memory in the
295     /// given range contains neither relocations nor uninitialized bytes.
296     pub fn check_bytes(
297         &self,
298         cx: &impl HasDataLayout,
299         range: AllocRange,
300         allow_uninit_and_ptr: bool,
301     ) -> AllocResult {
302         // Check bounds and relocations on the edges.
303         self.get_bytes_with_uninit_and_ptr(cx, range)?;
304         // Check uninit and ptr.
305         if !allow_uninit_and_ptr {
306             self.check_init(range)?;
307             self.check_relocations(cx, range)?;
308         }
309         Ok(())
310     }
311
312     /// Reads a *non-ZST* scalar.
313     ///
314     /// ZSTs can't be read because in order to obtain a `Pointer`, we need to check
315     /// for ZSTness anyway due to integer pointers being valid for ZSTs.
316     ///
317     /// It is the caller's responsibility to check bounds and alignment beforehand.
318     /// Most likely, you want to call `InterpCx::read_scalar` instead of this method.
319     pub fn read_scalar(
320         &self,
321         cx: &impl HasDataLayout,
322         range: AllocRange,
323     ) -> AllocResult<ScalarMaybeUninit<Tag>> {
324         // `get_bytes_unchecked` tests relocation edges.
325         let bytes = self.get_bytes_with_uninit_and_ptr(cx, range)?;
326         // Uninit check happens *after* we established that the alignment is correct.
327         // We must not return `Ok()` for unaligned pointers!
328         if self.is_init(range).is_err() {
329             // This inflates uninitialized bytes to the entire scalar, even if only a few
330             // bytes are uninitialized.
331             return Ok(ScalarMaybeUninit::Uninit);
332         }
333         // Now we do the actual reading.
334         let bits = read_target_uint(cx.data_layout().endian, bytes).unwrap();
335         // See if we got a pointer.
336         if range.size != cx.data_layout().pointer_size {
337             // Not a pointer.
338             // *Now*, we better make sure that the inside is free of relocations too.
339             self.check_relocations(cx, range)?;
340         } else {
341             // Maybe a pointer.
342             if let Some(&(tag, alloc_id)) = self.relocations.get(&range.start) {
343                 let ptr = Pointer::new_with_tag(alloc_id, Size::from_bytes(bits), tag);
344                 return Ok(ScalarMaybeUninit::Scalar(ptr.into()));
345             }
346         }
347         // We don't. Just return the bits.
348         Ok(ScalarMaybeUninit::Scalar(Scalar::from_uint(bits, range.size)))
349     }
350
351     /// Writes a *non-ZST* scalar.
352     ///
353     /// ZSTs can't be read because in order to obtain a `Pointer`, we need to check
354     /// for ZSTness anyway due to integer pointers being valid for ZSTs.
355     ///
356     /// It is the caller's responsibility to check bounds and alignment beforehand.
357     /// Most likely, you want to call `InterpCx::write_scalar` instead of this method.
358     pub fn write_scalar(
359         &mut self,
360         cx: &impl HasDataLayout,
361         range: AllocRange,
362         val: ScalarMaybeUninit<Tag>,
363     ) -> AllocResult {
364         let val = match val {
365             ScalarMaybeUninit::Scalar(scalar) => scalar,
366             ScalarMaybeUninit::Uninit => {
367                 self.mark_init(range, false);
368                 return Ok(());
369             }
370         };
371
372         let bytes = match val.to_bits_or_ptr(range.size, cx) {
373             Err(val) => u128::from(val.offset.bytes()),
374             Ok(data) => data,
375         };
376
377         let endian = cx.data_layout().endian;
378         let dst = self.get_bytes_mut(cx, range);
379         write_target_uint(endian, dst, bytes).unwrap();
380
381         // See if we have to also write a relocation.
382         if let Scalar::Ptr(val) = val {
383             self.relocations.insert(range.start, (val.tag, val.alloc_id));
384         }
385
386         Ok(())
387     }
388 }
389
390 /// Relocations.
391 impl<Tag: Copy, Extra> Allocation<Tag, Extra> {
392     /// Returns all relocations overlapping with the given pointer-offset pair.
393     pub fn get_relocations(
394         &self,
395         cx: &impl HasDataLayout,
396         range: AllocRange,
397     ) -> &[(Size, (Tag, AllocId))] {
398         // We have to go back `pointer_size - 1` bytes, as that one would still overlap with
399         // the beginning of this range.
400         let start = range.start.bytes().saturating_sub(cx.data_layout().pointer_size.bytes() - 1);
401         self.relocations.range(Size::from_bytes(start)..range.end())
402     }
403
404     /// Checks that there are no relocations overlapping with the given range.
405     #[inline(always)]
406     fn check_relocations(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult {
407         if self.get_relocations(cx, range).is_empty() {
408             Ok(())
409         } else {
410             Err(AllocError::ReadPointerAsBytes)
411         }
412     }
413
414     /// Removes all relocations inside the given range.
415     /// If there are relocations overlapping with the edges, they
416     /// are removed as well *and* the bytes they cover are marked as
417     /// uninitialized. This is a somewhat odd "spooky action at a distance",
418     /// but it allows strictly more code to run than if we would just error
419     /// immediately in that case.
420     fn clear_relocations(&mut self, cx: &impl HasDataLayout, range: AllocRange) {
421         // Find the start and end of the given range and its outermost relocations.
422         let (first, last) = {
423             // Find all relocations overlapping the given range.
424             let relocations = self.get_relocations(cx, range);
425             if relocations.is_empty() {
426                 return;
427             }
428
429             (
430                 relocations.first().unwrap().0,
431                 relocations.last().unwrap().0 + cx.data_layout().pointer_size,
432             )
433         };
434         let start = range.start;
435         let end = range.end();
436
437         // Mark parts of the outermost relocations as uninitialized if they partially fall outside the
438         // given range.
439         if first < start {
440             self.init_mask.set_range(first, start, false);
441         }
442         if last > end {
443             self.init_mask.set_range(end, last, false);
444         }
445
446         // Forget all the relocations.
447         self.relocations.remove_range(first..last);
448     }
449
450     /// Errors if there are relocations overlapping with the edges of the
451     /// given memory range.
452     #[inline]
453     fn check_relocation_edges(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult {
454         self.check_relocations(cx, alloc_range(range.start, Size::ZERO))?;
455         self.check_relocations(cx, alloc_range(range.end(), Size::ZERO))?;
456         Ok(())
457     }
458 }
459
460 /// Uninitialized bytes.
461 impl<Tag: Copy, Extra> Allocation<Tag, Extra> {
462     /// Checks whether the given range  is entirely initialized.
463     ///
464     /// Returns `Ok(())` if it's initialized. Otherwise returns the range of byte
465     /// indexes of the first contiguous uninitialized access.
466     fn is_init(&self, range: AllocRange) -> Result<(), Range<Size>> {
467         self.init_mask.is_range_initialized(range.start, range.end()) // `Size` addition
468     }
469
470     /// Checks that a range of bytes is initialized. If not, returns the `InvalidUninitBytes`
471     /// error which will report the first range of bytes which is uninitialized.
472     fn check_init(&self, range: AllocRange) -> AllocResult {
473         self.is_init(range).or_else(|idx_range| {
474             Err(AllocError::InvalidUninitBytes(Some(UninitBytesAccess {
475                 access_offset: range.start,
476                 access_size: range.size,
477                 uninit_offset: idx_range.start,
478                 uninit_size: idx_range.end - idx_range.start, // `Size` subtraction
479             })))
480         })
481     }
482
483     pub fn mark_init(&mut self, range: AllocRange, is_init: bool) {
484         if range.size.bytes() == 0 {
485             return;
486         }
487         self.init_mask.set_range(range.start, range.end(), is_init);
488     }
489 }
490
491 /// Run-length encoding of the uninit mask.
492 /// Used to copy parts of a mask multiple times to another allocation.
493 pub struct InitMaskCompressed {
494     /// Whether the first range is initialized.
495     initial: bool,
496     /// The lengths of ranges that are run-length encoded.
497     /// The initialization state of the ranges alternate starting with `initial`.
498     ranges: smallvec::SmallVec<[u64; 1]>,
499 }
500
501 impl InitMaskCompressed {
502     pub fn no_bytes_init(&self) -> bool {
503         // The `ranges` are run-length encoded and of alternating initialization state.
504         // So if `ranges.len() > 1` then the second block is an initialized range.
505         !self.initial && self.ranges.len() == 1
506     }
507 }
508
509 /// Transferring the initialization mask to other allocations.
510 impl<Tag, Extra> Allocation<Tag, Extra> {
511     /// Creates a run-length encoding of the initialization mask.
512     pub fn compress_uninit_range(&self, src: Pointer<Tag>, size: Size) -> InitMaskCompressed {
513         // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`),
514         // a naive initialization mask copying algorithm would repeatedly have to read the initialization mask from
515         // the source and write it to the destination. Even if we optimized the memory accesses,
516         // we'd be doing all of this `repeat` times.
517         // Therefore we precompute a compressed version of the initialization mask of the source value and
518         // then write it back `repeat` times without computing any more information from the source.
519
520         // A precomputed cache for ranges of initialized / uninitialized bits
521         // 0000010010001110 will become
522         // `[5, 1, 2, 1, 3, 3, 1]`,
523         // where each element toggles the state.
524
525         let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
526         let initial = self.init_mask.get(src.offset);
527         let mut cur_len = 1;
528         let mut cur = initial;
529
530         for i in 1..size.bytes() {
531             // FIXME: optimize to bitshift the current uninitialized block's bits and read the top bit.
532             if self.init_mask.get(src.offset + Size::from_bytes(i)) == cur {
533                 cur_len += 1;
534             } else {
535                 ranges.push(cur_len);
536                 cur_len = 1;
537                 cur = !cur;
538             }
539         }
540
541         ranges.push(cur_len);
542
543         InitMaskCompressed { ranges, initial }
544     }
545
546     /// Applies multiple instances of the run-length encoding to the initialization mask.
547     pub fn mark_compressed_init_range(
548         &mut self,
549         defined: &InitMaskCompressed,
550         dest: Pointer<Tag>,
551         size: Size,
552         repeat: u64,
553     ) {
554         // An optimization where we can just overwrite an entire range of initialization
555         // bits if they are going to be uniformly `1` or `0`.
556         if defined.ranges.len() <= 1 {
557             self.init_mask.set_range_inbounds(
558                 dest.offset,
559                 dest.offset + size * repeat, // `Size` operations
560                 defined.initial,
561             );
562             return;
563         }
564
565         for mut j in 0..repeat {
566             j *= size.bytes();
567             j += dest.offset.bytes();
568             let mut cur = defined.initial;
569             for range in &defined.ranges {
570                 let old_j = j;
571                 j += range;
572                 self.init_mask.set_range_inbounds(
573                     Size::from_bytes(old_j),
574                     Size::from_bytes(j),
575                     cur,
576                 );
577                 cur = !cur;
578             }
579         }
580     }
581 }
582
583 /// Relocations.
584 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
585 pub struct Relocations<Tag = (), Id = AllocId>(SortedMap<Size, (Tag, Id)>);
586
587 impl<Tag, Id> Relocations<Tag, Id> {
588     pub fn new() -> Self {
589         Relocations(SortedMap::new())
590     }
591
592     // The caller must guarantee that the given relocations are already sorted
593     // by address and contain no duplicates.
594     pub fn from_presorted(r: Vec<(Size, (Tag, Id))>) -> Self {
595         Relocations(SortedMap::from_presorted_elements(r))
596     }
597 }
598
599 impl<Tag> Deref for Relocations<Tag> {
600     type Target = SortedMap<Size, (Tag, AllocId)>;
601
602     fn deref(&self) -> &Self::Target {
603         &self.0
604     }
605 }
606
607 impl<Tag> DerefMut for Relocations<Tag> {
608     fn deref_mut(&mut self) -> &mut Self::Target {
609         &mut self.0
610     }
611 }
612
613 /// A partial, owned list of relocations to transfer into another allocation.
614 pub struct AllocationRelocations<Tag> {
615     relative_relocations: Vec<(Size, (Tag, AllocId))>,
616 }
617
618 impl<Tag: Copy, Extra> Allocation<Tag, Extra> {
619     pub fn prepare_relocation_copy(
620         &self,
621         cx: &impl HasDataLayout,
622         src: AllocRange,
623         dest: Size,
624         count: u64,
625     ) -> AllocationRelocations<Tag> {
626         let relocations = self.get_relocations(cx, src);
627         if relocations.is_empty() {
628             return AllocationRelocations { relative_relocations: Vec::new() };
629         }
630
631         let size = src.size;
632         let mut new_relocations = Vec::with_capacity(relocations.len() * (count as usize));
633
634         for i in 0..count {
635             new_relocations.extend(relocations.iter().map(|&(offset, reloc)| {
636                 // compute offset for current repetition
637                 let dest_offset = dest + size * i; // `Size` operations
638                 (
639                     // shift offsets from source allocation to destination allocation
640                     (offset + dest_offset) - src.start, // `Size` operations
641                     reloc,
642                 )
643             }));
644         }
645
646         AllocationRelocations { relative_relocations: new_relocations }
647     }
648
649     /// Applies a relocation copy.
650     /// The affected range, as defined in the parameters to `prepare_relocation_copy` is expected
651     /// to be clear of relocations.
652     pub fn mark_relocation_range(&mut self, relocations: AllocationRelocations<Tag>) {
653         self.relocations.insert_presorted(relocations.relative_relocations);
654     }
655 }
656
657 ////////////////////////////////////////////////////////////////////////////////
658 // Uninitialized byte tracking
659 ////////////////////////////////////////////////////////////////////////////////
660
661 type Block = u64;
662
663 /// A bitmask where each bit refers to the byte with the same index. If the bit is `true`, the byte
664 /// is initialized. If it is `false` the byte is uninitialized.
665 #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
666 #[derive(HashStable)]
667 pub struct InitMask {
668     blocks: Vec<Block>,
669     len: Size,
670 }
671
672 impl InitMask {
673     pub const BLOCK_SIZE: u64 = 64;
674
675     pub fn new(size: Size, state: bool) -> Self {
676         let mut m = InitMask { blocks: vec![], len: Size::ZERO };
677         m.grow(size, state);
678         m
679     }
680
681     /// Checks whether the range `start..end` (end-exclusive) is entirely initialized.
682     ///
683     /// Returns `Ok(())` if it's initialized. Otherwise returns a range of byte
684     /// indexes for the first contiguous span of the uninitialized access.
685     #[inline]
686     pub fn is_range_initialized(&self, start: Size, end: Size) -> Result<(), Range<Size>> {
687         if end > self.len {
688             return Err(self.len..end);
689         }
690
691         // FIXME(oli-obk): optimize this for allocations larger than a block.
692         let idx = (start.bytes()..end.bytes()).map(Size::from_bytes).find(|&i| !self.get(i));
693
694         match idx {
695             Some(idx) => {
696                 let uninit_end = (idx.bytes()..end.bytes())
697                     .map(Size::from_bytes)
698                     .find(|&i| self.get(i))
699                     .unwrap_or(end);
700                 Err(idx..uninit_end)
701             }
702             None => Ok(()),
703         }
704     }
705
706     pub fn set_range(&mut self, start: Size, end: Size, new_state: bool) {
707         let len = self.len;
708         if end > len {
709             self.grow(end - len, new_state);
710         }
711         self.set_range_inbounds(start, end, new_state);
712     }
713
714     pub fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) {
715         let (blocka, bita) = bit_index(start);
716         let (blockb, bitb) = bit_index(end);
717         if blocka == blockb {
718             // First set all bits except the first `bita`,
719             // then unset the last `64 - bitb` bits.
720             let range = if bitb == 0 {
721                 u64::MAX << bita
722             } else {
723                 (u64::MAX << bita) & (u64::MAX >> (64 - bitb))
724             };
725             if new_state {
726                 self.blocks[blocka] |= range;
727             } else {
728                 self.blocks[blocka] &= !range;
729             }
730             return;
731         }
732         // across block boundaries
733         if new_state {
734             // Set `bita..64` to `1`.
735             self.blocks[blocka] |= u64::MAX << bita;
736             // Set `0..bitb` to `1`.
737             if bitb != 0 {
738                 self.blocks[blockb] |= u64::MAX >> (64 - bitb);
739             }
740             // Fill in all the other blocks (much faster than one bit at a time).
741             for block in (blocka + 1)..blockb {
742                 self.blocks[block] = u64::MAX;
743             }
744         } else {
745             // Set `bita..64` to `0`.
746             self.blocks[blocka] &= !(u64::MAX << bita);
747             // Set `0..bitb` to `0`.
748             if bitb != 0 {
749                 self.blocks[blockb] &= !(u64::MAX >> (64 - bitb));
750             }
751             // Fill in all the other blocks (much faster than one bit at a time).
752             for block in (blocka + 1)..blockb {
753                 self.blocks[block] = 0;
754             }
755         }
756     }
757
758     #[inline]
759     pub fn get(&self, i: Size) -> bool {
760         let (block, bit) = bit_index(i);
761         (self.blocks[block] & (1 << bit)) != 0
762     }
763
764     #[inline]
765     pub fn set(&mut self, i: Size, new_state: bool) {
766         let (block, bit) = bit_index(i);
767         self.set_bit(block, bit, new_state);
768     }
769
770     #[inline]
771     fn set_bit(&mut self, block: usize, bit: usize, new_state: bool) {
772         if new_state {
773             self.blocks[block] |= 1 << bit;
774         } else {
775             self.blocks[block] &= !(1 << bit);
776         }
777     }
778
779     pub fn grow(&mut self, amount: Size, new_state: bool) {
780         if amount.bytes() == 0 {
781             return;
782         }
783         let unused_trailing_bits =
784             u64::try_from(self.blocks.len()).unwrap() * Self::BLOCK_SIZE - self.len.bytes();
785         if amount.bytes() > unused_trailing_bits {
786             let additional_blocks = amount.bytes() / Self::BLOCK_SIZE + 1;
787             self.blocks.extend(
788                 // FIXME(oli-obk): optimize this by repeating `new_state as Block`.
789                 iter::repeat(0).take(usize::try_from(additional_blocks).unwrap()),
790             );
791         }
792         let start = self.len;
793         self.len += amount;
794         self.set_range_inbounds(start, start + amount, new_state); // `Size` operation
795     }
796 }
797
798 #[inline]
799 fn bit_index(bits: Size) -> (usize, usize) {
800     let bits = bits.bytes();
801     let a = bits / InitMask::BLOCK_SIZE;
802     let b = bits % InitMask::BLOCK_SIZE;
803     (usize::try_from(a).unwrap(), usize::try_from(b).unwrap())
804 }