Skip to content

Commit 80a897a

Browse files
committed
Auto merge of rust-lang#118490 - Nadrieril:arena-alloc-matrix, r=nnethercote
Exhaustiveness: allocate memory better Exhaustiveness is a recursive algorithm that allocates a bunch of slices at every step. Let's see if I can improve performance by improving allocations. Already just using `Vec::with_capacity` is showing impressive improvements on my local measurements. r? `@ghost`
2 parents 85a4bd8 + c1774a1 commit 80a897a

File tree

2 files changed

+33
-31
lines changed

2 files changed

+33
-31
lines changed

compiler/rustc_arena/src/lib.rs

+25-16
Original file line numberDiff line numberDiff line change
@@ -197,23 +197,24 @@ impl<T> TypedArena<T> {
197197
start_ptr
198198
}
199199

200+
/// Allocates the elements of this iterator into a contiguous slice in the `TypedArena`.
201+
///
202+
/// Note: for reasons of reentrancy and panic safety we collect into a `SmallVec<[_; 8]>` before
203+
/// storing the elements in the arena.
200204
#[inline]
201205
pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
202-
// This implementation is entirely separate to
203-
// `DroplessIterator::alloc_from_iter`, even though conceptually they
204-
// are the same.
206+
// Despite the similarlty with `DroplessArena`, we cannot reuse their fast case. The reason
207+
// is subtle: these arenas are reentrant. In other words, `iter` may very well be holding a
208+
// reference to `self` and adding elements to the arena during iteration.
205209
//
206-
// `DroplessIterator` (in the fast case) writes elements from the
207-
// iterator one at a time into the allocated memory. That's easy
208-
// because the elements don't implement `Drop`. But for `TypedArena`
209-
// they do implement `Drop`, which means that if the iterator panics we
210-
// could end up with some allocated-but-uninitialized elements, which
211-
// will then cause UB in `TypedArena::drop`.
210+
// For this reason, if we pre-allocated any space for the elements of this iterator, we'd
211+
// have to track that some uninitialized elements are followed by some initialized elements,
212+
// else we might accidentally drop uninitialized memory if something panics or if the
213+
// iterator doesn't fill all the length we expected.
212214
//
213-
// Instead we use an approach where any iterator panic will occur
214-
// before the memory is allocated. This function is much less hot than
215-
// `DroplessArena::alloc_from_iter`, so it doesn't need to be
216-
// hyper-optimized.
215+
// So we collect all the elements beforehand, which takes care of reentrancy and panic
216+
// safety. This function is much less hot than `DroplessArena::alloc_from_iter`, so it
217+
// doesn't need to be hyper-optimized.
217218
assert!(mem::size_of::<T>() != 0);
218219

