Skip to content

Commit 0cd01aa

Browse files
committed
Auto merge of rust-lang#127969 - matthiaskrgr:rollup-nhxmwhn, r=matthiaskrgr
Rollup of 7 pull requests Successful merges: - rust-lang#112328 (Feat. adding ext that returns change_time) - rust-lang#126199 (Add `isqrt` to `NonZero<uN>`) - rust-lang#127856 (interpret: add sanity check in dyn upcast to double-check what codegen does) - rust-lang#127934 (Improve error when a compiler/library build fails in `checktools.sh`) - rust-lang#127960 (Cleanup dll/exe filename calculations in `run_make_support`) - rust-lang#127963 (Fix display of logo "border") - rust-lang#127967 (Disable run-make/split-debuginfo test for RISC-V 64) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 3811f40 + 73db4e3 commit 0cd01aa

File tree

24 files changed

+324
-313
lines changed

24 files changed

+324
-313
lines changed

compiler/rustc_const_eval/src/interpret/cast.rs

+36-5
Original file line numberDiff line numberDiff line change
@@ -401,15 +401,46 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
401401
}
402402
(ty::Dynamic(data_a, _, ty::Dyn), ty::Dynamic(data_b, _, ty::Dyn)) => {
403403
let val = self.read_immediate(src)?;
404-
if data_a.principal() == data_b.principal() {
405-
// A NOP cast that doesn't actually change anything, should be allowed even with mismatching vtables.
406-
// (But currently mismatching vtables violate the validity invariant so UB is triggered anyway.)
407-
return self.write_immediate(*val, dest);
408-
}
404+
// Take apart the old pointer, and find the dynamic type.
409405
let (old_data, old_vptr) = val.to_scalar_pair();
410406
let old_data = old_data.to_pointer(self)?;
411407
let old_vptr = old_vptr.to_pointer(self)?;
412408
let ty = self.get_ptr_vtable_ty(old_vptr, Some(data_a))?;
409+
410+
// Sanity-check that `supertrait_vtable_slot` in this type's vtable indeed produces
411+
// our destination trait.
412+
if cfg!(debug_assertions) {
413+
let vptr_entry_idx =
414+
self.tcx.supertrait_vtable_slot((src_pointee_ty, dest_pointee_ty));
415+
let vtable_entries = self.vtable_entries(data_a.principal(), ty);
416+
if let Some(entry_idx) = vptr_entry_idx {
417+
let Some(&ty::VtblEntry::TraitVPtr(upcast_trait_ref)) =
418+
vtable_entries.get(entry_idx)
419+
else {
420+
span_bug!(
421+
self.cur_span(),
422+
"invalid vtable entry index in {} -> {} upcast",
423+
src_pointee_ty,
424+
dest_pointee_ty
425+
);
426+
};
427+
let erased_trait_ref = upcast_trait_ref
428+
.map_bound(|r| ty::ExistentialTraitRef::erase_self_ty(*self.tcx, r));
429+
assert!(
430+
data_b
431+
.principal()
432+
.is_some_and(|b| self.eq_in_param_env(erased_trait_ref, b))
433+
);
434+
} else {
435+
// In this case codegen would keep using the old vtable. We don't want to do
436+
// that as it has the wrong trait. The reason codegen can do this is that
437+
// one vtable is a prefix of the other, so we double-check that.
438+
let vtable_entries_b = self.vtable_entries(data_b.principal(), ty);
439+
assert!(&vtable_entries[..vtable_entries_b.len()] == vtable_entries_b);
440+
};
441+
}
442+
443+
// Get the destination trait vtable and return that.
413444
let new_vptr = self.get_vtable_ptr(ty, data_b.principal())?;
414445
self.write_immediate(Immediate::new_dyn_trait(old_data, new_vptr, self), dest)
415446
}

compiler/rustc_const_eval/src/interpret/eval_context.rs

+30
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@ use std::cell::Cell;
22
use std::{fmt, mem};
33

44
use either::{Either, Left, Right};
5+
use rustc_infer::infer::at::ToTrace;
6+
use rustc_infer::traits::ObligationCause;
7+
use rustc_trait_selection::traits::ObligationCtxt;
58
use tracing::{debug, info, info_span, instrument, trace};
69

710
use rustc_errors::DiagCtxtHandle;
811
use rustc_hir::{self as hir, def_id::DefId, definitions::DefPathData};
912
use rustc_index::IndexVec;
13+
use rustc_infer::infer::TyCtxtInferExt;
1014
use rustc_middle::mir;
1115
use rustc_middle::mir::interpret::{
1216
CtfeProvenance, ErrorHandled, InvalidMetaKind, ReportedErrorInfo,
@@ -640,6 +644,32 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
640644
}
641645
}
642646

