Skip to content

Commit 5d26903

Browse files
authored
Rollup merge of rust-lang#73398 - oli-obk:const_raw_ptr_cmp, r=varkor,RalfJung,nagisa
A way forward for pointer equality in const eval r? @varkor on the first commit and @RalfJung on the second commit cc rust-lang#53020
2 parents 6f62d83 + e465b22 commit 5d26903

39 files changed

+358
-201
lines changed

src/liballoc/raw_vec.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ impl<T> RawVec<T, Global> {
6060
/// `#[rustc_force_min_const_fn]` attribute which requires conformance
6161
/// with `min_const_fn` but does not necessarily allow calling it in
6262
/// `stable(...) const fn` / user code not enabling `foo` when
63-
/// `#[rustc_const_unstable(feature = "foo", ..)]` is present.
63+
/// `#[rustc_const_unstable(feature = "foo", issue = "01234")]` is present.
6464
pub const NEW: Self = Self::new();
6565

6666
/// Creates the biggest possible `RawVec` (on the system heap)

src/libcore/intrinsics.rs

+13-3
Original file line numberDiff line numberDiff line change
@@ -1012,7 +1012,7 @@ extern "rust-intrinsic" {
10121012
///
10131013
/// The stabilized version of this intrinsic is
10141014
/// [`std::any::type_name`](../../std/any/fn.type_name.html)
1015-
#[rustc_const_unstable(feature = "const_type_name", issue = "none")]
1015+
#[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
10161016
pub fn type_name<T: ?Sized>() -> &'static str;
10171017

10181018
/// Gets an identifier which is globally unique to the specified type. This
@@ -1021,7 +1021,7 @@ extern "rust-intrinsic" {
10211021
///
10221022
/// The stabilized version of this intrinsic is
10231023
/// [`std::any::TypeId::of`](../../std/any/struct.TypeId.html#method.of)
1024-
#[rustc_const_unstable(feature = "const_type_id", issue = "none")]
1024+
#[rustc_const_unstable(feature = "const_type_id", issue = "41875")]
10251025
pub fn type_id<T: ?Sized + 'static>() -> u64;
10261026

10271027
/// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited:
@@ -1931,7 +1931,7 @@ extern "rust-intrinsic" {
19311931
pub fn nontemporal_store<T>(ptr: *mut T, val: T);
19321932

19331933
/// See documentation of `<*const T>::offset_from` for details.
1934-
#[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "none")]
1934+
#[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
19351935
pub fn ptr_offset_from<T>(ptr: *const T, base: *const T) -> isize;
19361936

19371937
/// Internal hook used by Miri to implement unwinding.
@@ -1948,6 +1948,16 @@ extern "rust-intrinsic" {
19481948
#[cfg(not(bootstrap))]
19491949
#[lang = "count_code_region"]
19501950
pub fn count_code_region(index: u32);
1951+
1952+
/// See documentation of `<*const T>::guaranteed_eq` for details.
1953+
#[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
1954+
#[cfg(not(bootstrap))]
1955+
pub fn ptr_guaranteed_eq<T>(ptr: *const T, other: *const T) -> bool;
1956+
1957+
/// See documentation of `<*const T>::guaranteed_ne` for details.
1958+
#[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
1959+
#[cfg(not(bootstrap))]
1960+
pub fn ptr_guaranteed_ne<T>(ptr: *const T, other: *const T) -> bool;
19511961
}
19521962

19531963
// Some functions are defined here because they accidentally got made

src/libcore/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@
8787
#![feature(const_generics)]
8888
#![feature(const_ptr_offset)]
8989
#![feature(const_ptr_offset_from)]
90+
#![cfg_attr(not(bootstrap), feature(const_raw_ptr_comparison))]
9091
#![feature(const_result)]
9192
#![feature(const_slice_from_raw_parts)]
9293
#![feature(const_slice_ptr_len)]

src/libcore/ptr/const_ptr.rs

+66
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,72 @@ impl<T: ?Sized> *const T {
295295
intrinsics::ptr_offset_from(self, origin)
296296
}
297297

298+
/// Returns whether two pointers are guaranteed to be equal.
299+
///
300+
/// At runtime this function behaves like `self == other`.
301+
/// However, in some contexts (e.g., compile-time evaluation),
302+
/// it is not always possible to determine equality of two pointers, so this function may
303+
/// spuriously return `false` for pointers that later actually turn out to be equal.
304+
/// But when it returns `true`, the pointers are guaranteed to be equal.
305+
///
306+
/// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
307+
/// comparisons for which both functions return `false`.
308+
///
309+
/// [`guaranteed_ne`]: #method.guaranteed_ne
310+
///
311+
/// The return value may change depending on the compiler version and unsafe code may not
312+
/// rely on the result of this function for soundness. It is suggested to only use this function
313+
/// for performance optimizations where spurious `false` return values by this function do not
314+
/// affect the outcome, but just the performance.
315+
/// The consequences of using this method to make runtime and compile-time code behave
316+
/// differently have not been explored. This method should not be used to introduce such
317+
/// differences, and it should also not be stabilized before we have a better understanding
318+
/// of this issue.
319+
/// ```
320+
#[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
321+
#[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
322+
#[inline]
323+
#[cfg(not(bootstrap))]
324+
pub const fn guaranteed_eq(self, other: *const T) -> bool
325+
where
326+
T: Sized,
327+
{
328+
intrinsics::ptr_guaranteed_eq(self, other)
329+
}
330+
331+
/// Returns whether two pointers are guaranteed to be inequal.
332+
///
333+
/// At runtime this function behaves like `self != other`.
334+
/// However, in some contexts (e.g., compile-time evaluation),
335+
/// it is not always possible to determine the inequality of two pointers, so this function may
336+
/// spuriously return `false` for pointers that later actually turn out to be inequal.
337+
/// But when it returns `true`, the pointers are guaranteed to be inequal.
338+
///
339+
/// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
340+
/// comparisons for which both functions return `false`.
341+
///
342+
/// [`guaranteed_eq`]: #method.guaranteed_eq
343+
///
344+
/// The return value may change depending on the compiler version and unsafe code may not
345+
/// rely on the result of this function for soundness. It is suggested to only use this function
346+
/// for performance optimizations where spurious `false` return values by this function do not
347+
/// affect the outcome, but just the performance.
348+
/// The consequences of using this method to make runtime and compile-time code behave
349+
/// differently have not been explored. This method should not be used to introduce such
350+
/// differences, and it should also not be stabilized before we have a better understanding
351+
/// of this issue.
352+
/// ```
353+
#[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
354+
#[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
355+
#[inline]
356+
#[cfg(not(bootstrap))]
357+
pub const fn guaranteed_ne(self, other: *const T) -> bool
358+
where
359+
T: Sized,
360+
{
361+
intrinsics::ptr_guaranteed_ne(self, other)
362+
}
363+
298364
/// Calculates the distance between two pointers. The returned value is in
299365
/// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
300366
///

src/libcore/ptr/mut_ptr.rs

+66
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,72 @@ impl<T: ?Sized> *mut T {
273273
if self.is_null() { None } else { Some(&mut *self) }
274274
}
275275

276+
/// Returns whether two pointers are guaranteed to be equal.
277+
///
278+
/// At runtime this function behaves like `self == other`.
279+
/// However, in some contexts (e.g., compile-time evaluation),
280+
/// it is not always possible to determine equality of two pointers, so this function may
281+
/// spuriously return `false` for pointers that later actually turn out to be equal.
282+
/// But when it returns `true`, the pointers are guaranteed to be equal.
283+
///
284+
/// This function is the mirror of [`guaranteed_ne`], but not its inverse. There are pointer
285+
/// comparisons for which both functions return `false`.
286+
///
287+
/// [`guaranteed_ne`]: #method.guaranteed_ne
288+
///
289+
/// The return value may change depending on the compiler version and unsafe code may not
290+
/// rely on the result of this function for soundness. It is suggested to only use this function
291+
/// for performance optimizations where spurious `false` return values by this function do not
292+
/// affect the outcome, but just the performance.
293+
/// The consequences of using this method to make runtime and compile-time code behave
294+
/// differently have not been explored. This method should not be used to introduce such
295+
/// differences, and it should also not be stabilized before we have a better understanding
296+
/// of this issue.
297+
/// ```
298+
#[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
299+
#[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
300+
#[inline]
301+
#[cfg(not(bootstrap))]
302+
pub const fn guaranteed_eq(self, other: *mut T) -> bool
303+
where
304+
T: Sized,
305+
{
306+
intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _)
307+
}
308+
309+
/// Returns whether two pointers are guaranteed to be inequal.
310+
///
311+
/// At runtime this function behaves like `self != other`.
312+
/// However, in some contexts (e.g., compile-time evaluation),
313+
/// it is not always possible to determine the inequality of two pointers, so this function may
314+
/// spuriously return `false` for pointers that later actually turn out to be inequal.
315+
/// But when it returns `true`, the pointers are guaranteed to be inequal.
316+
///
317+
/// This function is the mirror of [`guaranteed_eq`], but not its inverse. There are pointer
318+
/// comparisons for which both functions return `false`.
319+
///
320+
/// [`guaranteed_eq`]: #method.guaranteed_eq
321+
///
322+
/// The return value may change depending on the compiler version and unsafe code may not
323+
/// rely on the result of this function for soundness. It is suggested to only use this function
324+
/// for performance optimizations where spurious `false` return values by this function do not
325+
/// affect the outcome, but just the performance.
326+
/// The consequences of using this method to make runtime and compile-time code behave
327+
/// differently have not been explored. This method should not be used to introduce such
328+
/// differences, and it should also not be stabilized before we have a better understanding
329+
/// of this issue.
330+
/// ```
331+
#[unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
332+
#[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
333+
#[inline]
334+
#[cfg(not(bootstrap))]
335+
pub const unsafe fn guaranteed_ne(self, other: *mut T) -> bool
336+
where
337+
T: Sized,
338+
{
339+
intrinsics::ptr_guaranteed_ne(self as *const _, other as *const _)
340+
}
341+
276342
/// Calculates the distance between two pointers. The returned value is in
277343
/// units of T: the distance in bytes is divided by `mem::size_of::<T>()`.
278344
///

src/libcore/slice/mod.rs

+17
Original file line numberDiff line numberDiff line change
@@ -5956,10 +5956,18 @@ where
59565956
return false;
59575957
}
59585958

5959+
#[cfg(bootstrap)]
59595960
if self.as_ptr() == other.as_ptr() {
59605961
return true;
59615962
}
59625963

5964+
// While performance would suffer if `guaranteed_eq` just returned `false`
5965+
// for all arguments, correctness and return value of this function are not affected.
5966+
#[cfg(not(bootstrap))]
5967+
if self.as_ptr().guaranteed_eq(other.as_ptr()) {
5968+
return true;
5969+
}
5970+
59635971
self.iter().zip(other.iter()).all(|(x, y)| x == y)
59645972
}
59655973
}
@@ -5973,9 +5981,18 @@ where
59735981
if self.len() != other.len() {
59745982
return false;
59755983
}
5984+
5985+
#[cfg(bootstrap)]
59765986
if self.as_ptr() == other.as_ptr() {
59775987
return true;
59785988
}
5989+
5990+
// While performance would suffer if `guaranteed_eq` just returned `false`
5991+
// for all arguments, correctness and return value of this function are not affected.
5992+
#[cfg(not(bootstrap))]
5993+
if self.as_ptr().guaranteed_eq(other.as_ptr()) {
5994+
return true;
5995+
}
59795996
unsafe {
59805997
let size = mem::size_of_val(self);
59815998
memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0

src/librustc_codegen_llvm/intrinsic.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use log::debug;
1212
use rustc_ast::ast;
1313
use rustc_codegen_ssa::base::{compare_simd_types, to_immediate, wants_msvc_seh};
1414
use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
15-
use rustc_codegen_ssa::common::TypeKind;
15+
use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
1616
use rustc_codegen_ssa::glue;
1717
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
1818
use rustc_codegen_ssa::mir::place::PlaceRef;
@@ -731,6 +731,16 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
731731
return;
732732
}
733733