219220
let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
@@ -485,8 +486,9 @@ impl DroplessArena {
485486

486487
/// # Safety
487488
///
488-
/// The caller must ensure that `mem` is valid for writes up to
489-
/// `size_of::<T>() * len`.
489+
/// The caller must ensure that `mem` is valid for writes up to `size_of::<T>() * len`, and that
490+
/// that memory stays allocated and not shared for the lifetime of `self`. This must hold even
491+
/// if `iter.next()` allocates onto `self`.
490492
#[inline]
491493
unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
492494
&self,
@@ -516,6 +518,8 @@ impl DroplessArena {
516518

517519
#[inline]
518520
pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
521+
// Warning: this function is reentrant: `iter` could hold a reference to `&self` and
522+
// allocate additional elements while we're iterating.
519523
let iter = iter.into_iter();
520524
assert!(mem::size_of::<T>() != 0);
521525
assert!(!mem::needs_drop::<T>());
@@ -524,18 +528,23 @@ impl DroplessArena {
524528

525529
match size_hint {
526530
(min, Some(max)) if min == max => {
527-
// We know the exact number of elements the iterator will produce here
531+
// We know the exact number of elements the iterator expects to produce here.
528532
let len = min;
529533

530534
if len == 0 {
531535
return &mut [];
532536
}
533537

534538
let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
539+
// SAFETY: `write_from_iter` doesn't touch `self`. It only touches the slice we just
540+
// reserved. If the iterator panics or doesn't output `len` elements, this will
541+
// leave some unallocated slots in the arena, which is fine because we do not call
542+
// `drop`.
535543
unsafe { self.write_from_iter(iter, len, mem) }
536544
}
537545
(_, _) => {
538546
outline(move || -> &mut [T] {
547+
// Takes care of reentrancy.
539548
let mut vec: SmallVec<[_; 8]> = iter.collect();
540549
if vec.is_empty() {
541550
return &mut [];

compiler/rustc_mir_build/src/thir/pattern/usefulness.rs

+8-15
Original file line numberDiff line numberDiff line change
@@ -599,9 +599,9 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
599599
// an or-pattern. Panics if `self` is empty.
600600
fn expand_or_pat<'a>(&'a self) -> impl Iterator<Item = PatStack<'p, 'tcx>> + Captures<'a> {
601601
self.head().flatten_or_pat().into_iter().map(move |pat| {
602-
let mut new_pats = smallvec![pat];
603-
new_pats.extend_from_slice(&self.pats[1..]);
604-
PatStack { pats: new_pats }
602+
let mut new = self.clone();
603+
new.pats[0] = pat;
604+
new
605605
})
606606
}
607607

@@ -732,18 +732,11 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
732732
}
733733

734734
/// Build a new matrix from an iterator of `MatchArm`s.
735-
fn new<'a>(
736-
cx: &MatchCheckCtxt<'p, 'tcx>,
737-
iter: impl Iterator<Item = &'a MatchArm<'p, 'tcx>>,
738-
scrut_ty: Ty<'tcx>,
739-
) -> Self
740-
where
741-
'p: 'a,
742-
{
735+
fn new(cx: &MatchCheckCtxt<'p, 'tcx>, arms: &[MatchArm<'p, 'tcx>], scrut_ty: Ty<'tcx>) -> Self {
743736
let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty, DUMMY_SP));
744737
let wildcard_row = PatStack::from_pattern(wild_pattern);
745-
let mut matrix = Matrix { rows: vec![], wildcard_row };
746-
for (row_id, arm) in iter.enumerate() {
738+
let mut matrix = Matrix { rows: Vec::with_capacity(arms.len()), wildcard_row };
739+
for (row_id, arm) in arms.iter().enumerate() {
747740
let v = MatrixRow {
748741
pats: PatStack::from_pattern(arm.pat),
749742
parent_row: row_id, // dummy, we won't read it
@@ -806,7 +799,7 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
806799
ctor: &Constructor<'tcx>,
807800
) -> Matrix<'p, 'tcx> {
808801
let wildcard_row = self.wildcard_row.pop_head_constructor(pcx, ctor);
809-
let mut matrix = Matrix { rows: vec![], wildcard_row };
802+
let mut matrix = Matrix { rows: Vec::new(), wildcard_row };
810803
for (i, row) in self.rows().enumerate() {
811804
if ctor.is_covered_by(pcx, row.head().ctor()) {
812805
let new_row = row.pop_head_constructor(pcx, ctor, i);
@@ -1386,7 +1379,7 @@ pub(crate) fn compute_match_usefulness<'p, 'tcx>(
13861379
arms: &[MatchArm<'p, 'tcx>],
13871380
scrut_ty: Ty<'tcx>,
13881381
) -> UsefulnessReport<'p, 'tcx> {
1389-
let mut matrix = Matrix::new(cx, arms.iter(), scrut_ty);
1382+
let mut matrix = Matrix::new(cx, arms, scrut_ty);
13901383
let non_exhaustiveness_witnesses =
13911384
compute_exhaustiveness_and_reachability(cx, &mut matrix, true);
13921385

0 commit comments

Comments
 (0)