647+
/// Check if the two things are equal in the current param_env, using an infctx to get proper
648+
/// equality checks.
649+
pub(super) fn eq_in_param_env<T>(&self, a: T, b: T) -> bool
650+
where
651+
T: PartialEq + TypeFoldable<TyCtxt<'tcx>> + ToTrace<'tcx>,
652+
{
653+
// Fast path: compare directly.
654+
if a == b {
655+
return true;
656+
}
657+
// Slow path: spin up an inference context to check if these traits are sufficiently equal.
658+
let infcx = self.tcx.infer_ctxt().build();
659+
let ocx = ObligationCtxt::new(&infcx);
660+
let cause = ObligationCause::dummy_with_span(self.cur_span());
661+
// equate the two trait refs after normalization
662+
let a = ocx.normalize(&cause, self.param_env, a);
663+
let b = ocx.normalize(&cause, self.param_env, b);
664+
if ocx.eq(&cause, self.param_env, a, b).is_ok() {
665+
if ocx.select_all_or_error().is_empty() {
666+
// All good.
667+
return true;
668+
}
669+
}
670+
return false;
671+
}
672+
643673
/// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a
644674
/// frame which is not `#[track_caller]`. This matches the `caller_location` intrinsic,
645675
/// and is primarily intended for the panic machinery.

compiler/rustc_const_eval/src/interpret/terminator.rs

+6-11
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use std::borrow::Cow;
22

33
use either::Either;
4-
use rustc_middle::ty::TyCtxt;
54
use tracing::trace;
65

76
use rustc_middle::{
@@ -867,7 +866,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
867866
};
868867

869868
// Obtain the underlying trait we are working on, and the adjusted receiver argument.
870-
let (dyn_trait, dyn_ty, adjusted_recv) = if let ty::Dynamic(data, _, ty::DynStar) =
869+
let (trait_, dyn_ty, adjusted_recv) = if let ty::Dynamic(data, _, ty::DynStar) =
871870
receiver_place.layout.ty.kind()
872871
{
873872
let recv = self.unpack_dyn_star(&receiver_place, data)?;
@@ -898,20 +897,16 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
898897
(receiver_trait.principal(), dyn_ty, receiver_place.ptr())
899898
};
900899

901-
// Now determine the actual method to call. We can do that in two different ways and
902-
// compare them to ensure everything fits.
903-
let vtable_entries = if let Some(dyn_trait) = dyn_trait {
904-
let trait_ref = dyn_trait.with_self_ty(*self.tcx, dyn_ty);
905-
let trait_ref = self.tcx.erase_regions(trait_ref);
906-
self.tcx.vtable_entries(trait_ref)
907-
} else {
908-
TyCtxt::COMMON_VTABLE_ENTRIES
909-
};
900+
// Now determine the actual method to call. Usually we use the easy way of just
901+
// looking up the method at index `idx`.
902+
let vtable_entries = self.vtable_entries(trait_, dyn_ty);
910903
let Some(ty::VtblEntry::Method(fn_inst)) = vtable_entries.get(idx).copied() else {
911904
// FIXME(fee1-dead) these could be variants of the UB info enum instead of this
912905
throw_ub_custom!(fluent::const_eval_dyn_call_not_a_method);
913906
};
914907
trace!("Virtual call dispatches to {fn_inst:#?}");
908+
// We can also do the lookup based on `def_id` and `dyn_ty`, and check that that
909+
// produces the same result.
915910
if cfg!(debug_assertions) {
916911
let tcx = *self.tcx;
917912

compiler/rustc_const_eval/src/interpret/traits.rs

+23-25
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
1-
use rustc_infer::infer::TyCtxtInferExt;
2-
use rustc_infer::traits::ObligationCause;
31
use rustc_middle::mir::interpret::{InterpResult, Pointer};
42
use rustc_middle::ty::layout::LayoutOf;
5-
use rustc_middle::ty::{self, Ty};
3+
use rustc_middle::ty::{self, Ty, TyCtxt, VtblEntry};
64
use rustc_target::abi::{Align, Size};
7-
use rustc_trait_selection::traits::ObligationCtxt;
85
use tracing::trace;
96

107
use super::util::ensure_monomorphic_enough;
@@ -47,35 +44,36 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
4744
Ok((layout.size, layout.align.abi))
4845
}
4946

