Skip to content

Commit b542750

Browse files
committed
Auto merge of #164187 - jhpratt:rollup-rOAAkkN, r=jhpratt
Rollup of 7 pull requests Successful merges: - #159744 (Allow unary operand types to be inferred later) - #160597 (bootstrap: always build llvm's dylib when linking to it) - #162810 (vectorized vec::dedup pre-scan) - #162931 (directly deallocates the nodes instead of traversing every element when BTreemap dropping) - #162027 (std: add `fs::rename_noreplace`) - #163883 (Add `oneshot` `Sender::is_closed`) - #164146 (Nuke `Unique` (and `ptr_internals`))
2 parents 03cbd41 + 2aad7af commit b542750

46 files changed

Lines changed: 1262 additions & 493 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_codegen_ssa/src/mir/retag.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ impl<'a, 'tcx, V> RetagPlan<V> {
151151
let boxed_ty = layout.ty.expect_boxed_ty();
152152
let boxed_layout = bx.layout_of(boxed_ty);
153153
if let Some(mut plan) = Self::emit_retag(bx, boxed_layout, None, is_fn_entry) {
154-
// `Unique<T>`
154+
// `BoxRaw<T>`
155155
let unique = layout.field(bx, 0);
156156
assert_eq!(unique.fields.count(), 2);
157157
plan = plan.for_field(FieldIdx::ZERO);

‎compiler/rustc_hir_typeck/src/expr.rs‎

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -426,35 +426,46 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
426426
return Ty::new_error(tcx, guar);
427427
}
428428

429-
let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t);
429+
// Resolve what we can for `Not` and `Neg`, but allow later constraints
430+
// to determine an unresolved operand type,
431+
// so we call `deeply_resolve_ignoring_regions_with_obligations` for them.
430432
match unop {
431-
hir::UnOp::Deref => self.lookup_derefing(expr, oprnd, oprnd_t).unwrap_or_else(|| {
432-
let mut err =
433-
self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t });
434-
let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None);
435-
if let Some(sp) =
436-
tcx.sess.psess.complete_stmt_exprs_before_bin_op_lookalike.borrow().get(&sp)
437-
{
438-
err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
439-
}
440-
// The operand may be an uncalled function, in which case it is its return type
441-
// the user meant to dereference. Only suggest the call when that return type is
442-
// itself dereferenceable, mirroring the checks `lookup_derefing` just failed.
443-
self.suggest_fn_call(&mut err, oprnd, oprnd_t, |output| {
444-
output.builtin_deref(true).is_some()
445-
|| self.tcx.lang_items().deref_trait().is_some_and(|deref_trait| {
446-
self.type_implements_trait(deref_trait, [output], self.param_env)
447-
.may_apply()
448-
})
449-
});
450-
Ty::new_error(tcx, err.emit_err())
451-
}),
433+
hir::UnOp::Deref => {
434+
// Dereferencing must distinguish builtin pointers from
435+
// overloaded `Deref`, so it still requires a structurally resolved type.
436+
//
437+
// This is necessary as raw pointers do not implement `Deref`.
438+
let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t);
439+
self.lookup_derefing(expr, oprnd, oprnd_t).unwrap_or_else(|| {
440+
let mut err =
441+
self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t });
442+
let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None);
443+
if let Some(sp) =
444+
tcx.sess.psess.complete_stmt_exprs_before_bin_op_lookalike.borrow().get(&sp)
445+
{
446+
err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
447+
}
448+
// The operand may be an uncalled function, in which case it is its return type
449+
// the user meant to dereference. Only suggest the call when that return type is
450+
// itself dereferenceable, mirroring the checks `lookup_derefing` just failed.
451+
self.suggest_fn_call(&mut err, oprnd, oprnd_t, |output| {
452+
output.builtin_deref(true).is_some()
453+
|| self.tcx.lang_items().deref_trait().is_some_and(|deref_trait| {
454+
self.type_implements_trait(deref_trait, [output], self.param_env)
455+
.may_apply()
456+
})
457+
});
458+
Ty::new_error(tcx, err.emit_err())
459+
})
460+
}
452461
hir::UnOp::Not => {
462+
let oprnd_t = self.deeply_resolve_ignoring_regions_with_obligations(oprnd_t);
453463
let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
454464
// If it's builtin, we can reuse the type, this helps inference.
455465
if oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool { oprnd_t } else { result }
456466
}
457467
hir::UnOp::Neg => {
468+
let oprnd_t = self.deeply_resolve_ignoring_regions_with_obligations(oprnd_t);
458469
let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
459470
// If it's builtin, we can reuse the type, this helps inference.
460471
if oprnd_t.is_numeric() { oprnd_t } else { result }

‎library/alloc/src/collections/btree/map.rs‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -205,16 +205,13 @@ pub struct BTreeMap<
205205
#[stable(feature = "btree_drop", since = "1.7.0")]
206206
unsafe impl<#[may_dangle] K, #[may_dangle] V, A: AllocatorClone> Drop for BTreeMap<K, V, A> {
207207
fn drop(&mut self) {
208-
// Skip `into_iter` for an empty map: `dying_next` is too costly to inline, so the
209-
// empty drop isn't optimised away (see #161375).
210-
if self.root.is_some() {
211-
// SAFETY: `self` is not used after this and none of its fields are dropped again:
212-
// `alloc` is `ManuallyDrop` and `root` has no drop glue.
213-
drop(unsafe { ptr::read(self) }.into_iter())
208+
if let Some(root) = self.root.take() {
209+
// SAFETY: The tree won't be used after this point.
210+
// The allocator has not been moved out and will be moved into `drop_tree`.
211+
unsafe { root.into_dying().drop_tree(ManuallyDrop::take(&mut self.alloc)) };
214212
} else {
215-
// SAFETY: With no root there are no nodes to free, so only the allocator needs
216-
// dropping. `self` is not used after this, and `alloc` is dropped only here.
217-
unsafe { ManuallyDrop::drop(&mut self.alloc) }
213+
// SAFETY: The allocator has not been moved out and won't be used after this point.
214+
unsafe { ManuallyDrop::drop(&mut self.alloc) };
218215
}
219216
}
220217
}

‎library/alloc/src/collections/btree/map/tests.rs‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2542,6 +2542,114 @@ fn test_into_iter_drop_leak_height_1() {
25422542
}
25432543
}
25442544

