Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use addr_of! #121556

Merged
merged 2 commits into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/back/archive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ fn get_llvm_object_symbols(
llvm::LLVMRustGetSymbols(
buf.as_ptr(),
buf.len(),
&mut *state as *mut &mut _ as *mut c_void,
std::ptr::addr_of_mut!(*state) as *mut c_void,
callback,
error_callback,
)
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_llvm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ impl WriteBackendMethods for LlvmCodegenBackend {
fn print_pass_timings(&self) {
unsafe {
let mut size = 0;
let cstr = llvm::LLVMRustPrintPassTimings(&mut size as *mut usize);
let cstr = llvm::LLVMRustPrintPassTimings(std::ptr::addr_of_mut!(size));
if cstr.is_null() {
println!("failed to get pass timings");
} else {
Expand All @@ -182,7 +182,7 @@ impl WriteBackendMethods for LlvmCodegenBackend {
fn print_statistics(&self) {
unsafe {
let mut size = 0;
let cstr = llvm::LLVMRustPrintStatistics(&mut size as *mut usize);
let cstr = llvm::LLVMRustPrintStatistics(std::ptr::addr_of_mut!(size));
if cstr.is_null() {
println!("failed to get pass stats");
} else {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/llvm_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ pub(crate) fn print(req: &PrintRequest, mut out: &mut dyn PrintBackendInfo, sess
&tm,
cpu_cstring.as_ptr(),
callback,
&mut out as *mut &mut dyn PrintBackendInfo as *mut c_void,
std::ptr::addr_of_mut!(out) as *mut c_void,
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_data_structures/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ impl<T> RwLock<T> {
#[inline(always)]
pub fn leak(&self) -> &T {
let guard = self.read();
let ret = unsafe { &*(&*guard as *const T) };
let ret = unsafe { &*std::ptr::addr_of!(*guard) };
std::mem::forget(guard);
ret
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/query/on_disk_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ impl<'sess> OnDiskCache<'sess> {

for (index, file) in files.iter().enumerate() {
let index = SourceFileIndex(index as u32);
let file_ptr: *const SourceFile = &**file as *const _;
let file_ptr: *const SourceFile = std::ptr::addr_of!(**file);
file_to_file_index.insert(file_ptr, index);
let source_file_id = EncodedSourceFileId::new(tcx, file);
file_index_to_stable_id.insert(index, source_file_id);
Expand Down Expand Up @@ -835,7 +835,7 @@ pub struct CacheEncoder<'a, 'tcx> {
impl<'a, 'tcx> CacheEncoder<'a, 'tcx> {
#[inline]
fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
self.file_to_file_index[&(&*source_file as *const SourceFile)]
self.file_to_file_index[&std::ptr::addr_of!(*source_file)]
}

/// Encode something with additional information that allows to do some
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl<T> List<T> {
// length) that is 64-byte aligned, thus featuring the necessary
// trailing padding for elements with up to 64-byte alignment.
static EMPTY_SLICE: InOrder<usize, MaxAlign> = InOrder(0, MaxAlign);
unsafe { &*(&EMPTY_SLICE as *const _ as *const List<T>) }
unsafe { &*(std::ptr::addr_of!(EMPTY_SLICE) as *const List<T>) }
}

pub fn len(&self) -> usize {
Expand Down
2 changes: 1 addition & 1 deletion compiler/stable_mir/src/compiler_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ where
if TLV.is_set() {
Err(Error::from("StableMIR already running"))
} else {
let ptr: *const () = &context as *const &_ as _;
let ptr: *const () = std::ptr::addr_of!(context) as _;
TLV.set(&Cell::new(ptr), || Ok(f()))
}
}
Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/boxed/thin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ impl<T: ?Sized> ThinBox<T> {

fn with_header(&self) -> &WithHeader<<T as Pointee>::Metadata> {
// SAFETY: both types are transparent to `NonNull<u8>`
unsafe { &*((&self.ptr) as *const WithOpaqueHeader as *const WithHeader<_>) }
unsafe { &*(core::ptr::addr_of!(self.ptr) as *const WithHeader<_>) }
}
}

Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1969,7 +1969,7 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> {

// Copy value as bytes
ptr::copy_nonoverlapping(
&*src as *const T as *const u8,
core::ptr::addr_of!(*src) as *const u8,
ptr::addr_of_mut!((*ptr).value) as *mut u8,
value_size,
);
Expand Down Expand Up @@ -2440,7 +2440,7 @@ impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for Rc<T, A> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized, A: Allocator> fmt::Pointer for Rc<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Pointer::fmt(&(&**self as *const T), f)
fmt::Pointer::fmt(&core::ptr::addr_of!(**self), f)
}
}

Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1914,7 +1914,7 @@ impl<T: ?Sized, A: Allocator> Arc<T, A> {

// Copy value as bytes
ptr::copy_nonoverlapping(
&*src as *const T as *const u8,
core::ptr::addr_of!(*src) as *const u8,
ptr::addr_of_mut!((*ptr).data) as *mut u8,
value_size,
);
Expand Down Expand Up @@ -3265,7 +3265,7 @@ impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for Arc<T, A> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized, A: Allocator> fmt::Pointer for Arc<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Pointer::fmt(&(&**self as *const T), f)
fmt::Pointer::fmt(&core::ptr::addr_of!(**self), f)
}
}

Expand Down
3 changes: 2 additions & 1 deletion library/core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::ffi::c_char;
use crate::fmt;
use crate::intrinsics;
use crate::ops;
use crate::ptr::addr_of;
use crate::slice;
use crate::slice::memchr;
use crate::str;
Expand Down Expand Up @@ -603,7 +604,7 @@ impl CStr {
pub const fn to_bytes_with_nul(&self) -> &[u8] {
// SAFETY: Transmuting a slice of `c_char`s to a slice of `u8`s
// is safe on all supported targets.
unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
unsafe { &*(addr_of!(self.inner) as *const [u8]) }
}

/// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
Expand Down
6 changes: 3 additions & 3 deletions library/core/src/iter/adapters/filter_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedF
use crate::mem::{ManuallyDrop, MaybeUninit};
use crate::num::NonZero;
use crate::ops::{ControlFlow, Try};
use crate::ptr::addr_of;
use crate::{array, fmt};

/// An iterator that uses `f` to both filter and map elements from `iter`.
Expand Down Expand Up @@ -98,9 +99,8 @@ where
// SAFETY: Loop conditions ensure the index is in bounds.

unsafe {
let opt_payload_at: *const MaybeUninit<B> = (&val as *const Option<B>)
.byte_add(core::mem::offset_of!(Option<B>, Some.0))
.cast();
let opt_payload_at: *const MaybeUninit<B> =
addr_of!(val).byte_add(core::mem::offset_of!(Option<B>, Some.0)).cast();
let dst = guard.array.as_mut_ptr().add(idx);
crate::ptr::copy_nonoverlapping(opt_payload_at, dst, 1);
crate::mem::forget(val);
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/ptr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1553,7 +1553,7 @@ pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
// `dst` cannot overlap `src` because the caller has mutable access
// to `dst` while `src` is owned by this function.
unsafe {
copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::<T>());
copy_nonoverlapping(addr_of!(src) as *const u8, dst as *mut u8, mem::size_of::<T>());
// We are calling the intrinsic directly to avoid function calls in the generated code.
intrinsics::forget(src);
}
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/os/unix/net/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ mod libc {
fn sun_path_offset(addr: &libc::sockaddr_un) -> usize {
// Work with an actual instance of the type since using a null pointer is UB
let base = (addr as *const libc::sockaddr_un).addr();
let path = (&addr.sun_path as *const libc::c_char).addr();
let path = core::ptr::addr_of!(addr.sun_path).addr();
path - base
}

Expand Down Expand Up @@ -98,7 +98,7 @@ impl SocketAddr {
unsafe {
let mut addr: libc::sockaddr_un = mem::zeroed();
let mut len = mem::size_of::<libc::sockaddr_un>() as libc::socklen_t;
cvt(f(&mut addr as *mut _ as *mut _, &mut len))?;
cvt(f(core::ptr::addr_of_mut!(addr) as *mut _, &mut len))?;
SocketAddr::from_parts(addr, len)
}
}
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/os/unix/net/ancillary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub(super) fn recv_vectored_with_ancillary_from(
unsafe {
let mut msg_name: libc::sockaddr_un = zeroed();
let mut msg: libc::msghdr = zeroed();
msg.msg_name = &mut msg_name as *mut _ as *mut _;
msg.msg_name = core::ptr::addr_of_mut!(msg_name) as *mut _;
msg.msg_namelen = size_of::<libc::sockaddr_un>() as libc::socklen_t;
msg.msg_iov = bufs.as_mut_ptr().cast();
msg.msg_iovlen = bufs.len() as _;
Expand Down Expand Up @@ -70,7 +70,7 @@ pub(super) fn send_vectored_with_ancillary_to(
if let Some(path) = path { sockaddr_un(path)? } else { (zeroed(), 0) };

let mut msg: libc::msghdr = zeroed();
msg.msg_name = &mut msg_name as *mut _ as *mut _;
msg.msg_name = core::ptr::addr_of_mut!(msg_name) as *mut _;
msg.msg_namelen = msg_namelen;
msg.msg_iov = bufs.as_ptr() as *mut _;
msg.msg_iovlen = bufs.len() as _;
Expand Down
12 changes: 6 additions & 6 deletions library/std/src/os/unix/net/datagram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl UnixDatagram {
let socket = UnixDatagram::unbound()?;
let (addr, len) = sockaddr_un(path.as_ref())?;

cvt(libc::bind(socket.as_raw_fd(), &addr as *const _ as *const _, len as _))?;
cvt(libc::bind(socket.as_raw_fd(), core::ptr::addr_of!(addr) as *const _, len as _))?;

Ok(socket)
}
Expand Down Expand Up @@ -124,7 +124,7 @@ impl UnixDatagram {
let socket = UnixDatagram::unbound()?;
cvt(libc::bind(
socket.as_raw_fd(),
&socket_addr.addr as *const _ as *const _,
core::ptr::addr_of!(socket_addr.addr) as *const _,
socket_addr.len as _,
))?;
Ok(socket)
Expand Down Expand Up @@ -206,7 +206,7 @@ impl UnixDatagram {
unsafe {
let (addr, len) = sockaddr_un(path.as_ref())?;

cvt(libc::connect(self.as_raw_fd(), &addr as *const _ as *const _, len))?;
cvt(libc::connect(self.as_raw_fd(), core::ptr::addr_of!(addr) as *const _, len))?;
}
Ok(())
}
Expand Down Expand Up @@ -238,7 +238,7 @@ impl UnixDatagram {
unsafe {
cvt(libc::connect(
self.as_raw_fd(),
&socket_addr.addr as *const _ as *const _,
core::ptr::addr_of!(socket_addr.addr) as *const _,
socket_addr.len,
))?;
}
Expand Down Expand Up @@ -505,7 +505,7 @@ impl UnixDatagram {
buf.as_ptr() as *const _,
buf.len(),
MSG_NOSIGNAL,
&addr as *const _ as *const _,
core::ptr::addr_of!(addr) as *const _,
len,
))?;
Ok(count as usize)
Expand Down Expand Up @@ -540,7 +540,7 @@ impl UnixDatagram {
buf.as_ptr() as *const _,
buf.len(),
MSG_NOSIGNAL,
&socket_addr.addr as *const _ as *const _,
core::ptr::addr_of!(socket_addr.addr) as *const _,
socket_addr.len,
))?;
Ok(count as usize)
Expand Down
10 changes: 7 additions & 3 deletions library/std/src/os/unix/net/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ impl UnixListener {
)))]
const backlog: libc::c_int = libc::SOMAXCONN;

cvt(libc::bind(inner.as_inner().as_raw_fd(), &addr as *const _ as *const _, len as _))?;
cvt(libc::bind(
inner.as_inner().as_raw_fd(),
core::ptr::addr_of!(addr) as *const _,
len as _,
))?;
cvt(libc::listen(inner.as_inner().as_raw_fd(), backlog))?;

Ok(UnixListener(inner))
Expand Down Expand Up @@ -139,7 +143,7 @@ impl UnixListener {
const backlog: libc::c_int = 128;
cvt(libc::bind(
inner.as_raw_fd(),
&socket_addr.addr as *const _ as *const _,
core::ptr::addr_of!(socket_addr.addr) as *const _,
socket_addr.len as _,
))?;
cvt(libc::listen(inner.as_raw_fd(), backlog))?;
Expand Down Expand Up @@ -174,7 +178,7 @@ impl UnixListener {
pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
let mut len = mem::size_of_val(&storage) as libc::socklen_t;
let sock = self.0.accept(&mut storage as *mut _ as *mut _, &mut len)?;
let sock = self.0.accept(core::ptr::addr_of_mut!(storage) as *mut _, &mut len)?;
let addr = SocketAddr::from_parts(storage, len)?;
Ok((UnixStream(sock), addr))
}
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/os/unix/net/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ impl UnixStream {
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
let (addr, len) = sockaddr_un(path.as_ref())?;

cvt(libc::connect(inner.as_raw_fd(), &addr as *const _ as *const _, len))?;
cvt(libc::connect(inner.as_raw_fd(), core::ptr::addr_of!(addr) as *const _, len))?;
Ok(UnixStream(inner))
}
}
Expand Down Expand Up @@ -130,7 +130,7 @@ impl UnixStream {
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
cvt(libc::connect(
inner.as_raw_fd(),
&socket_addr.addr as *const _ as *const _,
core::ptr::addr_of!(socket_addr.addr) as *const _,
socket_addr.len,
))?;
Ok(UnixStream(inner))
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/os/unix/ucred.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ pub mod impl_linux {
socket.as_raw_fd(),
SOL_SOCKET,
SO_PEERCRED,
&mut ucred as *mut ucred as *mut c_void,
core::ptr::addr_of_mut!(ucred) as *mut c_void,
&mut ucred_size,
);

Expand Down Expand Up @@ -122,7 +122,7 @@ pub mod impl_mac {
socket.as_raw_fd(),
SOL_LOCAL,
LOCAL_PEERPID,
&mut pid as *mut pid_t as *mut c_void,
core::ptr::addr_of_mut!(pid) as *mut c_void,
&mut pid_size,
);

Expand Down
2 changes: 1 addition & 1 deletion library/std/src/panicking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>>
// method of calling a catch panic whilst juggling ownership.
let mut data = Data { f: ManuallyDrop::new(f) };

let data_ptr = &mut data as *mut _ as *mut u8;
let data_ptr = core::ptr::addr_of_mut!(data) as *mut u8;
// SAFETY:
//
// Access to the union's fields: this is `std` and we know that the `r#try`
Expand Down
8 changes: 6 additions & 2 deletions library/std/src/sync/mpmc/zero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,11 @@ impl<T> Channel<T> {
// Prepare for blocking until a receiver wakes us up.
let oper = Operation::hook(token);
let mut packet = Packet::<T>::message_on_stack(msg);
inner.senders.register_with_packet(oper, &mut packet as *mut Packet<T> as *mut (), cx);
inner.senders.register_with_packet(
oper,
core::ptr::addr_of_mut!(packet) as *mut (),
cx,
);
inner.receivers.notify();
drop(inner);

Expand Down Expand Up @@ -251,7 +255,7 @@ impl<T> Channel<T> {
let mut packet = Packet::<T>::empty_on_stack();
inner.receivers.register_with_packet(
oper,
&mut packet as *mut Packet<T> as *mut (),
core::ptr::addr_of_mut!(packet) as *mut (),
cx,
);
inner.senders.notify();
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/sys/pal/hermit/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ impl Socket {
buf.as_mut_ptr(),
buf.len(),
flags,
&mut storage as *mut _ as *mut _,
core::ptr::addr_of_mut!(storage) as *mut _,
&mut addrlen,
)
})?;
Expand Down Expand Up @@ -323,7 +323,7 @@ impl Socket {
netc::ioctl(
self.as_raw_fd(),
netc::FIONBIO,
&mut nonblocking as *mut _ as *mut core::ffi::c_void,
core::ptr::addr_of_mut!(nonblocking) as *mut core::ffi::c_void,
)
})
.map(drop)
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/sys/pal/hermit/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ pub struct Instant(Timespec);
impl Instant {
pub fn now() -> Instant {
let mut time: Timespec = Timespec::zero();
let _ = unsafe { abi::clock_gettime(CLOCK_MONOTONIC, &mut time.t as *mut timespec) };
let _ = unsafe { abi::clock_gettime(CLOCK_MONOTONIC, core::ptr::addr_of_mut!(time.t)) };

Instant(time)
}
Expand Down Expand Up @@ -197,7 +197,7 @@ pub const UNIX_EPOCH: SystemTime = SystemTime(Timespec::zero());
impl SystemTime {
pub fn now() -> SystemTime {
let mut time: Timespec = Timespec::zero();
let _ = unsafe { abi::clock_gettime(CLOCK_REALTIME, &mut time.t as *mut timespec) };
let _ = unsafe { abi::clock_gettime(CLOCK_REALTIME, core::ptr::addr_of_mut!(time.t)) };

SystemTime(time)
}
Expand Down
Loading
Loading