47+
pub(super) fn vtable_entries(
48+
&self,
49+
trait_: Option<ty::PolyExistentialTraitRef<'tcx>>,
50+
dyn_ty: Ty<'tcx>,
51+
) -> &'tcx [VtblEntry<'tcx>] {
52+
if let Some(trait_) = trait_ {
53+
let trait_ref = trait_.with_self_ty(*self.tcx, dyn_ty);
54+
let trait_ref = self.tcx.erase_regions(trait_ref);
55+
self.tcx.vtable_entries(trait_ref)
56+
} else {
57+
TyCtxt::COMMON_VTABLE_ENTRIES
58+
}
59+
}
60+
5061
/// Check that the given vtable trait is valid for a pointer/reference/place with the given
5162
/// expected trait type.
5263
pub(super) fn check_vtable_for_type(
5364
&self,
5465
vtable_trait: Option<ty::PolyExistentialTraitRef<'tcx>>,
5566
expected_trait: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
5667
) -> InterpResult<'tcx> {
57-
// Fast path: if they are equal, it's all fine.
58-
if expected_trait.principal() == vtable_trait {
59-
return Ok(());
60-
}
61-
if let (Some(expected_trait), Some(vtable_trait)) =
62-
(expected_trait.principal(), vtable_trait)
63-
{
64-
// Slow path: spin up an inference context to check if these traits are sufficiently equal.
65-
let infcx = self.tcx.infer_ctxt().build();
66-
let ocx = ObligationCtxt::new(&infcx);
67-
let cause = ObligationCause::dummy_with_span(self.cur_span());
68-
// equate the two trait refs after normalization
69-
let expected_trait = ocx.normalize(&cause, self.param_env, expected_trait);
70-
let vtable_trait = ocx.normalize(&cause, self.param_env, vtable_trait);
71-
if ocx.eq(&cause, self.param_env, expected_trait, vtable_trait).is_ok() {
72-
if ocx.select_all_or_error().is_empty() {
73-
// All good.
74-
return Ok(());
75-
}
76-
}
68+
let eq = match (expected_trait.principal(), vtable_trait) {
69+
(Some(a), Some(b)) => self.eq_in_param_env(a, b),
70+
(None, None) => true,
71+
_ => false,
72+
};
73+
if !eq {
74+
throw_ub!(InvalidVTableTrait { expected_trait, vtable_trait });
7775
}
78-
throw_ub!(InvalidVTableTrait { expected_trait, vtable_trait });
76+
Ok(())
7977
}
8078

8179
/// Turn a place with a `dyn Trait` type into a place with the actual dynamic type.

compiler/rustc_trait_selection/src/traits/vtable.rs

+12-8
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,9 @@ pub(crate) fn first_method_vtable_slot<'tcx>(tcx: TyCtxt<'tcx>, key: ty::TraitRe
364364
}
365365