2545+
#[test]
2546+
fn test_drop_map_elements_multi_level() {
2547+
for size in [1, MIN_INSERTS_HEIGHT_1, MIN_INSERTS_HEIGHT_2] {
2548+
let keys = Vec::from_iter((0..size).map(CrashTestDummy::new));
2549+
let vals = Vec::from_iter((0..size).map(CrashTestDummy::new));
2550+
let map = {
2551+
let mut map = BTreeMap::new();
2552+
2553+
(0..size).map(|i| (keys[i].spawn(Panic::Never), vals[i].spawn(Panic::Never))).for_each(
2554+
|(k, v)| {
2555+
map.insert(k, v);
2556+
},
2557+
);
2558+
map
2559+
};
2560+
2561+
drop(map);
2562+
2563+
for i in 0..size {
2564+
assert_eq!(keys[i].dropped(), 1);
2565+
assert_eq!(vals[i].dropped(), 1);
2566+
}
2567+
}
2568+
}
2569+
2570+
#[test]
2571+
fn test_drop_empty_map_allocator() {
2572+
use core::alloc::{AllocError, Allocator, AllocatorClone, Layout};
2573+
use core::cell::Cell;
2574+
use core::ptr::NonNull;
2575+
2576+
struct CountedAllocator<'a>(&'a Cell<usize>);
2577+
2578+
impl Clone for CountedAllocator<'_> {
2579+
fn clone(&self) -> Self {
2580+
Self(self.0)
2581+
}
2582+
}
2583+
2584+
impl Drop for CountedAllocator<'_> {
2585+
fn drop(&mut self) {
2586+
self.0.set(self.0.get() + 1);
2587+
}
2588+
}
2589+
2590+
unsafe impl Allocator for CountedAllocator<'_> {
2591+
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
2592+
Global.allocate(layout)
2593+
}
2594+
2595+
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
2596+
unsafe { Global.deallocate(ptr, layout) }
2597+
}
2598+
}
2599+
2600+
unsafe impl AllocatorClone for CountedAllocator<'_> {}
2601+
2602+
let dropped = Cell::new(0);
2603+
let map = BTreeMap::<i32, i32, _>::new_in(CountedAllocator(&dropped));
2604+
assert!(map.root.is_none());
2605+
2606+
drop(map);
2607+
2608+
assert_eq!(dropped.get(), 1);
2609+
}
2610+
2611+
#[test]
2612+
#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]
2613+
fn test_drop_map_elements_multi_level_panic() {
2614+
for size in [1, MIN_INSERTS_HEIGHT_1, MIN_INSERTS_HEIGHT_2] {
2615+
for panic_point in [0, size / 2, size - 1] {
2616+
for panic_in_key in [true, false] {
2617+
let keys = Vec::from_iter((0..size).map(CrashTestDummy::new));
2618+
let vals = Vec::from_iter((0..size).map(CrashTestDummy::new));
2619+
let map = {
2620+
let mut map = BTreeMap::new();
2621+
2622+
(0..size)
2623+
.map(|i| {
2624+
let key_panic = if panic_in_key && i == panic_point {
2625+
Panic::InDrop
2626+
} else {
2627+
Panic::Never
2628+
};
2629+
let val_panic = if !panic_in_key && i == panic_point {
2630+
Panic::InDrop
2631+
} else {
2632+
Panic::Never
2633+
};
2634+
(keys[i].spawn(key_panic), vals[i].spawn(val_panic))
2635+
})
2636+
.for_each(|(k, v)| {
2637+
map.insert(k, v);
2638+
});
2639+
map
2640+
};
2641+
2642+
catch_unwind(move || drop(map)).unwrap_err();
2643+
2644+
for i in 0..size {
2645+
assert_eq!(keys[i].dropped(), 1);
2646+
assert_eq!(vals[i].dropped(), 1);
2647+
}
2648+
}
2649+
}
2650+
}
2651+
}
2652+
25452653
#[test]
25462654
fn test_into_keys() {
25472655
let map = BTreeMap::from([(1, 'a'), (2, 'b'), (3, 'c')]);

‎library/alloc/src/collections/btree/navigate.rs‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,3 +852,70 @@ impl<BorrowType: marker::BorrowType, K, V> NodeRef<BorrowType, K, V, marker::Lea
852852
}
853853
}
854854
}
855+
856+
impl<K, V> NodeRef<marker::Dying, K, V, marker::LeafOrInternal> {
857+
/// # Safety
858+
/// - `self` must be the root.
859+
/// - The tree shouldn't be accessed anymore.
860+
pub(super) unsafe fn drop_tree<A: AllocatorClone>(self, alloc: A) {
861+
struct DropGuard<K, V, A: AllocatorClone> {
862+
node: Option<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>>,
863+
alloc: A,
864+
}
865+
866+
impl<K, V, A: AllocatorClone> Drop for DropGuard<K, V, A> {
867+
fn drop(&mut self) {
868+
if let Some(cur) = self.node.take() {
869+
let mut next =
870+
// SAFETY: When unwinding reached this guard, all kvs in cur
871+
// have already been dropped in `drop_kvs`, while the node itself has not
872+
// yet been deallocated.
873+
unsafe { deallocate_and_next_postorder_node(cur, self.alloc.clone()) };
874+
875+
while let Some(mut node) = next {
876+
// SAFETY: Every node only calls the function once
877+
unsafe { node.drop_kvs() };
878+
next =
879+
// SAFETY: `drop_kvs()` above only dropped kvs and the node is still accessible,
880+
// and also each node is deallocated exactly once.
881+
unsafe { deallocate_and_next_postorder_node(node, self.alloc.clone()) }
882+
}
883+
}
884+
}
885+
}
886+
/// Deallocates `node` and returns the next node in postorder traversal
887+
///
888+
/// # Safety
889+
///
890+
/// The node must be initialized, all kvs in node must have already
891+
/// been dropped or moved out and its children must have already been deallocated.
892+
/// Also the node can't be touched anymore.
893+
unsafe fn deallocate_and_next_postorder_node<K, V, A: AllocatorClone>(
894+
node: NodeRef<marker::Dying, K, V, marker::LeafOrInternal>,
895+
alloc: A,
896+
) -> Option<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>> {
897+
// SAFETY: guaranteed by the caller
898+
let parent = unsafe { node.deallocate_and_ascend(alloc) }?;
899+
900+
Some(match parent.right_kv() {
901+
Ok(kv) => kv.right_edge().descend().first_leaf_edge().into_node().forget_type(),
902+
Err(last_edge) => last_edge.into_node().forget_type(),
903+
})
904+
}
905+
906+
let node = self.first_leaf_edge().into_node().forget_type();
907+
let mut guard = DropGuard { node: Some(node), alloc };
908+
loop {
909+
// SAFETY: all kvs of each node are dropped once
910+
unsafe { guard.node.as_mut().unwrap().drop_kvs() };
911+
// SAFETY: Nodes are deallocated in postorder, and each node is deallocated exactly once.
912+
if let Some(next) = unsafe {
913+
deallocate_and_next_postorder_node(guard.node.take().unwrap(), guard.alloc.clone())
914+
} {
915+
guard.node = Some(next);
916+
} else {
917+
return;
918+
}
919+
}
920+
}
921+
}