734+
"ptr_guaranteed_eq" | "ptr_guaranteed_ne" => {
735+
let a = args[0].immediate();
736+
let b = args[1].immediate();
737+
if name == "ptr_guaranteed_eq" {
738+
self.icmp(IntPredicate::IntEQ, a, b)
739+
} else {
740+
self.icmp(IntPredicate::IntNE, a, b)
741+
}
742+
}
743+
734744
"ptr_offset_from" => {
735745
let ty = substs.type_at(0);
736746
let pointee_size = self.size_of(ty);

src/librustc_feature/active.rs

-3
Original file line numberDiff line numberDiff line change
@@ -401,9 +401,6 @@ declare_features! (
401401
/// Allows dereferencing raw pointers during const eval.
402402
(active, const_raw_ptr_deref, "1.27.0", Some(51911), None),
403403

404-
/// Allows comparing raw pointers during const eval.
405-
(active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
406-
407404
/// Allows `#[doc(alias = "...")]`.
408405
(active, doc_alias, "1.27.0", Some(50146), None),
409406

src/librustc_feature/removed.rs

+5
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,11 @@ declare_features! (
113113
Some("removed in favor of `#![feature(marker_trait_attr)]`")),
114114
/// Allows `#[no_debug]`.
115115
(removed, no_debug, "1.43.0", Some(29721), None, Some("removed due to lack of demand")),
116+
117+
/// Allows comparing raw pointers during const eval.
118+
(removed, const_compare_raw_pointers, "1.46.0", Some(53020), None,
119+
Some("cannot be allowed in const eval in any meaningful way")),
120+
116121
// -------------------------------------------------------------------------
117122
// feature-group-end: removed features
118123
// -------------------------------------------------------------------------

src/librustc_mir/interpret/intrinsics.rs

+5
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,11 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
291291
let offset_ptr = ptr.ptr_wrapping_signed_offset(offset_bytes, self);
292292
self.write_scalar(offset_ptr, dest)?;
293293
}
294+
sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
295+
// FIXME: return `true` for at least some comparisons where we can reliably
296+
// determine the result of runtime (in)equality tests at compile-time.
297+
self.write_scalar(Scalar::from_bool(false), dest)?;
298+
}
294299
sym::ptr_offset_from => {
295300
let a = self.read_immediate(args[0])?.to_scalar()?;
296301
let b = self.read_immediate(args[1])?.to_scalar()?;

src/librustc_mir/transform/check_consts/ops.rs

+9-11
Original file line numberDiff line numberDiff line change
@@ -296,18 +296,16 @@ impl NonConstOp for Panic {
296296
#[derive(Debug)]
297297
pub struct RawPtrComparison;
298298
impl NonConstOp for RawPtrComparison {
299-
fn feature_gate() -> Option<Symbol> {
300-
Some(sym::const_compare_raw_pointers)
301-
}
302-
303299
fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
304-
feature_err(
305-
&ccx.tcx.sess.parse_sess,
306-
sym::const_compare_raw_pointers,
307-
span,
308-
&format!("comparing raw pointers inside {}", ccx.const_kind()),
309-
)
310-
.emit();
300+
let mut err = ccx
301+
.tcx
302+
.sess
303+
.struct_span_err(span, "pointers cannot be reliably compared during const eval.");
304+
err.note(
305+
"see issue #53020 <https://github.com/rust-lang/rust/issues/53020> \
306+
for more information",
307+
);
308+
err.emit();
311309
}
312310
}
313311

src/librustc_mir/transform/check_unsafety.rs

-15
Original file line numberDiff line numberDiff line change
@@ -171,21 +171,6 @@ impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
171171
_ => {}
172172
}
173173
}
174-
// raw pointer and fn pointer operations are unsafe as it is not clear whether one
175-
// pointer would be "less" or "equal" to another, because we cannot know where llvm
176-
// or the linker will place various statics in memory. Without this information the
177-
// result of a comparison of addresses would differ between runtime and compile-time.
178-
Rvalue::BinaryOp(_, ref lhs, _)
179-
if self.const_context && self.tcx.features().const_compare_raw_pointers =>
180-
{
181-
if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
182-
self.require_unsafe(
183-
"pointer operation",
184-
"operations on pointers in constants",
185-
UnsafetyViolationKind::General,
186-
);
187-
}
188-
}
189174
_ => {}
190175
}
191176
self.super_rvalue(rvalue, location);