366366
/// Given a `dyn Subtrait` and `dyn Supertrait` trait object, find the slot of
367-
/// // the trait vptr in the subtrait's vtable.
367+
/// the trait vptr in the subtrait's vtable.
368+
///
369+
/// A return value of `None` means that the original vtable can be reused.
368370
pub(crate) fn supertrait_vtable_slot<'tcx>(
369371
tcx: TyCtxt<'tcx>,
370372
key: (
@@ -373,20 +375,22 @@ pub(crate) fn supertrait_vtable_slot<'tcx>(
373375
),
374376
) -> Option<usize> {
375377
debug_assert!(!key.has_non_region_infer() && !key.has_non_region_param());
376-
377378
let (source, target) = key;
378-
let ty::Dynamic(source, _, _) = *source.kind() else {
379+
380+
// If the target principal is `None`, we can just return `None`.
381+
let ty::Dynamic(target, _, _) = *target.kind() else {
379382
bug!();
380383
};
381-
let source_principal = tcx
382-
.normalize_erasing_regions(ty::ParamEnv::reveal_all(), source.principal().unwrap())
384+
let target_principal = tcx
385+
.normalize_erasing_regions(ty::ParamEnv::reveal_all(), target.principal()?)
383386
.with_self_ty(tcx, tcx.types.trait_object_dummy_self);
384387

385-
let ty::Dynamic(target, _, _) = *target.kind() else {
388+
// Given that we have a target principal, it is a bug for there not to be a source principal.
389+
let ty::Dynamic(source, _, _) = *source.kind() else {
386390
bug!();
387391
};
388-
let target_principal = tcx
389-
.normalize_erasing_regions(ty::ParamEnv::reveal_all(), target.principal().unwrap())
392+
let source_principal = tcx
393+
.normalize_erasing_regions(ty::ParamEnv::reveal_all(), source.principal().unwrap())
390394
.with_self_ty(tcx, tcx.types.trait_object_dummy_self);
391395

392396
let vtable_segment_callback = {

library/core/src/num/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
#![stable(feature = "rust1", since = "1.0.0")]
44

55
use crate::ascii;
6-
use crate::hint;
76
use crate::intrinsics;
87
use crate::mem;
98
use crate::str::FromStr;

library/core/src/num/nonzero.rs

+54-6
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
use crate::cmp::Ordering;
44
use crate::fmt;
55
use crate::hash::{Hash, Hasher};
6+
use crate::hint;
67
use crate::intrinsics;
78
use crate::marker::{Freeze, StructuralPartialEq};
89
use crate::ops::{BitOr, BitOrAssign, Div, DivAssign, Neg, Rem, RemAssign};
@@ -604,7 +605,6 @@ macro_rules! nonzero_integer {
604605
}
605606

606607
nonzero_integer_signedness_dependent_methods! {
607-
Self = $Ty,
608608
Primitive = $signedness $Int,
609609
UnsignedPrimitive = $Uint,
610610
}
@@ -823,7 +823,7 @@ macro_rules! nonzero_integer {
823823
}
824824
}
825825

826-
nonzero_integer_signedness_dependent_impls!($Ty $signedness $Int);
826+
nonzero_integer_signedness_dependent_impls!($signedness $Int);
827827
};
828828

829829
(Self = $Ty:ident, Primitive = unsigned $Int:ident $(,)?) => {
@@ -849,7 +849,7 @@ macro_rules! nonzero_integer {
849849

850850
macro_rules! nonzero_integer_signedness_dependent_impls {
851851
// Impls for unsigned nonzero types only.
852-
($Ty:ident unsigned $Int:ty) => {
852+
(unsigned $Int:ty) => {
853853
#[stable(feature = "nonzero_div", since = "1.51.0")]
854854
impl Div<NonZero<$Int>> for $Int {
855855
type Output = $Int;
@@ -897,7 +897,7 @@ macro_rules! nonzero_integer_signedness_dependent_impls {
897897
}
898898
};
899899
// Impls for signed nonzero types only.
900-
($Ty:ident signed $Int:ty) => {
900+
(signed $Int:ty) => {
901901
#[stable(feature = "signed_nonzero_neg", since = "1.71.0")]
902902
impl Neg for NonZero<$Int> {
903903
type Output = Self;
@@ -918,7 +918,6 @@ macro_rules! nonzero_integer_signedness_dependent_impls {
918918
macro_rules! nonzero_integer_signedness_dependent_methods {
919919
// Associated items for unsigned nonzero types only.
920920
(
921-
Self = $Ty:ident,
922921
Primitive = unsigned $Int:ident,
923922
UnsignedPrimitive = $Uint:ty,
924923
) => {
@@ -1224,11 +1223,60 @@ macro_rules! nonzero_integer_signedness_dependent_methods {
12241223

12251224
intrinsics::ctpop(self.get()) < 2
12261225
}
1226+
1227+
/// Returns the square root of the number, rounded down.
1228+
///
1229+
/// # Examples
1230+
///
1231+
/// Basic usage:
1232+
/// ```
1233+
/// #![feature(isqrt)]
1234+
/// # use std::num::NonZero;
1235+
/// #
1236+
/// # fn main() { test().unwrap(); }
1237+
/// # fn test() -> Option<()> {
1238+
#[doc = concat!("let ten = NonZero::new(10", stringify!($Int), ")?;")]
1239+
#[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1240+
///
1241+
/// assert_eq!(ten.isqrt(), three);
1242+
/// # Some(())
1243+
/// # }
1244+
#[unstable(feature = "isqrt", issue = "116226")]
1245+
#[rustc_const_unstable(feature = "isqrt", issue = "116226")]
1246+
#[must_use = "this returns the result of the operation, \
1247+
without modifying the original"]
1248+
#[inline]
1249+
pub const fn isqrt(self) -> Self {
1250+
// The algorithm is based on the one presented in
1251+
// <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)>
1252+
// which cites as source the following C code:
1253+
// <https://web.archive.org/web/20120306040058/http://medialab.freaknet.org/martin/src/sqrt/sqrt.c>.
1254+
1255+
let mut op = self.get();
1256+
let mut res = 0;
1257+
let mut one = 1 << (self.ilog2() & !1);
1258+
1259+
while one != 0 {
1260+
if op >= res + one {
1261+
op -= res + one;
1262+
res = (res >> 1) + one;
1263+
} else {
1264+
res >>= 1;
1265+
}
1266+
one >>= 2;
1267+
}
1268+
1269+
// SAFETY: The result fits in an integer with half as many bits.
1270+
// Inform the optimizer about it.
1271+
unsafe { hint::assert_unchecked(res < 1 << (Self::BITS / 2)) };
1272+
1273+
// SAFETY: The square root of an integer >= 1 is always >= 1.
1274+
unsafe { Self::new_unchecked(res) }
1275+
}
12271276
};
12281277

12291278
// Associated items for signed nonzero types only.
12301279
(
1231-
Self = $Ty:ident,
12321280
Primitive = signed $Int:ident,
12331281
UnsignedPrimitive = $Uint:ty,
12341282
) => {

0 commit comments

Comments
 (0)