‎library/alloc/src/collections/btree/node.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,45 @@ impl<K, V> NodeRef<marker::Dying, K, V, marker::LeafOrInternal> {
429429
}
430430
ret
431431
}
432+
/// Drops all kvs in this node without deallocating the node itself
433+
///
434+
/// # Safety
435+
///
436+
/// - kvs in the node must be initialized and must not be accessed after this call.
437+
/// - No kvs in the node can be accessed through any other path while this function is running.
438+
pub(super) unsafe fn drop_kvs(&mut self) {
439+
struct DropGuard<'a, K, V> {
440+
node: &'a NodeRef<marker::Dying, K, V, marker::LeafOrInternal>,
441+
idx: usize,
442+
}
443+
impl<'a, K, V> Drop for DropGuard<'a, K, V> {
444+
fn drop(&mut self) {
445+
let len = self.node.len();
446+
for i in self.idx..len {
447+
// SAFETY: i < len and the kv has been initialized and
448+
// it won't use the i-th kv more than once.
449+
unsafe {
450+
let kv = Handle::new_kv(ptr::read(self.node), i);
451+
kv.drop_key_val();
452+
}
453+
}
454+
}
455+
}
456+
let len = self.len();
457+
for idx in 0..len {
458+
// If `kv.drop_key_val()` panics, the guard would drop
459+
// the rest and skip the panicked kv.
460+
let guard = DropGuard { node: self, idx: idx + 1 };
461+
// SAFETY: idx < len and the kv has been initialized and
462+
// it won't touch the idx-th more than once
463+
unsafe {
464+
let kv = Handle::new_kv(ptr::read(self), idx);
465+
kv.drop_key_val();
466+
}
467+
468+
core::mem::forget(guard);
469+
}
470+
}
432471
}
433472

434473
impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {

‎library/alloc/src/lib.rs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,6 @@
157157
#![feature(pin_coerce_unsized_trait)]
158158
#![feature(ptr_alignment_type)]
159159
#![feature(ptr_cast_slice)]
160-
#![feature(ptr_internals)]
161160
#![feature(ptr_metadata)]
162161
#![feature(random)]
163162
#![feature(raw_os_error_ty)]

0 commit comments

Comments
 (0)