src/librustc_span/symbol.rs

+2
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,8 @@ symbols! {
588588
proc_macro_non_items,
589589
proc_macro_path_invoc,
590590
profiler_runtime,
591+
ptr_guaranteed_eq,
592+
ptr_guaranteed_ne,
591593
ptr_offset_from,
592594
pub_restricted,
593595
pure,

src/librustc_typeck/check/intrinsic.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,8 @@ pub fn intrinsic_operation_unsafety(intrinsic: &str) -> hir::Unsafety {
7474
| "wrapping_add" | "wrapping_sub" | "wrapping_mul" | "saturating_add"
7575
| "saturating_sub" | "rotate_left" | "rotate_right" | "ctpop" | "ctlz" | "cttz"
7676
| "bswap" | "bitreverse" | "discriminant_value" | "type_id" | "likely" | "unlikely"
77-
| "minnumf32" | "minnumf64" | "maxnumf32" | "maxnumf64" | "type_name" => {
78-
hir::Unsafety::Normal
79-
}
77+
| "ptr_guaranteed_eq" | "ptr_guaranteed_ne" | "minnumf32" | "minnumf64" | "maxnumf32"
78+
| "maxnumf64" | "type_name" => hir::Unsafety::Normal,
8079
_ => hir::Unsafety::Unsafe,
8180
}
8281
}
@@ -258,6 +257,10 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
258257
(1, vec![param(0), param(0)], tcx.intern_tup(&[param(0), tcx.types.bool]))
259258
}
260259

260+
"ptr_guaranteed_eq" | "ptr_guaranteed_ne" => {
261+
(1, vec![tcx.mk_imm_ptr(param(0)), tcx.mk_imm_ptr(param(0))], tcx.types.bool)
262+
}
263+
261264
"ptr_offset_from" => {
262265
(1, vec![tcx.mk_imm_ptr(param(0)), tcx.mk_imm_ptr(param(0))], tcx.types.isize)
263266
}

0 commit comments

Comments
 (0)