From 3d486d0c4124c4ef167c7625e570beca4ec44c9f Mon Sep 17 00:00:00 2001 From: ywxt Date: Wed, 11 Nov 2026 11:23:17 +0800 Subject: [PATCH 01/39] prevent optimization for input in benchmarks --- library/coretests/benches/ascii.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/coretests/benches/ascii.rs b/library/coretests/benches/ascii.rs index 64bdc7fed118f..940ec0f75892d 100644 --- a/library/coretests/benches/ascii.rs +++ b/library/coretests/benches/ascii.rs @@ -50,7 +50,7 @@ macro_rules! benches { fn $name(bencher: &mut Bencher) { bencher.bytes = $input.len() as u64; bencher.iter(|| { - let mut vec = $input.as_bytes().to_vec(); + let mut vec = black_box($input).as_bytes().to_vec(); { let $arg = &mut vec[..]; black_box($body); From 499332ac7d2115a6b7fc7fe0d640667938023c78 Mon Sep 17 00:00:00 2001 From: Takayuki Maeda Date: Thu, 12 Nov 2026 00:31:40 +0900 Subject: [PATCH 02/39] avoid redundant scans when extracting stage0 archives --- src/bootstrap/bootstrap.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index fcec091fed1c7..8dae5d4853f03 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -199,7 +199,8 @@ def unpack(tarball, tarball_suffix, dst, verbose=0, match=None): eprint("extracting", tarball) fname = os.path.basename(tarball).replace(tarball_suffix, "") with contextlib.closing(tarfile.open(tarball)) as tar: - for member in tar.getnames(): + for member_info in tar: + member = member_info.name if "/" not in member: continue name = member.replace(fname + "/", "", 1) @@ -210,7 +211,7 @@ def unpack(tarball, tarball_suffix, dst, verbose=0, match=None): dst_path = os.path.join(dst, name) if verbose > 0: eprint(" extracting", member) - tar.extract(member, dst) + tar.extract(member_info, dst) src_path = os.path.join(dst, member) if os.path.isdir(src_path) and os.path.exists(dst_path): continue From 832e0f3a2039f3142ae32d78a3ff0cd3040e494d Mon Sep 17 00:00:00 2001 From: Takayuki Maeda Date: Thu, 12 Nov 2026 17:39:01 +0900 Subject: [PATCH 03/39] prepare stage0 directories before parallel extraction --- src/bootstrap/bootstrap.py | 15 ++++++++++++--- src/tools/rust-installer/src/tarballer.rs | 2 ++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 8dae5d4853f03..ae6f5f1c9bbd3 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -194,12 +194,15 @@ def verify(path, expected, verbose): return verified -def unpack(tarball, tarball_suffix, dst, verbose=0, match=None): +def unpack(tarball, tarball_suffix, dst, verbose=0, match=None, directories_only=False): """Unpack the given tarball file""" - eprint("extracting", tarball) + if not directories_only: + eprint("extracting", tarball) fname = os.path.basename(tarball).replace(tarball_suffix, "") with contextlib.closing(tarfile.open(tarball)) as tar: for member_info in tar: + if directories_only and not member_info.isdir(): + break member = member_info.name if "/" not in member: continue @@ -536,13 +539,14 @@ def download_component(download_info): ) -def unpack_component(download_info): +def unpack_component(download_info, directories_only=False): unpack( download_info.tarball_path, download_info.tarball_suffix, download_info.bin_root, match=download_info.pattern, verbose=download_info.verbose, + directories_only=directories_only, ) @@ -697,6 +701,11 @@ def download_toolchain(self): for download_info in tarballs_download_info: download_component(download_info) + # rust-installer writes all directories before files. Move them serially + # so parallel extraction cannot race when creating shared directories. + for download_info in tarballs_download_info: + unpack_component(download_info, directories_only=True) + # Unpack the tarballs in parallel. # In Python 2.7, Pool cannot be used as a context manager. pool_size = min(len(tarballs_download_info), get_cpus()) diff --git a/src/tools/rust-installer/src/tarballer.rs b/src/tools/rust-installer/src/tarballer.rs index 854bb85f2c526..f999be962f3d1 100644 --- a/src/tools/rust-installer/src/tarballer.rs +++ b/src/tools/rust-installer/src/tarballer.rs @@ -67,6 +67,8 @@ impl Tarballer { // Write the tar into both encoded files. We write all directories // first, so files may be directly created. (See rust-lang/rustup.rs#1092.) + // Bootstrap also relies on this ordering. It prepares directories up to the + // first non-directory entry before extracting toolchain components in parallel. let buf = BufWriter::with_capacity(1024 * 1024, encoder); let mut builder = Builder::new(buf); // Make uid, gid and mtime deterministic to improve reproducibility From ea12d595892e20dab04d32aa008978a47efd7f1e Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 4 Nov 2026 22:19:08 +0100 Subject: [PATCH 04/39] join 32-bit and 64-bit virtual function elimination tests --- .../src/debuginfo/metadata.rs | 2 +- .../virtual-function-elimination-32bit.rs | 35 ------------------- .../virtual-function-elimination.rs | 23 +++++++----- 3 files changed, 16 insertions(+), 44 deletions(-) delete mode 100644 tests/codegen-llvm/virtual-function-elimination-32bit.rs diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index ff0b924f5701e..3da5b8c4d0864 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -1788,7 +1788,7 @@ pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>( let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, trait_ref); let typeid = cx.create_metadata(trait_ref_typeid.as_bytes()); - let type_ = [llvm::LLVMValueAsMetadata(cx.const_usize(0)), typeid]; + let type_ = [llvm::LLVMValueAsMetadata(cx.const_u64(0)), typeid]; cx.global_add_metadata_node(vtable, llvm::MD_type, &type_); let vcall_visibility = [llvm::LLVMValueAsMetadata(cx.const_u64(vcall_visibility as u64))]; diff --git a/tests/codegen-llvm/virtual-function-elimination-32bit.rs b/tests/codegen-llvm/virtual-function-elimination-32bit.rs deleted file mode 100644 index c9919cecccf9b..0000000000000 --- a/tests/codegen-llvm/virtual-function-elimination-32bit.rs +++ /dev/null @@ -1,35 +0,0 @@ -//@ compile-flags: -Zvirtual-function-elimination -Clto -Copt-level=3 -Csymbol-mangling-version=v0 -//@ ignore-64bit - -// CHECK: @vtable.0 = {{.*}}, !type ![[TYPE0:[0-9]+]], !vcall_visibility ![[VCALL_VIS0:[0-9]+]] - -#![crate_type = "lib"] - -trait T { - // CHECK-LABEL: ; ::used - fn used(&self) -> i32 { - 1 - } - // CHECK-LABEL-NOT: {{.*}}::unused - fn unused(&self) -> i32 { - 2 - } -} - -#[derive(Copy, Clone)] -struct S; - -impl T for S {} - -fn taking_t(t: &dyn T) -> i32 { - // CHECK: @llvm.type.checked.load({{.*}}, i32 12, metadata !"[[MANGLED_TYPE0:[0-9a-zA-Z_]+]]") - t.used() -} - -pub fn main() { - let s = S; - taking_t(&s); -} - -// CHECK: ![[TYPE0]] = !{i32 0, !"[[MANGLED_TYPE0]]"} -// CHECK: ![[VCALL_VIS0]] = !{i64 2} diff --git a/tests/codegen-llvm/virtual-function-elimination.rs b/tests/codegen-llvm/virtual-function-elimination.rs index 26604478c11a2..90331a4c59f3e 100644 --- a/tests/codegen-llvm/virtual-function-elimination.rs +++ b/tests/codegen-llvm/virtual-function-elimination.rs @@ -1,8 +1,7 @@ //@ compile-flags: -Zvirtual-function-elimination -Clto -Copt-level=3 -Csymbol-mangling-version=v0 -//@ ignore-32bit // CHECK: @vtable.0 = {{.*}}, !type ![[TYPE0:[0-9]+]], !vcall_visibility ![[VCALL_VIS0:[0-9]+]] -// CHECK: @vtable.1 = {{.*}}, !type ![[TYPE1:[0-9]+]], !vcall_visibility ![[VCALL_VIS0:[0-9]+]] +// CHECK: @vtable.1 = {{.*}}, !type ![[TYPE1:[0-9]+]], !vcall_visibility ![[VCALL_VIS0]] // CHECK: @vtable.2 = {{.*}}, !type ![[TYPE2:[0-9]+]], !vcall_visibility ![[VCALL_VIS2:[0-9]+]] #![crate_type = "lib"] @@ -61,25 +60,33 @@ impl V for S { } } +// CHECK-LABEL: taking_t +#[unsafe(no_mangle)] fn taking_t(t: &dyn T) -> i32 { - // CHECK: @llvm.type.checked.load({{.*}}, i32 24, metadata !"[[MANGLED_TYPE0:[0-9a-zA-Z_]+]]") + // CHECK: @llvm.type.checked.load({{.*}}, i32 {{12|24}}, metadata !"[[MANGLED_TYPE0:[0-9a-zA-Z_]+]]") t.used() } +// CHECK-LABEL: taking_rc_t +#[unsafe(no_mangle)] fn taking_rc_t(t: Rc) -> i32 { - // CHECK: @llvm.type.checked.load({{.*}}, i32 40, metadata !"[[MANGLED_TYPE0:[0-9a-zA-Z_]+]]") + // CHECK: @llvm.type.checked.load({{.*}}, i32 {{20|40}}, metadata !"[[MANGLED_TYPE0:[0-9a-zA-Z_]+]]") t.by_rc() } +// CHECK-LABEL: taking_u +#[unsafe(no_mangle)] fn taking_u(u: &dyn U) -> i32 { - // CHECK: @llvm.type.checked.load({{.*}}, i32 64, metadata !"[[MANGLED_TYPE1:[0-9a-zA-Z_]+]]") - // CHECK: @llvm.type.checked.load({{.*}}, i32 24, metadata !"[[MANGLED_TYPE1:[0-9a-zA-Z_]+]]") - // CHECK: @llvm.type.checked.load({{.*}}, i32 32, metadata !"[[MANGLED_TYPE1:[0-9a-zA-Z_]+]]") + // CHECK: @llvm.type.checked.load({{.*}}, i32 {{32|64}}, metadata !"[[MANGLED_TYPE1:[0-9a-zA-Z_]+]]") + // CHECK: @llvm.type.checked.load({{.*}}, i32 {{12|24}}, metadata !"[[MANGLED_TYPE1:[0-9a-zA-Z_]+]]") + // CHECK: @llvm.type.checked.load({{.*}}, i32 {{16|32}}, metadata !"[[MANGLED_TYPE1:[0-9a-zA-Z_]+]]") u.subtrait_used() + u.used() + u.used_through_sub_trait() } +// CHECK-LABEL: taking_v +#[unsafe(no_mangle)] pub fn taking_v(v: &dyn V) -> i32 { - // CHECK: @llvm.type.checked.load({{.*}}, i32 24, metadata !"NtC[[CRATE_IDENT:[a-zA-Z0-9]{12}]]_28virtual_function_elimination1V") + // CHECK: @llvm.type.checked.load({{.*}}, i32 {{12|24}}, metadata !"NtC[[CRATE_IDENT:[a-zA-Z0-9]{12}]]_28virtual_function_elimination1V") v.public_function() } From 00b1f622439fd23fd0c2fb31fb6bb4317abd2e17 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 4 Nov 2026 17:41:19 +0100 Subject: [PATCH 05/39] use `trait_ref`'s def_id In `with_self_ty` the def_id that is used is just `self.def_id`, so this is always the same DefId --- compiler/rustc_codegen_llvm/src/context.rs | 3 +-- .../rustc_codegen_llvm/src/debuginfo/metadata.rs | 5 +---- compiler/rustc_codegen_ssa/src/meth.rs | 12 ++++++------ compiler/rustc_codegen_ssa/src/traits/misc.rs | 1 - 4 files changed, 8 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 56f0be1a89e2a..1d4c684b242c6 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -946,11 +946,10 @@ impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { fn apply_vcall_visibility_metadata( &self, - ty: Ty<'tcx>, poly_trait_ref: Option>, vtable: Value<'ll>, ) { - apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable); + apply_vcall_visibility_metadata(self, poly_trait_ref, vtable); } fn get_fn(&self, instance: Instance<'tcx>) -> Value<'ll> { diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 3da5b8c4d0864..d799fcaf9c779 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -1736,7 +1736,6 @@ fn find_vtable_behind_cast<'ll>(vtable: Value<'ll>) -> Value<'ll> { pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, - ty: Ty<'tcx>, trait_ref: Option>, vtable: Value<'ll>, ) { @@ -1756,9 +1755,7 @@ pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>( // Unwrap potential addrspacecast let vtable = find_vtable_behind_cast(vtable); - let trait_ref_self = trait_ref.with_self_ty(cx.tcx, ty); - let trait_def_id = trait_ref_self.def_id; - let trait_vis = cx.tcx.visibility(trait_def_id); + let trait_vis = cx.tcx.visibility(trait_ref.def_id); let cgus = cx.sess().codegen_units().as_usize(); let single_cgu = cgus == 1; diff --git a/compiler/rustc_codegen_ssa/src/meth.rs b/compiler/rustc_codegen_ssa/src/meth.rs index 5b945fc3c2763..97553f79ae238 100644 --- a/compiler/rustc_codegen_ssa/src/meth.rs +++ b/compiler/rustc_codegen_ssa/src/meth.rs @@ -143,22 +143,22 @@ fn dyn_trait_in_self<'tcx>( #[instrument(level = "debug", skip(cx))] pub(crate) fn get_vtable<'tcx, Cx: CodegenMethods<'tcx>>( cx: &Cx, - ty: Ty<'tcx>, + self_ty: Ty<'tcx>, trait_ref: Option>, ) -> Cx::Value { let tcx = cx.tcx(); // Check the cache. - if let Some(&val) = cx.vtables().borrow().get(&(ty, trait_ref)) { + if let Some(&val) = cx.vtables().borrow().get(&(self_ty, trait_ref)) { return val; } - let vtable_alloc_id = tcx.vtable_allocation((ty, trait_ref)); + let vtable_alloc_id = tcx.vtable_allocation((self_ty, trait_ref)); let vtable_allocation = tcx.global_alloc(vtable_alloc_id).unwrap_memory(); let vtable = cx.static_addr_of(vtable_allocation, Some("vtable")); - cx.apply_vcall_visibility_metadata(ty, trait_ref, vtable); - cx.create_vtable_debuginfo(ty, trait_ref, vtable); - cx.vtables().borrow_mut().insert((ty, trait_ref), vtable); + cx.apply_vcall_visibility_metadata(trait_ref, vtable); + cx.create_vtable_debuginfo(self_ty, trait_ref, vtable); + cx.vtables().borrow_mut().insert((self_ty, trait_ref), vtable); vtable } diff --git a/compiler/rustc_codegen_ssa/src/traits/misc.rs b/compiler/rustc_codegen_ssa/src/traits/misc.rs index 7e48e86290ee8..4bf4bc6beec75 100644 --- a/compiler/rustc_codegen_ssa/src/traits/misc.rs +++ b/compiler/rustc_codegen_ssa/src/traits/misc.rs @@ -13,7 +13,6 @@ pub trait MiscCodegenMethods<'tcx>: BackendTypes { ) -> &RefCell, Option>), Self::Value>>; fn apply_vcall_visibility_metadata( &self, - _ty: Ty<'tcx>, _poly_trait_ref: Option>, _vtable: Self::Value, ) { From 211e160ec79696d41fa644fe951e28309d0a4298 Mon Sep 17 00:00:00 2001 From: Gennaro Biondi Date: Fri, 13 Nov 2026 20:59:06 +0100 Subject: [PATCH 06/39] Enhance documentation for try_clone File implementation clarifies that cloning the given File would create a new handle pointing to the OS file resource instead of sharing the old handle with the new cloned File --- library/std/src/fs.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index bf61ab79964c4..41114ec1fc392 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -1150,9 +1150,9 @@ impl File { self.inner.file_attr().map(Metadata) } - /// Creates a new `File` instance that shares the same underlying file handle - /// as the existing `File` instance. Reads, writes, and seeks will affect - /// both `File` instances simultaneously. + /// Creates a new `File` instance with a different OS handle referring to + /// the same underlying system resource as the existing `File` instance. + /// Reads, writes, and seeks will affect both `File` instances simultaneously. /// /// # Examples /// From 85f0143506115c2fd3e9e17fe1cdb4ee57005bc9 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 4 Nov 2026 21:19:43 +0100 Subject: [PATCH 07/39] document and refactor `VCallVisibility` --- .../src/debuginfo/metadata.rs | 80 +++++++++++-------- 1 file changed, 48 insertions(+), 32 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index d799fcaf9c779..65d478fe35c66 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -1734,6 +1734,52 @@ fn find_vtable_behind_cast<'ll>(vtable: Value<'ll>) -> Value<'ll> { vtable } +/// From where can virtual calls using this vtable be made? +/// +/// See also . +#[derive(PartialEq, Eq, PartialOrd, Ord)] +enum VCallVisibility { + /// Virtual function calls using this vtable could be made from external code. + Public = 0, + /// All virtual function calls which might use this vtable are in the current LTO unit, + /// meaning they will be in the current module once LTO linking has been performed. + LinkageUnit = 1, + /// All virtual function calls which might use this vtable are in the current module. + TranslationUnit = 2, +} + +impl VCallVisibility { + fn for_trait<'ll, 'tcx>( + cx: &CodegenCx<'ll, 'tcx>, + trait_ref: &ExistentialTraitRef<'tcx>, + ) -> Self { + let lto = cx.sess().lto(); + let trait_vis = cx.tcx.visibility(trait_ref.def_id); + let cgus = cx.sess().codegen_units().as_usize(); + let single_cgu = cgus == 1; + + // Because LLVM requires full LTO for the virtual function elimination optimization to + // apply, only the `Lto::Fat` cases are relevant currently. + match (lto, trait_vis, single_cgu) { + // If there is not LTO and the visibility in public, we have to assume that the vtable + // can be seen from anywhere. With multiple CGUs, the vtable is quasi-public. + (Lto::No | Lto::ThinLocal, Visibility::Public, _) + | (Lto::No, Visibility::Restricted(_), false) => VCallVisibility::Public, + // With LTO and a quasi-public visibility, the usages of the functions of the vtable are + // all known by the `LinkageUnit`. + // FIXME: LLVM only supports this optimization for `Lto::Fat` currently. Once it also + // supports `Lto::Thin` the `VCallVisibility` may have to be adjusted for those. + (Lto::Fat | Lto::Thin, Visibility::Public, _) + | (Lto::ThinLocal | Lto::Thin | Lto::Fat, Visibility::Restricted(_), false) => { + VCallVisibility::LinkageUnit + } + // If there is only one CGU, private vtables can only be seen by that CGU/translation + // unit and therefore we know of all usages of functions in the vtable. + (_, Visibility::Restricted(_), true) => VCallVisibility::TranslationUnit, + } + } +} + pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, trait_ref: Option>, @@ -1745,42 +1791,12 @@ pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>( return; } - enum VCallVisibility { - Public = 0, - LinkageUnit = 1, - TranslationUnit = 2, - } - let Some(trait_ref) = trait_ref else { return }; // Unwrap potential addrspacecast let vtable = find_vtable_behind_cast(vtable); - let trait_vis = cx.tcx.visibility(trait_ref.def_id); - - let cgus = cx.sess().codegen_units().as_usize(); - let single_cgu = cgus == 1; - - let lto = cx.sess().lto(); - - // Since LLVM requires full LTO for the virtual function elimination optimization to apply, - // only the `Lto::Fat` cases are relevant currently. - let vcall_visibility = match (lto, trait_vis, single_cgu) { - // If there is not LTO and the visibility in public, we have to assume that the vtable can - // be seen from anywhere. With multiple CGUs, the vtable is quasi-public. - (Lto::No | Lto::ThinLocal, Visibility::Public, _) - | (Lto::No, Visibility::Restricted(_), false) => VCallVisibility::Public, - // With LTO and a quasi-public visibility, the usages of the functions of the vtable are - // all known by the `LinkageUnit`. - // FIXME: LLVM only supports this optimization for `Lto::Fat` currently. Once it also - // supports `Lto::Thin` the `VCallVisibility` may have to be adjusted for those. - (Lto::Fat | Lto::Thin, Visibility::Public, _) - | (Lto::ThinLocal | Lto::Thin | Lto::Fat, Visibility::Restricted(_), false) => { - VCallVisibility::LinkageUnit - } - // If there is only one CGU, private vtables can only be seen by that CGU/translation unit - // and therefore we know of all usages of functions in the vtable. - (_, Visibility::Restricted(_), true) => VCallVisibility::TranslationUnit, - }; + + let vcall_visibility = VCallVisibility::for_def_id(cx, trait_ref.def_id); let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, trait_ref); let typeid = cx.create_metadata(trait_ref_typeid.as_bytes()); From 9b8230b0d0f1f425081eb5e8412e1bc0ad2a30e6 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 4 Nov 2026 21:22:44 +0100 Subject: [PATCH 08/39] support a slice of (super)traits in `apply_vcall_visibility_metadata` For now it gets at most one trait, the next step is to (recursively) provide supertraits too --- compiler/rustc_codegen_llvm/src/context.rs | 4 +-- .../src/debuginfo/metadata.rs | 30 ++++++++++++++----- compiler/rustc_codegen_ssa/src/meth.rs | 2 +- compiler/rustc_codegen_ssa/src/traits/misc.rs | 2 +- 4 files changed, 26 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 1d4c684b242c6..4b3ca5d5f8a5e 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -946,10 +946,10 @@ impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { fn apply_vcall_visibility_metadata( &self, - poly_trait_ref: Option>, + trait_hierarchy: &[ty::ExistentialTraitRef<'tcx>], vtable: Value<'ll>, ) { - apply_vcall_visibility_metadata(self, poly_trait_ref, vtable); + apply_vcall_visibility_metadata(self, trait_hierarchy, vtable); } fn get_fn(&self, instance: Instance<'tcx>) -> Value<'ll> { diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 65d478fe35c66..938d6a9226e6d 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -1780,9 +1780,13 @@ impl VCallVisibility { } } +/// Apply the virtual call visibility metadata to the vtable. +/// +/// Adds a !type annotation for every trait in the trait hierarchy, and a !vcall_visibility +/// annotation based on the most visible trait in the hierarchy. pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, - trait_ref: Option>, + trait_hierarchy: &[ExistentialTraitRef<'tcx>], vtable: Value<'ll>, ) { // FIXME(flip1995): The virtual function elimination optimization only works with full LTO in @@ -1791,19 +1795,29 @@ pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>( return; } - let Some(trait_ref) = trait_ref else { return }; + // Find the smallest "scope" from which virtual calls using this vtable can be made. + let Some(vcall_visibility) = + trait_hierarchy.iter().map(|trait_ref| VCallVisibility::for_trait(cx, trait_ref)).min() + else { + return; + }; - // Unwrap potential addrspacecast + // Unwrap a potential addrspacecast. let vtable = find_vtable_behind_cast(vtable); - let vcall_visibility = VCallVisibility::for_def_id(cx, trait_ref.def_id); + // The start of a Rust vtable is at offset 0 of a `&dyn T`'s address. + let vtable_offset = 0; - let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, trait_ref); - let typeid = cx.create_metadata(trait_ref_typeid.as_bytes()); + // Add `!type !{i64 0, !"typeid"}` to the vtable for each trait in the hierarchy. + for trait_ref in trait_hierarchy { + let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, *trait_ref); + let typeid = cx.create_metadata(trait_ref_typeid.as_bytes()); - let type_ = [llvm::LLVMValueAsMetadata(cx.const_u64(0)), typeid]; - cx.global_add_metadata_node(vtable, llvm::MD_type, &type_); + let type_ = [llvm::LLVMValueAsMetadata(cx.const_u64(vtable_offset)), typeid]; + cx.global_add_metadata_node(vtable, llvm::MD_type, &type_); + } + // Add `!vcall_visibility !{i64 vis}` to the vtable. let vcall_visibility = [llvm::LLVMValueAsMetadata(cx.const_u64(vcall_visibility as u64))]; cx.global_set_metadata_node(vtable, llvm::MD_vcall_visibility, &vcall_visibility); } diff --git a/compiler/rustc_codegen_ssa/src/meth.rs b/compiler/rustc_codegen_ssa/src/meth.rs index 97553f79ae238..3705a9f79bf56 100644 --- a/compiler/rustc_codegen_ssa/src/meth.rs +++ b/compiler/rustc_codegen_ssa/src/meth.rs @@ -157,7 +157,7 @@ pub(crate) fn get_vtable<'tcx, Cx: CodegenMethods<'tcx>>( let vtable_allocation = tcx.global_alloc(vtable_alloc_id).unwrap_memory(); let vtable = cx.static_addr_of(vtable_allocation, Some("vtable")); - cx.apply_vcall_visibility_metadata(trait_ref, vtable); + cx.apply_vcall_visibility_metadata(trait_ref.as_slice(), vtable); cx.create_vtable_debuginfo(self_ty, trait_ref, vtable); cx.vtables().borrow_mut().insert((self_ty, trait_ref), vtable); vtable diff --git a/compiler/rustc_codegen_ssa/src/traits/misc.rs b/compiler/rustc_codegen_ssa/src/traits/misc.rs index 4bf4bc6beec75..08da31fd1efa2 100644 --- a/compiler/rustc_codegen_ssa/src/traits/misc.rs +++ b/compiler/rustc_codegen_ssa/src/traits/misc.rs @@ -13,7 +13,7 @@ pub trait MiscCodegenMethods<'tcx>: BackendTypes { ) -> &RefCell, Option>), Self::Value>>; fn apply_vcall_visibility_metadata( &self, - _poly_trait_ref: Option>, + _trait_hierarchy: &[ty::ExistentialTraitRef<'tcx>], _vtable: Self::Value, ) { } From 33726d1da56b90edaf45f2f025d34feb94767b8e Mon Sep 17 00:00:00 2001 From: Jules Bertholet Date: Fri, 13 Nov 2026 15:58:29 -0500 Subject: [PATCH 09/39] `rustc_hir_typeck::upvar`: replace for loop with `.any()` --- compiler/rustc_hir_typeck/src/upvar.rs | 17 +++++++---------- .../crates/hir-ty/src/infer/closure/analysis.rs | 17 +++++++---------- 2 files changed, 14 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 3c59017c78d85..3136b9ae41447 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -2642,19 +2642,16 @@ fn truncate_place_to_len_and_update_capture_kind<'tcx>( // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so // we don't need to worry about that case here. match curr_mode { - ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => { - for i in len..place.projections.len() { - if place.projections[i].kind == ProjectionKind::Deref + ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) + if (len..place.projections.len()).any(|i| { + place.projections[i].kind == ProjectionKind::Deref && is_mut_ref(place.ty_before_projection(i)) - { - *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable); - break; - } - } + }) => + { + *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable); } - ty::UpvarCapture::ByRef(..) => {} - ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {} + ty::UpvarCapture::ByRef(_) | ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {} } place.projections.truncate(len); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure/analysis.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure/analysis.rs index a2767fcfa7494..491a1b526f6be 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure/analysis.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/closure/analysis.rs @@ -1456,19 +1456,16 @@ fn truncate_place_to_len_and_update_capture_kind( // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so // we don't need to worry about that case here. match info.capture_kind { - UpvarCapture::ByRef(BorrowKind::Mutable) => { - for i in len..place.projections.len() { - if place.projections[i].kind == ProjectionKind::Deref + UpvarCapture::ByRef(BorrowKind::Mutable) + if (len..place.projections.len()).any(|i| { + place.projections[i].kind == ProjectionKind::Deref && is_mut_ref(place.ty_before_projection(i)) - { - info.capture_kind = UpvarCapture::ByRef(BorrowKind::UniqueImmutable); - break; - } - } + }) => + { + info.capture_kind = UpvarCapture::ByRef(BorrowKind::UniqueImmutable); } - UpvarCapture::ByRef(..) => {} - UpvarCapture::ByValue | UpvarCapture::ByUse => {} + UpvarCapture::ByRef(_) | UpvarCapture::ByValue | UpvarCapture::ByUse => {} } // Now fix the sources, to point at the smaller place. From 016e281a37df73191460cf1618666f7d5c7960ac Mon Sep 17 00:00:00 2001 From: Bee Date: Fri, 13 Nov 2026 22:32:30 +0000 Subject: [PATCH 10/39] Merge `type_bf16()` with `type_f16b()` --- compiler/rustc_codegen_llvm/src/intrinsic.rs | 2 +- compiler/rustc_codegen_llvm/src/type_.rs | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index fcc0e4818db51..f0ef906c3dc18 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -1086,7 +1086,7 @@ fn can_autocast<'ll>(cx: &CodegenCx<'ll, '_>, rust_ty: Type<'ll>, llvm_ty: Type< _ if let Some((llvm_element_ty, element_count)) = cx.vector_element_type_and_length(llvm_ty) => { - if llvm_element_ty == cx.type_bf16() { + if llvm_element_ty == cx.type_f16b() { rust_ty == cx.type_vector(cx.type_i16(), element_count) } else if llvm_element_ty == cx.type_i1() { let int_width = element_count.next_power_of_two().max(8); diff --git a/compiler/rustc_codegen_llvm/src/type_.rs b/compiler/rustc_codegen_llvm/src/type_.rs index 90250fc97b284..d885349766220 100644 --- a/compiler/rustc_codegen_llvm/src/type_.rs +++ b/compiler/rustc_codegen_llvm/src/type_.rs @@ -168,10 +168,6 @@ impl<'ll, CX: Borrow>> GenericCx<'ll, CX> { } } - pub(crate) fn type_bf16(&self) -> Type<'ll> { - unsafe { llvm::LLVMBFloatTypeInContext(self.llcx()) } - } - pub(crate) fn type_array(&self, ty: Type<'ll>, len: u64) -> Type<'ll> { unsafe { llvm::LLVMArrayType2(ty, len) } } From 0df97849e3a1abbaff8969ec3b9cd9334ab68790 Mon Sep 17 00:00:00 2001 From: Dennis Duda Date: Sat, 14 Nov 2026 00:01:49 +0100 Subject: [PATCH 11/39] windows: use io::const_error in get_access_mode --- library/std/src/sys/fs/windows.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/std/src/sys/fs/windows.rs b/library/std/src/sys/fs/windows.rs index 77311d233fc74..a7802c1e8bf4c 100644 --- a/library/std/src/sys/fs/windows.rs +++ b/library/std/src/sys/fs/windows.rs @@ -279,12 +279,12 @@ impl OpenOptions { match (self.read, self.write, self.append) { (_, false, false) if self.truncate || self.create || self.create_new => { - Err(io::Error::new( + Err(io::const_error!( io::ErrorKind::InvalidInput, "creating or truncating a file requires write or append access", )) } - (_, _, true) if self.truncate && !self.create_new => Err(io::Error::new( + (_, _, true) if self.truncate && !self.create_new => Err(io::const_error!( io::ErrorKind::InvalidInput, "append and truncate cannot both be enabled", )), @@ -293,7 +293,7 @@ impl OpenOptions { (true, true, false) => Ok(c::GENERIC_READ | c::GENERIC_WRITE), (false, _, true) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA), (true, _, true) => Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)), - (false, false, false) => Err(io::Error::new( + (false, false, false) => Err(io::const_error!( io::ErrorKind::InvalidInput, "must specify at least one of read, write, or append access", )), From 8d5c28c16a80b183894fc88d3169bfb2bd1d2be2 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:24:58 +0100 Subject: [PATCH 12/39] Prune un/under used methods of `ast::Attribute` --- compiler/rustc_ast/src/ast.rs | 11 ----- compiler/rustc_ast/src/attr/mod.rs | 47 ++----------------- .../rustc_attr_parsing/src/attributes/cfg.rs | 2 +- .../src/deriving/default.rs | 2 +- compiler/rustc_expand/src/diagnostics.rs | 18 ------- compiler/rustc_expand/src/expand.rs | 26 +--------- .../rustc_resolve/src/build_reduced_graph.rs | 2 +- .../src/attrs/allow_attributes.rs | 2 +- src/tools/clippy/clippy_utils/src/attrs.rs | 13 ++--- src/tools/clippy/clippy_utils/src/msrvs.rs | 22 ++++----- 10 files changed, 26 insertions(+), 119 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 968566feab637..05c06345d5f77 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -3556,17 +3556,6 @@ impl GeneratedAttr { } } - pub fn is_word(&self) -> bool { - match self { - GeneratedAttr::AutomaticallyDerived => true, - GeneratedAttr::RustcConstUnstableDerived => false, - GeneratedAttr::Inline => true, - GeneratedAttr::DocHidden => false, - GeneratedAttr::CoverageOff => false, - GeneratedAttr::RustcTestMarker(_) => false, - GeneratedAttr::RustcTrivialFieldReads => false, - } - } pub fn value_str(&self) -> Option { match self { GeneratedAttr::AutomaticallyDerived => None, diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 45fc0165de73d..bcf83f45088c6 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -8,7 +8,6 @@ use std::sync::atomic::{AtomicU32, Ordering}; use rustc_index::bit_set::GrowableBitSet; use rustc_span::{Ident, Span, Symbol, sym}; -use smallvec::{SmallVec, smallvec}; use thin_vec::{ThinVec, thin_vec}; use crate::ast::{ @@ -135,15 +134,6 @@ impl Attribute { } } - pub fn meta_kind(&self) -> Option { - match &self.kind { - AttrKind::Normal(normal) => normal.item.meta_kind(), - AttrKind::Synthetic(..) => unreachable!(), - AttrKind::DocComment(..) => None, - AttrKind::Generated(..) => None, - } - } - pub fn append_token_trees_to(&self, res: &mut Vec) { match &self.kind { AttrKind::Normal(normal) => normal @@ -202,15 +192,6 @@ impl Attribute { AttrKind::Synthetic(..) | AttrKind::DocComment(..) | AttrKind::Generated(..) => None, } } - - pub fn path_span(&self) -> Option { - match &self.kind { - AttrKind::Normal(attr) => Some(attr.item.path.span), - AttrKind::Synthetic(..) => unreachable!(), - AttrKind::DocComment(_, _) => None, - AttrKind::Generated(generated) => generated.path_span(), - } - } } impl AttrItem { @@ -282,6 +263,11 @@ impl AttrItem { pub fn meta_kind(&self) -> Option { MetaItemKind::from_attr_args(&self.args) } + + /// Returns whether the attribute is a path, without any arguments. + pub fn is_word(&self) -> bool { + matches!(self.args, AttrArgs::Empty) + } } impl MetaItem { @@ -892,29 +878,6 @@ impl Attribute { names.iter().any(|&name| self.has_name(name)) } - /// Returns whether the attribute is a path, without any arguments. - pub fn is_word(&self) -> bool { - match &self.kind { - AttrKind::Normal(normal) => matches!(normal.item.args, AttrArgs::Empty), - AttrKind::Synthetic(..) => unreachable!(), - AttrKind::DocComment(..) => false, - AttrKind::Generated(generated) => generated.is_word(), - } - } - - pub fn path(&self) -> SmallVec<[Symbol; 1]> { - use SyntheticAttr::*; - match &self.kind { - AttrKind::Normal(normal) => { - normal.item.path.segments.iter().map(|i| i.ident.name).collect() - } - AttrKind::Synthetic(CfgTrace(_)) => smallvec![sym::cfg], - AttrKind::Synthetic(CfgAttrTrace(_)) => smallvec![sym::cfg_attr], - AttrKind::DocComment(_, _) => smallvec![sym::doc], - AttrKind::Generated(generated) => generated.path().iter().copied().collect(), - } - } - /// Returns the documentation if this is a doc comment or a sugared doc comment. /// * `///doc` returns `Some("doc")`. /// * `#[doc = "doc"]` returns `Some("doc")`. diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg.rs b/compiler/rustc_attr_parsing/src/attributes/cfg.rs index d904e120eb349..8846ed766e7f3 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg.rs @@ -395,7 +395,7 @@ fn parse_cfg_attr_internal<'a>( attribute.span, item.span, attribute.style, - AttrPath { segments: attribute.path().into_boxed_slice(), span: attribute.span }, + AttrPath::from_ast(&item.path, identity), Some(item.unsafety), AttributeSafety::Normal, ParsedDescription::Attribute, diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index efefcf0006387..6aa45b9d41126 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -293,7 +293,7 @@ fn validate_default_attribute( return Err(guar); } }; - if !attr.is_word() { + if !attr.get_normal_item().is_word() { let guar = cx.dcx().emit_err(diagnostics::DefaultHasArg { span: attr.span }); return Err(guar); diff --git a/compiler/rustc_expand/src/diagnostics.rs b/compiler/rustc_expand/src/diagnostics.rs index 43da7a03a6454..481b2d5346300 100644 --- a/compiler/rustc_expand/src/diagnostics.rs +++ b/compiler/rustc_expand/src/diagnostics.rs @@ -602,21 +602,3 @@ pub(crate) struct TrailingMacro { pub is_trailing: bool, pub name: Ident, } - -#[derive(Diagnostic)] -#[diag("unused attribute `{$attr_name}`")] -pub(crate) struct UnusedBuiltinAttribute { - #[note( - "the built-in attribute `{$attr_name}` will be ignored, since it's applied to the macro invocation `{$macro_name}`" - )] - pub invoc_span: Span, - pub attr_name: Symbol, - pub macro_name: String, - #[suggestion( - "remove the attribute", - code = "", - applicability = "machine-applicable", - style = "tool-only" - )] - pub attr_span: Span, -} diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 326014b2699db..935532fddcc9e 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -23,7 +23,7 @@ use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_errors::PResult; use rustc_feature::Features; use rustc_hir::def::MacroKinds; -use rustc_lint_defs::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS}; +use rustc_lint_defs::builtin::UNUSED_DOC_COMMENTS; use rustc_parse::parser::{ AllowConstBlockItems, AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser, RecoverColon, RecoverComma, Recovery, token_descr, @@ -2229,7 +2229,6 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // Run attributes through the attribute parser // since they will not be detected after macro expansion. fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) { - use SyntheticAttr::*; let mut attrs = attrs.iter().peekable(); let mut span: Option = None; while let Some(attr) = attrs.next() { @@ -2265,29 +2264,6 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { ); continue; } - - match &attr.kind { - AttrKind::Normal(normal) - if rustc_attr_parsing::is_builtin_attr(&normal.item) - && !AttributeParser::is_parsed_attribute(&attr.path()) => - { - let attr_name = attr.name().unwrap(); - self.cx.sess.psess.buffer_lint( - UNUSED_ATTRIBUTES, - attr.span, - self.cx.current_expansion.lint_node_id, - crate::diagnostics::UnusedBuiltinAttribute { - attr_name, - macro_name: pprust::path_to_string(&call.path), - invoc_span: call.path.span, - attr_span: attr.span, - }, - ); - } - AttrKind::Normal(_) => {} - AttrKind::Synthetic(CfgTrace(_) | CfgAttrTrace(_)) | AttrKind::Generated(..) => {} - AttrKind::DocComment(..) => unreachable!(), // handled above - } } } diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 53bf60d038123..11fde009f9a7c 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -1248,7 +1248,7 @@ impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> { continue; } - if !attr.is_word() { + if !attr.get_normal_item().is_word() { self.r.dcx().emit_err(diagnostics::ArgumentsMacroUseNotAllowed { span: attr.span }); } return true; diff --git a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs index 01d442133ccf0..7c185702f3194 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs @@ -8,10 +8,10 @@ use rustc_lint::EarlyContext; // Separate each crate's features. pub fn check<'cx>(cx: &EarlyContext<'cx>, attr: &'cx Attribute) { if let AttrStyle::Outer = attr.style - && let Some(path_span) = attr.path_span() && !attr.span.from_expansion() && !is_from_proc_macro(cx, attr) { + let path_span = attr.get_normal_item().path.span; #[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")] span_lint_and_then(cx, ALLOW_ATTRIBUTES, path_span, "#[allow] attribute found", |diag| { diag.span_suggestion(path_span, "replace it with", "expect", Applicability::MachineApplicable); diff --git a/src/tools/clippy/clippy_utils/src/attrs.rs b/src/tools/clippy/clippy_utils/src/attrs.rs index fbb3d65238a0a..be9d6761f3625 100644 --- a/src/tools/clippy/clippy_utils/src/attrs.rs +++ b/src/tools/clippy/clippy_utils/src/attrs.rs @@ -2,6 +2,7 @@ use crate::source::SpanExt as _; use crate::{sym, tokenize_with_text}; +use rustc_ast::AttrKind; use rustc_attr_ir::{AttrArgs, find_attr}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; @@ -14,14 +15,14 @@ use std::str::FromStr as _; /// Validates a single clippy attribute and emits errors for unknown or deprecated ones. pub fn check_clippy_attr(sess: &Session, attr: &rustc_ast::ast::Attribute) { - if let [clippy, segment2] = &*attr.path() - && *clippy == sym::clippy + let AttrKind::Normal(normal) = &attr.kind else { return }; + let attr_item = &normal.item; + if let [clippy, segment2] = &*attr_item.path.segments + && clippy.ident.name == sym::clippy { - let path_span = attr - .path_span() - .expect("Clippy attributes are tool attributes, so they have a span"); + let path_span = attr_item.path.span; - match *segment2 { + match segment2.ident.name { sym::cyclomatic_complexity => { sess.dcx() .struct_span_err(path_span, "usage of deprecated attribute") diff --git a/src/tools/clippy/clippy_utils/src/msrvs.rs b/src/tools/clippy/clippy_utils/src/msrvs.rs index 19eb0512cd703..9e986c0337f41 100644 --- a/src/tools/clippy/clippy_utils/src/msrvs.rs +++ b/src/tools/clippy/clippy_utils/src/msrvs.rs @@ -271,13 +271,15 @@ fn parse_ast_attrs(attrs: &[Attribute]) -> Option { } fn parse_hir_attrs(attrs: &[rustc_attr_ir::Attribute]) -> Option { - let msrv = attrs.iter().find_map(|attr| - if let rustc_attr_ir::Attribute::Tool(item) = attr && let [sym::clippy, sym::msrv] = item.path.segments { + let msrv = attrs.iter().find_map(|attr| { + if let rustc_attr_ir::Attribute::Tool(item) = attr + && let [sym::clippy, sym::msrv] = item.path.segments + { attr.value_lit().and_then(|lit| lit.value_as_str()) } else { None } - )?; + })?; parse_version(msrv) } @@ -290,24 +292,18 @@ pub fn check_attrs(sess: &Session, attrs: &[Attribute]) { if let Some(duplicate) = msrv_attrs.next_back() { sess.dcx() - .struct_span_err( - duplicate.span, - "`clippy::msrv` is defined multiple times", - ) + .struct_span_err(duplicate.span, "`clippy::msrv` is defined multiple times") .with_span_note(msrv_attr.span, "first definition found here") .emit(); } let Some(msrv) = msrv_attr.value_str() else { - sess.dcx() - .span_err(msrv_attr.span, "bad clippy attribute"); + sess.dcx().span_err(msrv_attr.span, "bad clippy attribute"); return; }; if parse_version(msrv).is_none() { - sess.dcx().span_err( - msrv_attr.span, - format!("`{msrv}` is not a valid Rust version"), - ); + sess.dcx() + .span_err(msrv_attr.span, format!("`{msrv}` is not a valid Rust version")); } } From ab4f981828b5452363f0bd6c0bea64674d89132a Mon Sep 17 00:00:00 2001 From: Mahdi Ali-Raihan Date: Thu, 22 Oct 2026 17:04:02 +0000 Subject: [PATCH 13/39] Implemented different with_native_path conversion methods, refactoring fs functions to utilize with_native_path, and move exists to use with_native_path * Implemented different with_native_path conversion methods, refactoring fs functions to utilize with_native_path, and move exists to use with_native_path * Refactored Vexos' File::open and stat shared code in opening a file with a CStr through File::open_c * Place path/motor.rs' and path/unsupported.rs' with_native_path implementation in path/unix_like.rs to remove unnecessary files --- library/std/src/sys/fs/common.rs | 8 - library/std/src/sys/fs/hermit.rs | 62 ++--- library/std/src/sys/fs/mod.rs | 16 +- library/std/src/sys/fs/motor.rs | 45 ++-- library/std/src/sys/fs/solid.rs | 93 +++---- library/std/src/sys/fs/uefi.rs | 28 +-- library/std/src/sys/fs/unix.rs | 9 +- library/std/src/sys/fs/vexos.rs | 229 ++++++++++-------- library/std/src/sys/path/mod.rs | 8 +- library/std/src/sys/path/solid.rs | 53 ++++ library/std/src/sys/path/uefi.rs | 6 + .../src/sys/path/{unix.rs => unix_like.rs} | 26 ++ .../std/src/sys/path/unsupported_backslash.rs | 26 -- 13 files changed, 333 insertions(+), 276 deletions(-) create mode 100644 library/std/src/sys/path/solid.rs rename library/std/src/sys/path/{unix.rs => unix_like.rs} (76%) delete mode 100644 library/std/src/sys/path/unsupported_backslash.rs diff --git a/library/std/src/sys/fs/common.rs b/library/std/src/sys/fs/common.rs index 6a7a1f52c15ac..4c06f8acf208f 100644 --- a/library/std/src/sys/fs/common.rs +++ b/library/std/src/sys/fs/common.rs @@ -54,14 +54,6 @@ fn remove_dir_all_recursive(path: &Path) -> io::Result<()> { ignore_notfound(fs::remove_dir(path)) } -pub fn exists(path: &Path) -> io::Result { - match fs::metadata(path) { - Ok(_) => Ok(true), - Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), - Err(error) => Err(error), - } -} - pub struct Dir { path: PathBuf, } diff --git a/library/std/src/sys/fs/hermit.rs b/library/std/src/sys/fs/hermit.rs index 32ed0bd76214f..c8fe9a6db6fd7 100644 --- a/library/std/src/sys/fs/hermit.rs +++ b/library/std/src/sys/fs/hermit.rs @@ -11,7 +11,7 @@ use crate::os::hermit::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, Raw use crate::path::{Path, PathBuf}; use crate::sync::Arc; use crate::sys::fd::FileDesc; -pub use crate::sys::fs::common::{Dir, ExtraHomeDirs, ExtraMediaDirs, copy, exists}; +pub use crate::sys::fs::common::{Dir, ExtraHomeDirs, ExtraMediaDirs, copy}; use crate::sys::helpers::run_path_with_cstr; use crate::sys::io::DEFAULT_BUF_SIZE; use crate::sys::time::SystemTime; @@ -301,9 +301,7 @@ impl DirEntry { } pub fn metadata(&self) -> io::Result { - let mut path = self.path(); - path.set_file_name(self.file_name_os_str()); - lstat(&path) + run_path_with_cstr(&self.path(), &lstat) } pub fn file_type(&self) -> io::Result { @@ -594,70 +592,74 @@ pub fn readdir(path: &Path) -> io::Result { Ok(ReadDir { inner, fd, buf }) } -pub fn unlink(path: &Path) -> io::Result<()> { - run_path_with_cstr(path, &|path| cvt(unsafe { hermit_abi::unlink(path.as_ptr()) }).map(|_| ())) +pub fn unlink(path: &CStr) -> io::Result<()> { + cvt(unsafe { hermit_abi::unlink(path.as_ptr()) }).map(|_| ()) } -pub fn rename(_old: &Path, _new: &Path) -> io::Result<()> { +pub fn rename(_old: &CStr, _new: &CStr) -> io::Result<()> { unsupported() } -pub fn rename_noreplace(_old: &Path, _new: &Path) -> io::Result<()> { +pub fn rename_noreplace(_old: &CStr, _new: &CStr) -> io::Result<()> { unsupported() } -pub fn set_perm(_p: &Path, _perm: FilePermissions) -> io::Result<()> { +pub fn set_perm(_p: &CStr, _perm: FilePermissions) -> io::Result<()> { unsupported() } -pub fn set_perm_nofollow(_p: &Path, _perm: FilePermissions) -> io::Result<()> { +pub fn set_perm_nofollow(_p: &CStr, _perm: FilePermissions) -> io::Result<()> { unsupported() } -pub fn set_times(_p: &Path, _times: FileTimes) -> io::Result<()> { +pub fn set_times(_p: &CStr, _times: FileTimes) -> io::Result<()> { unsupported() } -pub fn set_times_nofollow(_p: &Path, _times: FileTimes) -> io::Result<()> { +pub fn set_times_nofollow(_p: &CStr, _times: FileTimes) -> io::Result<()> { unsupported() } -pub fn rmdir(path: &Path) -> io::Result<()> { - run_path_with_cstr(path, &|path| cvt(unsafe { hermit_abi::rmdir(path.as_ptr()) }).map(|_| ())) +pub fn rmdir(path: &CStr) -> io::Result<()> { + cvt(unsafe { hermit_abi::rmdir(path.as_ptr()) }).map(|_| ()) +} + +pub fn exists(path: &CStr) -> io::Result { + match stat(path) { + Ok(_) => Ok(true), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } } pub fn remove_dir_all(_path: &Path) -> io::Result<()> { unsupported() } -pub fn readlink(_p: &Path) -> io::Result { +pub fn readlink(_p: &CStr) -> io::Result { unsupported() } -pub fn symlink(_original: &Path, _link: &Path) -> io::Result<()> { +pub fn symlink(_original: &CStr, _link: &CStr) -> io::Result<()> { unsupported() } -pub fn link(_original: &Path, _link: &Path) -> io::Result<()> { +pub fn link(_original: &CStr, _link: &CStr) -> io::Result<()> { unsupported() } -pub fn stat(path: &Path) -> io::Result { - run_path_with_cstr(path, &|path| { - let mut stat_val: stat_struct = unsafe { mem::zeroed() }; - cvt(unsafe { hermit_abi::stat(path.as_ptr(), &mut stat_val) })?; - Ok(FileAttr::from_stat(stat_val)) - }) +pub fn stat(path: &CStr) -> io::Result { + let mut stat_val: stat_struct = unsafe { mem::zeroed() }; + cvt(unsafe { hermit_abi::stat(path.as_ptr(), &mut stat_val) })?; + Ok(FileAttr::from_stat(stat_val)) } -pub fn lstat(path: &Path) -> io::Result { - run_path_with_cstr(path, &|path| { - let mut stat_val: stat_struct = unsafe { mem::zeroed() }; - cvt(unsafe { hermit_abi::lstat(path.as_ptr(), &mut stat_val) })?; - Ok(FileAttr::from_stat(stat_val)) - }) +pub fn lstat(path: &CStr) -> io::Result { + let mut stat_val: stat_struct = unsafe { mem::zeroed() }; + cvt(unsafe { hermit_abi::lstat(path.as_ptr(), &mut stat_val) })?; + Ok(FileAttr::from_stat(stat_val)) } -pub fn canonicalize(_p: &Path) -> io::Result { +pub fn canonicalize(_p: &CStr) -> io::Result { unsupported() } diff --git a/library/std/src/sys/fs/mod.rs b/library/std/src/sys/fs/mod.rs index e15841b363d18..4f8dccea71096 100644 --- a/library/std/src/sys/fs/mod.rs +++ b/library/std/src/sys/fs/mod.rs @@ -2,6 +2,7 @@ use crate::io; use crate::path::{Path, PathBuf}; +use crate::sys::path::with_native_path; pub mod common; @@ -17,15 +18,11 @@ cfg_select! { pub(crate) use unix::debug_assert_fd_is_open; #[cfg(not(target_os = "wasi"))] pub use unix::{chown, fchown, lchown, mkfifo}; - - use crate::sys::helpers::run_path_with_cstr as with_native_path; } target_os = "windows" => { mod windows; use windows as imp; pub use windows::{junction_point, symlink_inner}; - - use crate::sys::path::with_native_path; } target_os = "hermit" => { mod hermit; @@ -53,13 +50,6 @@ cfg_select! { } } -// FIXME: Replace this with platform-specific path conversion functions. -#[cfg(not(any(target_family = "unix", target_os = "windows", target_os = "wasi")))] -#[inline] -pub fn with_native_path(path: &Path, f: &dyn Fn(&Path) -> io::Result) -> io::Result { - f(path) -} - pub use imp::{ Dir, DirBuilder, DirEntry, ExtraHomeDirs, ExtraMediaDirs, File, FileAttr, FilePermissions, FileTimes, FileType, OpenOptions, ReadDir, @@ -143,10 +133,6 @@ pub fn copy(from: &Path, to: &Path) -> io::Result { } pub fn exists(path: &Path) -> io::Result { - // FIXME: use with_native_path on all platforms - #[cfg(not(windows))] - return imp::exists(path); - #[cfg(windows)] with_native_path(path, &imp::exists) } diff --git a/library/std/src/sys/fs/motor.rs b/library/std/src/sys/fs/motor.rs index 269ece5666494..0e8d743f3068d 100644 --- a/library/std/src/sys/fs/motor.rs +++ b/library/std/src/sys/fs/motor.rs @@ -4,7 +4,7 @@ use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}; use crate::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::path::{Path, PathBuf}; use crate::sys::fd::FileDesc; -pub use crate::sys::fs::common::{Dir, ExtraHomeDirs, ExtraMediaDirs, exists}; +pub use crate::sys::fs::common::{Dir, ExtraHomeDirs, ExtraMediaDirs}; use crate::sys::time::SystemTime; use crate::sys::{ AsInner, AsInnerMut, FromInner, IntoInner, io_slices, io_slices_mut, map_motor_error, @@ -313,73 +313,74 @@ impl DirBuilder { } } -pub fn unlink(path: &Path) -> io::Result<()> { - let path = path.to_str().ok_or(io::Error::from(io::ErrorKind::InvalidFilename))?; +pub fn unlink(path: &str) -> io::Result<()> { moto_rt::fs::unlink(path).map_err(map_motor_error) } -pub fn rename(old: &Path, new: &Path) -> io::Result<()> { - let old = old.to_str().ok_or(io::Error::from(io::ErrorKind::InvalidFilename))?; - let new = new.to_str().ok_or(io::Error::from(io::ErrorKind::InvalidFilename))?; +pub fn rename(old: &str, new: &str) -> io::Result<()> { moto_rt::fs::rename(old, new).map_err(map_motor_error) } -pub fn rename_noreplace(_old: &Path, _new: &Path) -> io::Result<()> { +pub fn rename_noreplace(_old: &str, _new: &str) -> io::Result<()> { unsupported() } -pub fn rmdir(path: &Path) -> io::Result<()> { - let path = path.to_str().ok_or(io::Error::from(io::ErrorKind::InvalidFilename))?; +pub fn rmdir(path: &str) -> io::Result<()> { moto_rt::fs::rmdir(path).map_err(map_motor_error) } +pub fn exists(path: &str) -> io::Result { + match stat(path) { + Ok(_) => Ok(true), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + pub fn remove_dir_all(path: &Path) -> io::Result<()> { let path = path.to_str().ok_or(io::Error::from(io::ErrorKind::InvalidFilename))?; moto_rt::fs::rmdir_all(path).map_err(map_motor_error) } -pub fn set_perm(path: &Path, perm: FilePermissions) -> io::Result<()> { +pub fn set_perm(path: &str, perm: FilePermissions) -> io::Result<()> { // Motor does not support symlinks set_perm_nofollow(path, perm) } -pub fn set_perm_nofollow(path: &Path, perm: FilePermissions) -> io::Result<()> { - let path = path.to_str().ok_or(io::Error::from(io::ErrorKind::InvalidFilename))?; +pub fn set_perm_nofollow(path: &str, perm: FilePermissions) -> io::Result<()> { moto_rt::fs::set_perm(path, perm.rt_perm).map_err(map_motor_error) } -pub fn set_times(_p: &Path, _times: FileTimes) -> io::Result<()> { +pub fn set_times(_p: &str, _times: FileTimes) -> io::Result<()> { unsupported() } -pub fn set_times_nofollow(_p: &Path, _times: FileTimes) -> io::Result<()> { +pub fn set_times_nofollow(_p: &str, _times: FileTimes) -> io::Result<()> { unsupported() } -pub fn readlink(_p: &Path) -> io::Result { +pub fn readlink(_p: &str) -> io::Result { unsupported() } -pub fn symlink(_original: &Path, _link: &Path) -> io::Result<()> { +pub fn symlink(_original: &str, _link: &str) -> io::Result<()> { unsupported() } -pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> { +pub fn link(_src: &str, _dst: &str) -> io::Result<()> { unsupported() } -pub fn stat(path: &Path) -> io::Result { - let path = path.to_str().ok_or(io::Error::from(io::ErrorKind::InvalidFilename))?; +pub fn stat(path: &str) -> io::Result { let inner = moto_rt::fs::stat(path).map_err(map_motor_error)?; Ok(FileAttr { inner }) } -pub fn lstat(path: &Path) -> io::Result { +pub fn lstat(path: &str) -> io::Result { stat(path) } -pub fn canonicalize(path: &Path) -> io::Result { - let path = path.to_str().ok_or(io::Error::from(io::ErrorKind::InvalidFilename))?; +pub fn canonicalize(path: &str) -> io::Result { let path = moto_rt::fs::canonicalize(path).map_err(map_motor_error)?; Ok(path.into()) } diff --git a/library/std/src/sys/fs/solid.rs b/library/std/src/sys/fs/solid.rs index c43a4794e620e..00242f7e8cc6e 100644 --- a/library/std/src/sys/fs/solid.rs +++ b/library/std/src/sys/fs/solid.rs @@ -1,6 +1,6 @@ #![allow(dead_code)] -use crate::ffi::{CStr, CString, OsStr, OsString}; +use crate::ffi::{CStr, OsStr, OsString}; use crate::fmt; use crate::fs::TryLockError; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}; @@ -9,9 +9,10 @@ use crate::os::raw::{c_int, c_short}; use crate::os::solid::ffi::OsStrExt; use crate::path::{Path, PathBuf}; use crate::sync::Arc; -pub use crate::sys::fs::common::{Dir, ExtraHomeDirs, ExtraMediaDirs, exists}; +pub use crate::sys::fs::common::{Dir, ExtraHomeDirs, ExtraMediaDirs}; use crate::sys::helpers::ignore_notfound; use crate::sys::pal::{abi, error}; +use crate::sys::path::cstr; use crate::sys::time::SystemTime; use crate::sys::{unsupported, unsupported_err}; @@ -214,7 +215,8 @@ impl DirEntry { } pub fn metadata(&self) -> io::Result { - lstat(&self.path()) + let cstr = cstr(&self.path())?; + lstat(&cstr) } pub fn file_type(&self) -> io::Result { @@ -224,7 +226,7 @@ impl DirEntry { abi::DT_REG => Ok(FileType(abi::S_IFREG)), abi::DT_DIR => Ok(FileType(abi::S_IFDIR)), abi::DT_BLK => Ok(FileType(abi::S_IFBLK)), - _ => lstat(&self.path()).map(|m| m.file_type()), + _ => lstat(&cstr(&self.path())?).map(|m| m.file_type()), } } } @@ -304,26 +306,6 @@ impl OpenOptions { } } -fn cstr(path: &Path) -> io::Result { - let path = path.as_os_str().as_bytes(); - - if !path.starts_with(br"\") { - // Relative paths aren't supported - return Err(crate::io::const_error!( - crate::io::ErrorKind::Unsupported, - "relative path is not supported on this platform", - )); - } - - // Apply the thread-safety wrapper - const SAFE_PREFIX: &[u8] = br"\TS"; - let wrapped_path = [SAFE_PREFIX, &path, &[0]].concat(); - - CString::from_vec_with_nul(wrapped_path).map_err(|_| { - crate::io::const_error!(io::ErrorKind::InvalidInput, "path provided contains a nul byte") - }) -} - impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result { let flags = opts.get_access_mode()? @@ -520,52 +502,48 @@ impl fmt::Debug for File { } } -pub fn unlink(p: &Path) -> io::Result<()> { +pub fn unlink(p: &CStr) -> io::Result<()> { if stat(p)?.file_type().is_dir() { Err(io::const_error!(io::ErrorKind::IsADirectory, "is a directory")) } else { - error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(cstr(p)?.as_ptr()) }) + error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(p.as_ptr()) }) .map_err(|e| e.as_io_error())?; Ok(()) } } -pub fn rename(old: &Path, new: &Path) -> io::Result<()> { - error::SolidError::err_if_negative(unsafe { - abi::SOLID_FS_Rename(cstr(old)?.as_ptr(), cstr(new)?.as_ptr()) - }) - .map_err(|e| e.as_io_error())?; +pub fn rename(old: &CStr, new: &CStr) -> io::Result<()> { + error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Rename(old.as_ptr(), new.as_ptr()) }) + .map_err(|e| e.as_io_error())?; Ok(()) } -pub fn rename_noreplace(_old: &Path, _new: &Path) -> io::Result<()> { +pub fn rename_noreplace(_old: &CStr, _new: &CStr) -> io::Result<()> { unsupported() } -pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { +pub fn set_perm(p: &CStr, perm: FilePermissions) -> io::Result<()> { // Solid does not support symlinks set_perm_nofollow(p, perm) } -pub fn set_perm_nofollow(p: &Path, perm: FilePermissions) -> io::Result<()> { - error::SolidError::err_if_negative(unsafe { - abi::SOLID_FS_Chmod(cstr(p)?.as_ptr(), perm.0.into()) - }) - .map_err(|e| e.as_io_error())?; +pub fn set_perm_nofollow(p: &CStr, perm: FilePermissions) -> io::Result<()> { + error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Chmod(p.as_ptr(), perm.0.into()) }) + .map_err(|e| e.as_io_error())?; Ok(()) } -pub fn set_times(_p: &Path, _times: FileTimes) -> io::Result<()> { +pub fn set_times(_p: &CStr, _times: FileTimes) -> io::Result<()> { unsupported() } -pub fn set_times_nofollow(_p: &Path, _times: FileTimes) -> io::Result<()> { +pub fn set_times_nofollow(_p: &CStr, _times: FileTimes) -> io::Result<()> { unsupported() } -pub fn rmdir(p: &Path) -> io::Result<()> { +pub fn rmdir(p: &CStr) -> io::Result<()> { if stat(p)?.file_type().is_dir() { - error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(cstr(p)?.as_ptr()) }) + error::SolidError::err_if_negative(unsafe { abi::SOLID_FS_Unlink(p.as_ptr()) }) .map_err(|e| e.as_io_error())?; Ok(()) } else { @@ -573,6 +551,14 @@ pub fn rmdir(p: &Path) -> io::Result<()> { } } +pub fn exists(path: &CStr) -> io::Result { + match stat(path) { + Ok(_) => Ok(true), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + pub fn remove_dir_all(path: &Path) -> io::Result<()> { for child in readdir(path)? { let result: io::Result<()> = try { @@ -581,7 +567,7 @@ pub fn remove_dir_all(path: &Path) -> io::Result<()> { if child_type.is_dir() { remove_dir_all(&child.path())?; } else { - unlink(&child.path())?; + unlink(&cstr(&child.path())?)?; } }; // ignore internal NotFound errors @@ -591,43 +577,40 @@ pub fn remove_dir_all(path: &Path) -> io::Result<()> { return result; } } - ignore_notfound(rmdir(path)) + ignore_notfound(rmdir(&cstr(path)?)) } -pub fn readlink(p: &Path) -> io::Result { +pub fn readlink(p: &CStr) -> io::Result { // This target doesn't support symlinks stat(p)?; Err(io::const_error!(io::ErrorKind::InvalidInput, "not a symbolic link")) } -pub fn symlink(_original: &Path, _link: &Path) -> io::Result<()> { +pub fn symlink(_original: &CStr, _link: &CStr) -> io::Result<()> { // This target doesn't support symlinks unsupported() } -pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> { +pub fn link(_src: &CStr, _dst: &CStr) -> io::Result<()> { // This target doesn't support symlinks unsupported() } -pub fn stat(p: &Path) -> io::Result { +pub fn stat(p: &CStr) -> io::Result { // This target doesn't support symlinks lstat(p) } -pub fn lstat(p: &Path) -> io::Result { +pub fn lstat(p: &CStr) -> io::Result { unsafe { let mut out_stat = MaybeUninit::uninit(); - error::SolidError::err_if_negative(abi::SOLID_FS_Stat( - cstr(p)?.as_ptr(), - out_stat.as_mut_ptr(), - )) - .map_err(|e| e.as_io_error())?; + error::SolidError::err_if_negative(abi::SOLID_FS_Stat(p.as_ptr(), out_stat.as_mut_ptr())) + .map_err(|e| e.as_io_error())?; Ok(FileAttr { stat: out_stat.assume_init() }) } } -pub fn canonicalize(_p: &Path) -> io::Result { +pub fn canonicalize(_p: &CStr) -> io::Result { unsupported() } diff --git a/library/std/src/sys/fs/uefi.rs b/library/std/src/sys/fs/uefi.rs index 945eaeaff1d7d..c7b4090875705 100644 --- a/library/std/src/sys/fs/uefi.rs +++ b/library/std/src/sys/fs/uefi.rs @@ -271,11 +271,13 @@ impl File { return Err(io::const_error!(io::ErrorKind::InvalidInput, "Invalid open options")); } - if opts.create_new && exists(path)? { + let path = crate::path::absolute(path)?; + + if opts.create_new && exists(&path)? { return Err(io::const_error!(io::ErrorKind::AlreadyExists, "File already exists")); } - let f = uefi_fs::File::from_path(path, opts.mode, 0).map(Self)?; + let f = uefi_fs::File::from_path(&path, opts.mode, 0).map(Self)?; if opts.truncate { f.truncate(0)?; @@ -419,8 +421,7 @@ impl fmt::Debug for File { } pub fn readdir(p: &Path) -> io::Result { - let path = crate::path::absolute(p)?; - let f = uefi_fs::File::from_path(&path, file::MODE_READ, 0)?; + let f = uefi_fs::File::from_path(p, file::MODE_READ, 0)?; let file_info = f.file_info()?; let file_attr = FileAttr::from_uefi(file_info); @@ -452,11 +453,8 @@ pub fn unlink(p: &Path) -> io::Result<()> { /// 3. Construct the target path relative to the current disk root. /// 4. Set this target path as the file_name in the file_info structure. pub fn rename(old: &Path, new: &Path) -> io::Result<()> { - let old_absolute = crate::path::absolute(old)?; - let new_absolute = crate::path::absolute(new)?; - - let mut old_components = old_absolute.components(); - let mut new_components = new_absolute.components(); + let mut old_components = old.components(); + let mut new_components = new.components(); let Some(old_disk) = old_components.next() else { return Err(io::const_error!(io::ErrorKind::InvalidInput, "Old path is not valid")); @@ -550,7 +548,7 @@ pub fn lstat(p: &Path) -> io::Result { } pub fn canonicalize(p: &Path) -> io::Result { - crate::path::absolute(p) + Ok(p.to_path_buf()) } fn set_perm_inner(f: &uefi_fs::File, perm: FilePermissions) -> io::Result<()> { @@ -589,7 +587,7 @@ mod uefi_fs { use crate::ffi::OsString; use crate::io; use crate::os::uefi::ffi::OsStringExt; - use crate::path::Path; + use crate::path::{Path, PathBuf}; use crate::ptr::NonNull; use crate::sys::pal::helpers::{self, UefiBox}; use crate::sys::pal::system_time; @@ -597,7 +595,7 @@ mod uefi_fs { pub(crate) struct File { protocol: NonNull, - path: crate::path::PathBuf, + path: PathBuf, } // SAFETY: UEFI has no regular threads, and as per @@ -607,13 +605,11 @@ mod uefi_fs { impl File { pub(crate) fn from_path(path: &Path, open_mode: u64, attr: u64) -> io::Result { - let absolute = crate::path::absolute(path)?; - - let p = helpers::OwnedDevicePath::from_text(absolute.as_os_str())?; + let p = helpers::OwnedDevicePath::from_text(path.as_os_str())?; let (vol, mut path_remaining) = Self::open_volume_from_device_path(p.borrow())?; let protocol = Self::open(vol, &mut path_remaining, open_mode, attr)?; - Ok(Self { protocol, path: absolute }) + Ok(Self { protocol, path: path.to_path_buf() }) } /// Open Filesystem volume given a devicepath to the volume, or a file/directory in the diff --git a/library/std/src/sys/fs/unix.rs b/library/std/src/sys/fs/unix.rs index 4b384aee7bc24..d2292fb6c76b9 100644 --- a/library/std/src/sys/fs/unix.rs +++ b/library/std/src/sys/fs/unix.rs @@ -55,7 +55,6 @@ use crate::os::wasi::prelude::*; use crate::path::{Path, PathBuf}; use crate::sync::Arc; use crate::sys::fd::FileDesc; -pub use crate::sys::fs::common::exists; #[cfg(target_os = "wasi")] pub use crate::sys::fs::common::{ExtraHomeDirs, ExtraMediaDirs}; use crate::sys::helpers::run_path_with_cstr; @@ -2040,6 +2039,14 @@ pub fn rmdir(p: &CStr) -> io::Result<()> { cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ()) } +pub fn exists(path: &CStr) -> io::Result { + match stat(path) { + Ok(_) => Ok(true), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + pub fn readlink(c_path: &CStr) -> io::Result { let p = c_path.as_ptr(); diff --git a/library/std/src/sys/fs/vexos.rs b/library/std/src/sys/fs/vexos.rs index e9fa1d46d225b..42c1bc65f3714 100644 --- a/library/std/src/sys/fs/vexos.rs +++ b/library/std/src/sys/fs/vexos.rs @@ -1,4 +1,4 @@ -use crate::ffi::{OsString, c_char}; +use crate::ffi::{CStr, OsString, c_char}; use crate::fmt; use crate::fs::TryLockError; use crate::hash::Hash; @@ -11,10 +11,7 @@ use crate::sys::{unsupported, unsupported_err}; #[expect(dead_code)] #[path = "unsupported.rs"] mod unsupported_fs; -pub use unsupported_fs::{ - Dir, DirBuilder, ExtraHomeDirs, ExtraMediaDirs, FileTimes, canonicalize, link, readlink, - remove_dir_all, rename, rename_noreplace, rmdir, symlink, unlink, -}; +pub use unsupported_fs::{Dir, DirBuilder, ExtraHomeDirs, ExtraMediaDirs, FileTimes}; /// VEXos file descriptor. /// @@ -155,7 +152,7 @@ impl DirEntry { } pub fn metadata(&self) -> io::Result { - stat(&self.path) + run_path_with_cstr(&self.path(), &stat) } pub fn file_type(&self) -> io::Result { @@ -197,84 +194,85 @@ impl OpenOptions { impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result { - run_path_with_cstr(path, &|path| { - // Enforce the invariants of `create_new`/`create`. - // - // Since VEXos doesn't have anything akin to POSIX's `oflags`, we need to enforce - // the requirements that `create_new` can't have an existing file and `!create` - // doesn't create a file ourselves. - if !opts.read && (opts.write || opts.append) && (opts.create_new || !opts.create) { - let status = unsafe { vex_sdk::vexFileStatus(path.as_ptr()) }; - - if opts.create_new && status != 0 { - return Err(io::const_error!(io::ErrorKind::AlreadyExists, "file exists",)); - } else if !opts.create && status == 0 { - return Err(io::const_error!( - io::ErrorKind::NotFound, - "no such file or directory", - )); - } + run_path_with_cstr(path, &|path| File::open_c(path, opts)) + } + + pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result { + // Enforce the invariants of `create_new`/`create`. + // + // Since VEXos doesn't have anything akin to POSIX's `oflags`, we need to enforce + // the requirements that `create_new` can't have an existing file and `!create` + // doesn't create a file ourselves. + if !opts.read && (opts.write || opts.append) && (opts.create_new || !opts.create) { + let status = unsafe { vex_sdk::vexFileStatus(path.as_ptr()) }; + + if opts.create_new && status != 0 { + return Err(io::const_error!(io::ErrorKind::AlreadyExists, "file exists",)); + } else if !opts.create && status == 0 { + return Err( + io::const_error!(io::ErrorKind::NotFound, "no such file or directory",), + ); } + } - let file = match opts { - // read + write - unsupported - OpenOptions { read: true, write: true, .. } => { - return Err(io::const_error!( - io::ErrorKind::InvalidInput, - "opening files with read and write access is unsupported on this target", - )); - } + let file = match opts { + // read + write - unsupported + OpenOptions { read: true, write: true, .. } => { + return Err(io::const_error!( + io::ErrorKind::InvalidInput, + "opening files with read and write access is unsupported on this target", + )); + } - // read - OpenOptions { - read: true, - write: false, - append: _, - truncate: false, - create: false, - create_new: false, - } => unsafe { vex_sdk::vexFileOpen(path.as_ptr(), c"".as_ptr()) }, - - // append - OpenOptions { - read: false, - write: _, - append: true, - truncate: false, - create: _, - create_new: _, - } => unsafe { vex_sdk::vexFileOpenWrite(path.as_ptr()) }, - - // write - OpenOptions { - read: false, - write: true, - append: false, - truncate, - create: _, - create_new: _, - } => unsafe { - if *truncate { - vex_sdk::vexFileOpenCreate(path.as_ptr()) - } else { - // Open in append, but jump to the start of the file. - let fd = vex_sdk::vexFileOpenWrite(path.as_ptr()); - vex_sdk::vexFileSeek(fd, 0, 0); - fd - } - }, - - _ => { - return Err(io::const_error!(io::ErrorKind::InvalidInput, "invalid argument")); + // read + OpenOptions { + read: true, + write: false, + append: _, + truncate: false, + create: false, + create_new: false, + } => unsafe { vex_sdk::vexFileOpen(path.as_ptr(), c"".as_ptr()) }, + + // append + OpenOptions { + read: false, + write: _, + append: true, + truncate: false, + create: _, + create_new: _, + } => unsafe { vex_sdk::vexFileOpenWrite(path.as_ptr()) }, + + // write + OpenOptions { + read: false, + write: true, + append: false, + truncate, + create: _, + create_new: _, + } => unsafe { + if *truncate { + vex_sdk::vexFileOpenCreate(path.as_ptr()) + } else { + // Open in append, but jump to the start of the file. + let fd = vex_sdk::vexFileOpenWrite(path.as_ptr()); + vex_sdk::vexFileSeek(fd, 0, 0); + fd } - }; + }, - if file.is_null() { - Err(io::const_error!(io::ErrorKind::NotFound, "could not open file")) - } else { - Ok(Self { fd: FileDesc(file) }) + _ => { + return Err(io::const_error!(io::ErrorKind::InvalidInput, "invalid argument")); } - }) + }; + + if file.is_null() { + Err(io::const_error!(io::ErrorKind::NotFound, "could not open file")) + } else { + Ok(Self { fd: FileDesc(file) }) + } } pub fn file_attr(&self) -> io::Result { @@ -501,51 +499,84 @@ pub fn readdir(_p: &Path) -> io::Result { unsupported() } -pub fn set_perm(_p: &Path, _perm: FilePermissions) -> io::Result<()> { +pub fn unlink(_p: &CStr) -> io::Result<()> { + unsupported() +} + +pub fn rename(_old: &CStr, _new: &CStr) -> io::Result<()> { unsupported() } -pub fn set_perm_nofollow(_p: &Path, _perm: FilePermissions) -> io::Result<()> { +pub fn rename_noreplace(_old: &CStr, _new: &CStr) -> io::Result<()> { unsupported() } -pub fn set_times(_p: &Path, _times: FileTimes) -> io::Result<()> { +pub fn set_perm(_p: &CStr, _perm: FilePermissions) -> io::Result<()> { unsupported() } -pub fn set_times_nofollow(_p: &Path, _times: FileTimes) -> io::Result<()> { +pub fn set_perm_nofollow(_p: &CStr, _perm: FilePermissions) -> io::Result<()> { unsupported() } -pub fn exists(path: &Path) -> io::Result { - run_path_with_cstr(path, &|path| Ok(unsafe { vex_sdk::vexFileStatus(path.as_ptr()) } != 0)) +pub fn set_times(_p: &CStr, _times: FileTimes) -> io::Result<()> { + unsupported() +} + +pub fn set_times_nofollow(_p: &CStr, _times: FileTimes) -> io::Result<()> { + unsupported() +} + +pub fn rmdir(_p: &CStr) -> io::Result<()> { + unsupported() } -pub fn stat(p: &Path) -> io::Result { +pub fn remove_dir_all(_path: &Path) -> io::Result<()> { + unsupported() +} + +pub fn exists(path: &CStr) -> io::Result { + Ok(unsafe { vex_sdk::vexFileStatus(path.as_ptr()) } != 0) +} + +pub fn readlink(_p: &CStr) -> io::Result { + unsupported() +} + +pub fn symlink(_original: &CStr, _link: &CStr) -> io::Result<()> { + unsupported() +} + +pub fn link(_src: &CStr, _dst: &CStr) -> io::Result<()> { + unsupported() +} + +pub fn stat(p: &CStr) -> io::Result { // `vexFileStatus` returns 3 if the given path is a directory, 1 if the path is a // file, or 0 if no such path exists. const FILE_STATUS_DIR: u32 = 3; + let file_type = unsafe { vex_sdk::vexFileStatus(p.as_ptr()) }; - run_path_with_cstr(p, &|c_path| { - let file_type = unsafe { vex_sdk::vexFileStatus(c_path.as_ptr()) }; - - // We can't get the size if its a directory because we cant open it as a file - if file_type == FILE_STATUS_DIR { - Ok(FileAttr::Dir) - } else { - let mut opts = OpenOptions::new(); - opts.read(true); - let file = File::open(p, &opts)?; - file.file_attr() - } - }) + // We can't get the size if its a directory because we cant open it as a file + if file_type == FILE_STATUS_DIR { + Ok(FileAttr::Dir) + } else { + let mut opts = OpenOptions::new(); + opts.read(true); + let file = File::open_c(p, &opts)?; + file.file_attr() + } } -pub fn lstat(p: &Path) -> io::Result { +pub fn lstat(p: &CStr) -> io::Result { // Symlinks aren't supported in this filesystem stat(p) } +pub fn canonicalize(_p: &CStr) -> io::Result { + unsupported() +} + // Cannot use `copy` from `common` here, since `File::set_permissions` is unsupported on this target. pub fn copy(from: &Path, to: &Path) -> io::Result { use crate::fs::File; diff --git a/library/std/src/sys/path/mod.rs b/library/std/src/sys/path/mod.rs index bbb7577e186ae..bd7a499e13188 100644 --- a/library/std/src/sys/path/mod.rs +++ b/library/std/src/sys/path/mod.rs @@ -28,8 +28,8 @@ cfg_select! { pub use sgx::*; } target_os = "solid_asp3" => { - mod unsupported_backslash; - pub use unsupported_backslash::*; + mod solid; + pub use solid::*; } target_os = "uefi" => { mod uefi; @@ -41,7 +41,7 @@ cfg_select! { pub use cygwin::*; } _ => { - mod unix; - pub use unix::*; + mod unix_like; + pub use unix_like::*; } } diff --git a/library/std/src/sys/path/solid.rs b/library/std/src/sys/path/solid.rs new file mode 100644 index 0000000000000..e13190c2d0311 --- /dev/null +++ b/library/std/src/sys/path/solid.rs @@ -0,0 +1,53 @@ +#![forbid(unsafe_op_in_unsafe_fn)] +use crate::ffi::{CStr, CString, OsStr}; +use crate::io; +use crate::os::solid::ffi::OsStrExt; +use crate::path::{Path, PathBuf, Prefix}; +use crate::sys::unsupported; + +path_separator_bytes!(b'\\'); + +pub fn cstr(path: &Path) -> io::Result { + let path = path.as_os_str().as_bytes(); + + if !path.starts_with(br"\") { + // Relative paths aren't supported + return Err(crate::io::const_error!( + crate::io::ErrorKind::Unsupported, + "relative path is not supported on this platform", + )); + } + + // Apply the thread-safety wrapper + const SAFE_PREFIX: &[u8] = br"\TS"; + let wrapped_path = [SAFE_PREFIX, &path, &[0]].concat(); + + CString::from_vec_with_nul(wrapped_path).map_err(|_| { + crate::io::const_error!(io::ErrorKind::InvalidInput, "path provided contains a nul byte") + }) +} + +#[inline] +pub const fn is_verbatim_sep(b: u8) -> bool { + is_sep_byte(b) +} + +pub fn parse_prefix(_: &OsStr) -> Option> { + None +} + +pub const HAS_PREFIXES: bool = true; + +#[inline] +pub fn with_native_path(path: &Path, f: &dyn Fn(&CStr) -> io::Result) -> io::Result { + let path = cstr(path)?; + f(&path) +} + +pub(crate) fn absolute(_path: &Path) -> io::Result { + unsupported() +} + +pub(crate) fn is_absolute(path: &Path) -> bool { + path.has_root() && path.prefix().is_some() +} diff --git a/library/std/src/sys/path/uefi.rs b/library/std/src/sys/path/uefi.rs index 8c911ee5f9c53..6dd31fa51e693 100644 --- a/library/std/src/sys/path/uefi.rs +++ b/library/std/src/sys/path/uefi.rs @@ -21,6 +21,12 @@ pub fn parse_prefix(_: &OsStr) -> Option> { pub const HAS_PREFIXES: bool = true; +#[inline] +pub fn with_native_path(path: &Path, f: &dyn Fn(&Path) -> io::Result) -> io::Result { + let path = absolute(path)?; + f(path.as_ref()) +} + /// UEFI paths can be of 4 types: /// /// 1. Absolute Shell Path: Uses shell mappings (eg: `FS0:`). Does not exist if UEFI shell not present. diff --git a/library/std/src/sys/path/unix.rs b/library/std/src/sys/path/unix_like.rs similarity index 76% rename from library/std/src/sys/path/unix.rs rename to library/std/src/sys/path/unix_like.rs index 5a8c0c77745e0..aae61c958bf5a 100644 --- a/library/std/src/sys/path/unix.rs +++ b/library/std/src/sys/path/unix_like.rs @@ -1,7 +1,33 @@ use crate::ffi::OsStr; +#[cfg(target_os = "motor")] +use crate::os::motor::ffi::OsStrExt; use crate::path::{Path, PathBuf, Prefix}; use crate::{env, io}; +cfg_select! { + target_os = "motor" => { + #[inline] + pub fn with_native_path( + path: &Path, + f: &dyn Fn(&str) -> io::Result, + ) -> io::Result { + f(path.as_os_str().as_str()) + } + } + any(target_family = "unix", target_os = "vexos", target_os = "hermit", target_os = "wasi") => { + pub use crate::sys::helpers::run_path_with_cstr as with_native_path; + } + _ => { + #[inline] + pub fn with_native_path( + path: &Path, + f: &dyn Fn(&Path) -> io::Result, + ) -> io::Result { + f(path) + } + } +} + path_separator_bytes!(b'/'); #[inline] diff --git a/library/std/src/sys/path/unsupported_backslash.rs b/library/std/src/sys/path/unsupported_backslash.rs deleted file mode 100644 index ce1851e938395..0000000000000 --- a/library/std/src/sys/path/unsupported_backslash.rs +++ /dev/null @@ -1,26 +0,0 @@ -#![forbid(unsafe_op_in_unsafe_fn)] -use crate::ffi::OsStr; -use crate::io; -use crate::path::{Path, PathBuf, Prefix}; -use crate::sys::unsupported; - -path_separator_bytes!(b'\\'); - -#[inline] -pub const fn is_verbatim_sep(b: u8) -> bool { - is_sep_byte(b) -} - -pub fn parse_prefix(_: &OsStr) -> Option> { - None -} - -pub const HAS_PREFIXES: bool = true; - -pub(crate) fn absolute(_path: &Path) -> io::Result { - unsupported() -} - -pub(crate) fn is_absolute(path: &Path) -> bool { - path.has_root() && path.prefix().is_some() -} From a6b77dde268f8cd01a965f5b4b9c6b24680fd2dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 13 Nov 2026 05:06:32 +0000 Subject: [PATCH 14/39] Tweak wording of missing `core` note ``` = help: consider building the core library from source with `cargo build -Zbuild-std=core` ``` --- compiler/rustc_metadata/src/diagnostics.rs | 15 +++++++++++---- tests/ui/crate-loading/missing-std-tier-3.rs | 2 +- tests/ui/crate-loading/missing-std-tier-3.stderr | 2 +- tests/ui/crate-loading/missing-std.rs | 2 +- tests/ui/crate-loading/missing-std.stderr | 2 +- .../missing-target-no-std-error.stderr | 2 +- 6 files changed, 16 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_metadata/src/diagnostics.rs b/compiler/rustc_metadata/src/diagnostics.rs index 21091ef70d3c8..2f061c6f2f92c 100644 --- a/compiler/rustc_metadata/src/diagnostics.rs +++ b/compiler/rustc_metadata/src/diagnostics.rs @@ -525,10 +525,17 @@ impl Diagnostic<'_> for CannotFindCrate { // Recommend -Zbuild-std even on stable builds for Tier 3 targets because // it's the recommended way to use the target, the user should switch to nightly. if self.is_nightly_build || !has_precompiled_std { - diag.help(msg!( - "consider building the standard library from source with \ - `cargo build -Zbuild-std`" - )); + if self.crate_name == sym::core && self.missing_core { + diag.help(msg!( + "consider building the `core` library from source with \ + `cargo build -Zbuild-std=core`" + )); + } else { + diag.help(msg!( + "consider building the standard library from source with \ + `cargo build -Zbuild-std`" + )); + } } } else if self.crate_name == self.profiler_runtime { diag.note(msg!("the compiler may have been built without the profiler runtime")); diff --git a/tests/ui/crate-loading/missing-std-tier-3.rs b/tests/ui/crate-loading/missing-std-tier-3.rs index 74c7db3db0abf..195ab1bf50c05 100644 --- a/tests/ui/crate-loading/missing-std-tier-3.rs +++ b/tests/ui/crate-loading/missing-std-tier-3.rs @@ -10,5 +10,5 @@ extern crate core; //~^ ERROR can't find crate for `core` //~| NOTE can't find crate //~| NOTE target may not be installed -//~| HELP consider building the standard library from source with `cargo build -Zbuild-std` +//~| HELP consider building the `core` library from source with `cargo build -Zbuild-std=core` fn main() {} diff --git a/tests/ui/crate-loading/missing-std-tier-3.stderr b/tests/ui/crate-loading/missing-std-tier-3.stderr index 197feeccd9c5e..50a4110c7f8d6 100644 --- a/tests/ui/crate-loading/missing-std-tier-3.stderr +++ b/tests/ui/crate-loading/missing-std-tier-3.stderr @@ -5,7 +5,7 @@ LL | extern crate core; | ^^^^^^^^^^^^^^^^^^ can't find crate | = note: the `m68k-unknown-linux-gnu` target may not be installed - = help: consider building the standard library from source with `cargo build -Zbuild-std` + = help: consider building the `core` library from source with `cargo build -Zbuild-std=core` error: aborting due to 1 previous error diff --git a/tests/ui/crate-loading/missing-std.rs b/tests/ui/crate-loading/missing-std.rs index 0fb45b4cfe987..2c1cd63de8e36 100644 --- a/tests/ui/crate-loading/missing-std.rs +++ b/tests/ui/crate-loading/missing-std.rs @@ -8,6 +8,6 @@ extern crate core; //~^ ERROR can't find crate for `core` //~| NOTE can't find crate //~| NOTE target may not be installed -//~| HELP consider building the standard library from source with `cargo build -Zbuild-std` +//~| HELP consider building the `core` library from source with `cargo build -Zbuild-std=core` //~| HELP consider downloading the target with `rustup target add x86_64-unknown-uefi` fn main() {} diff --git a/tests/ui/crate-loading/missing-std.stderr b/tests/ui/crate-loading/missing-std.stderr index 67ed73a2ec6f6..59908ee0505c3 100644 --- a/tests/ui/crate-loading/missing-std.stderr +++ b/tests/ui/crate-loading/missing-std.stderr @@ -6,7 +6,7 @@ LL | extern crate core; | = note: the `x86_64-unknown-uefi` target may not be installed = help: consider downloading the target with `rustup target add x86_64-unknown-uefi` - = help: consider building the standard library from source with `cargo build -Zbuild-std` + = help: consider building the `core` library from source with `cargo build -Zbuild-std=core` error: aborting due to 1 previous error diff --git a/tests/ui/crate-loading/missing-target-no-std-error.stderr b/tests/ui/crate-loading/missing-target-no-std-error.stderr index 11c856f844fc8..779991be8fc89 100644 --- a/tests/ui/crate-loading/missing-target-no-std-error.stderr +++ b/tests/ui/crate-loading/missing-target-no-std-error.stderr @@ -2,7 +2,7 @@ error[E0463]: can't find crate for `core` | = note: the `thumbv7em-none-eabihf` target may not be installed = help: consider downloading the target with `rustup target add thumbv7em-none-eabihf` - = help: consider building the standard library from source with `cargo build -Zbuild-std` + = help: consider building the `core` library from source with `cargo build -Zbuild-std=core` error[E0463]: can't find crate for `cortex_m` --> $DIR/missing-target-no-std-error.rs:12:1 From 8bb9cef9a408c64ace8f5595141eba5ee8409cbf Mon Sep 17 00:00:00 2001 From: Augie Fackler Date: Fri, 13 Nov 2026 20:37:31 -0500 Subject: [PATCH 15/39] PassWrapper: adapt for latest round of LLVM codegen flag refactor --- compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index 489973000e1a1..ea2f0010742d7 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -29,6 +29,7 @@ #include "llvm/Passes/StandardInstrumentations.h" #include "llvm/Plugins/PassPlugin.h" #include "llvm/Support/CBindingWrapping.h" +#include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Program.h" #include "llvm/Support/TimeProfiler.h" @@ -62,7 +63,9 @@ using namespace llvm; +#if LLVM_VERSION_LT(24, 0) static codegen::RegisterCodeGenFlags CGF; +#endif typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef; @@ -453,6 +456,8 @@ extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) { return; Initialized = true; #if LLVM_VERSION_GE(24, 0) + for (const cl::LibraryOptions *L : codegen::getToolOptions()) + cl::addLibraryOptions(*L); char *Err; if (LLVMParseCommandLineOptionsWithError(Argc, Argv, "", &Err)) { // FIXME: Report the error via Rust's diagnostics infrastructure. From 9f9ec7199d61d698d3d3267d5f4a7f094f0fa904 Mon Sep 17 00:00:00 2001 From: N1ark Date: Sun, 6 Sep 2026 17:57:48 +0100 Subject: [PATCH 16/39] cranelift: use fallbacks for abs f16, f128 --- .../src/intrinsics/mod.rs | 89 ++++++++++--------- 1 file changed, 46 insertions(+), 43 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 61e165ef272a5..3e81c6367cdf7 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -376,10 +376,13 @@ fn codegen_float_intrinsic_call<'tcx>( true } -/// Used to distinguish fallbacks of float intrinsics. For some we have a codegen fallback, -/// while for others we fallback to an external libcall. -enum IntrinsicFallback { - Fallback(&'static str), +/// How a float intrinsic is lowered: either directly to Cranelift instructions, or to a call to an +/// external (libm/compiler-builtins) function. This is unrelated to the Rust fallback bodies of +/// intrinsics. +// FIXME: the `Libcall` cases could probably all use the Rust fallback bodies instead, which would +// allow removing this enum. +enum FloatIntrinsicLowering { + Libcall(&'static str), Codegen(Value), } @@ -1099,8 +1102,8 @@ fn codegen_regular_intrinsic_call<'tcx>( layout.ty ); }; + use FloatIntrinsicLowering::*; use FloatTy::*; - use IntrinsicFallback::*; let x = arg1.load_scalar(fx); let y = arg2.load_scalar(fx); let z = arg3.load_scalar(fx); @@ -1109,7 +1112,7 @@ fn codegen_regular_intrinsic_call<'tcx>( // sofware emulation, use cranelift intrinsic analogous to llvm.fmuladd.*. (sym::fma | sym::fmuladd, F32 | F64) => Codegen(fx.bcx.ins().fma(x, y, z)), - (sym::fma, F128) => Fallback("fmaf128"), + (sym::fma, F128) => Libcall("fmaf128"), (sym::fmuladd, F128) | (_, F16) => { // We use the intrinsic fallback bodies for the rest @@ -1120,7 +1123,7 @@ fn codegen_regular_intrinsic_call<'tcx>( }; let val = match res { Codegen(val) => val, - Fallback(name) => { + Libcall(name) => { let ty = fx.clif_type(layout.ty).unwrap(); let arg = AbiParam::new(ty); fx.lib_call(name, vec![arg, arg, arg], vec![arg], &[x, y, z])[0] @@ -1141,14 +1144,14 @@ fn codegen_regular_intrinsic_call<'tcx>( layout.ty ); }; + use FloatIntrinsicLowering::*; use FloatTy::*; - use IntrinsicFallback::*; let x = arg1.load_scalar(fx); let y = arg2.load_scalar(fx); let res = match (intrinsic, float_ty) { - (sym::powf, F32) => Fallback("powf"), - (sym::powf, F64) => Fallback("pow"), - (sym::powf, F128) => Fallback("powf128"), + (sym::powf, F32) => Libcall("powf"), + (sym::powf, F64) => Libcall("pow"), + (sym::powf, F128) => Libcall("powf128"), (_, F16) => { // We use the intrinsic fallback bodies for the rest @@ -1159,7 +1162,7 @@ fn codegen_regular_intrinsic_call<'tcx>( }; let val = match res { Codegen(_) => span_bug!(source_info.span, "`powf` is always lowered to a libcall"), - Fallback(name) => { + Libcall(name) => { let ty = fx.clif_type(layout.ty).unwrap(); let arg = AbiParam::new(ty); fx.lib_call(name, vec![arg, arg], vec![arg], &[x, y])[0] @@ -1193,58 +1196,58 @@ fn codegen_regular_intrinsic_call<'tcx>( layout.ty ); }; + use FloatIntrinsicLowering::*; use FloatTy::*; - use IntrinsicFallback::*; let x = arg.load_scalar(fx); let res = match (intrinsic, float_ty) { (sym::fabs, F32 | F64) => Codegen(fx.bcx.ins().fabs(x)), (sym::sqrt, F32 | F64) => Codegen(fx.bcx.ins().sqrt(x)), - (sym::sqrt, F128) => Fallback("sqrtf128"), + (sym::sqrt, F128) => Libcall("sqrtf128"), (sym::floor, F32 | F64) => Codegen(fx.bcx.ins().floor(x)), - (sym::floor, F128) => Fallback("floorf128"), + (sym::floor, F128) => Libcall("floorf128"), (sym::ceil, F32 | F64) => Codegen(fx.bcx.ins().ceil(x)), - (sym::ceil, F128) => Fallback("ceilf128"), + (sym::ceil, F128) => Libcall("ceilf128"), (sym::trunc, F32 | F64) => Codegen(fx.bcx.ins().trunc(x)), - (sym::trunc, F128) => Fallback("truncf128"), + (sym::trunc, F128) => Libcall("truncf128"), (sym::round_ties_even, F32 | F64) => Codegen(fx.bcx.ins().nearest(x)), - (sym::round_ties_even, F128) => Fallback("rintf128"), + (sym::round_ties_even, F128) => Libcall("rintf128"), - (sym::round, F32) => Fallback("roundf"), - (sym::round, F64) => Fallback("round"), - (sym::round, F128) => Fallback("roundf128"), + (sym::round, F32) => Libcall("roundf"), + (sym::round, F64) => Libcall("round"), + (sym::round, F128) => Libcall("roundf128"), - (sym::exp, F32) => Fallback("expf"), - (sym::exp, F64) => Fallback("exp"), - (sym::exp, F128) => Fallback("expf128"), + (sym::exp, F32) => Libcall("expf"), + (sym::exp, F64) => Libcall("exp"), + (sym::exp, F128) => Libcall("expf128"), - (sym::exp2, F32) => Fallback("exp2f"), - (sym::exp2, F64) => Fallback("exp2"), - (sym::exp2, F128) => Fallback("exp2f128"), + (sym::exp2, F32) => Libcall("exp2f"), + (sym::exp2, F64) => Libcall("exp2"), + (sym::exp2, F128) => Libcall("exp2f128"), - (sym::log, F32) => Fallback("logf"), - (sym::log, F64) => Fallback("log"), - (sym::log, F128) => Fallback("logf128"), + (sym::log, F32) => Libcall("logf"), + (sym::log, F64) => Libcall("log"), + (sym::log, F128) => Libcall("logf128"), - (sym::log2, F32) => Fallback("log2f"), - (sym::log2, F64) => Fallback("log2"), - (sym::log2, F128) => Fallback("log2f128"), + (sym::log2, F32) => Libcall("log2f"), + (sym::log2, F64) => Libcall("log2"), + (sym::log2, F128) => Libcall("log2f128"), - (sym::log10, F32) => Fallback("log10f"), - (sym::log10, F64) => Fallback("log10"), - (sym::log10, F128) => Fallback("log10f128"), + (sym::log10, F32) => Libcall("log10f"), + (sym::log10, F64) => Libcall("log10"), + (sym::log10, F128) => Libcall("log10f128"), - (sym::sin, F32) => Fallback("sinf"), - (sym::sin, F64) => Fallback("sin"), - (sym::sin, F128) => Fallback("sinf128"), + (sym::sin, F32) => Libcall("sinf"), + (sym::sin, F64) => Libcall("sin"), + (sym::sin, F128) => Libcall("sinf128"), - (sym::cos, F32) => Fallback("cosf"), - (sym::cos, F64) => Fallback("cos"), - (sym::cos, F128) => Fallback("cosf128"), + (sym::cos, F32) => Libcall("cosf"), + (sym::cos, F64) => Libcall("cos"), + (sym::cos, F128) => Libcall("cosf128"), (sym::fabs, F128) | (_, F16) => { // FIXME(bytecodealliance/wasmtime#8312): Use the native operations once @@ -1257,7 +1260,7 @@ fn codegen_regular_intrinsic_call<'tcx>( }; let val = match res { Codegen(val) => val, - Fallback(name) => { + Libcall(name) => { let ty = fx.clif_type(layout.ty).unwrap(); fx.lib_call(name, vec![AbiParam::new(ty)], vec![AbiParam::new(ty)], &[x])[0] } From 624e4613ed4c4a448d31569f0f3767bf171aeec4 Mon Sep 17 00:00:00 2001 From: N1ark Date: Sun, 6 Sep 2026 18:14:25 +0100 Subject: [PATCH 17/39] Make `copysign` generic --- .../src/intrinsics/mod.rs | 99 +++++++------------ .../rustc_codegen_gcc/src/intrinsic/mod.rs | 33 ++----- .../src/back/llvm_backend.rs | 2 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 9 +- .../src/interpret/intrinsics.rs | 63 ++++++++---- .../rustc_hir_analysis/src/check/intrinsic.rs | 10 +- compiler/rustc_span/src/symbol.rs | 5 +- library/core/src/intrinsics/mod.rs | 45 ++------- library/core/src/num/f128.rs | 2 +- library/core/src/num/f16.rs | 2 +- library/core/src/num/f32.rs | 2 +- library/core/src/num/f64.rs | 2 +- 12 files changed, 106 insertions(+), 168 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 3e81c6367cdf7..7a68b628c9b6c 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -297,9 +297,6 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( target.expect("target for simd intrinsic"), source_info.span, ); - } else if codegen_float_intrinsic_call(fx, intrinsic, args, destination) { - let ret_block = fx.get_block(target.expect("target for float intrinsic")); - fx.bcx.ins().jump(ret_block, &[]); } else { codegen_regular_intrinsic_call( fx, @@ -315,67 +312,6 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( Ok(()) } -fn codegen_float_intrinsic_call<'tcx>( - fx: &mut FunctionCx<'_, '_, 'tcx>, - intrinsic: Symbol, - args: &[Spanned>], - ret: CPlace<'tcx>, -) -> bool { - let (name, arg_count, ty, clif_ty) = match intrinsic { - sym::copysignf16 => return false, // has a fallback - sym::copysignf32 => ("copysignf", 2, fx.tcx.types.f32, types::F32), - sym::copysignf64 => ("copysign", 2, fx.tcx.types.f64, types::F64), - sym::copysignf128 => return false, // has a fallback - - _ => return false, - }; - - if args.len() != arg_count { - bug!("wrong number of args for intrinsic {:?}", intrinsic); - } - - let (a, b, c); - let args = match args { - [x] => { - a = [codegen_operand(fx, &x.node).load_scalar(fx)]; - &a as &[_] - } - [x, y] => { - b = [ - codegen_operand(fx, &x.node).load_scalar(fx), - codegen_operand(fx, &y.node).load_scalar(fx), - ]; - &b - } - [x, y, z] => { - c = [ - codegen_operand(fx, &x.node).load_scalar(fx), - codegen_operand(fx, &y.node).load_scalar(fx), - codegen_operand(fx, &z.node).load_scalar(fx), - ]; - &c - } - _ => unreachable!(), - }; - - let layout = fx.layout_of(ty); - // FIXME(bytecodealliance/wasmtime#8312): Use native Cranelift operations - // for `f16` and `f128` once the lowerings have been implemented in Cranelift. - let val = match intrinsic { - sym::copysignf32 | sym::copysignf64 => fx.bcx.ins().fcopysign(args[0], args[1]), - - _ => { - let input_tys: Vec<_> = args.iter().map(|_| AbiParam::new(clif_ty)).collect(); - fx.lib_call(name, input_tys, vec![AbiParam::new(clif_ty)], args)[0] - } - }; - - let res = CValue::by_val(val, layout); - ret.write_cvalue(fx, res); - - true -} - /// How a float intrinsic is lowered: either directly to Cranelift instructions, or to a call to an /// external (libm/compiler-builtins) function. This is unrelated to the Rust fallback bodies of /// intrinsics. @@ -1172,6 +1108,41 @@ fn codegen_regular_intrinsic_call<'tcx>( ret.write_cvalue(fx, val); } + sym::copysign => { + intrinsic_args!(fx, args => (arg1, arg2); intrinsic); + let layout = arg1.layout(); + let ty::Float(float_ty) = layout.ty.kind() else { + span_bug!( + source_info.span, + "expected a float type for {:?} intrinsic, but got: {:?}", + intrinsic, + layout.ty + ); + }; + use FloatIntrinsicLowering::*; + use FloatTy::*; + let x = arg1.load_scalar(fx); + let y = arg2.load_scalar(fx); + let res = match (intrinsic, float_ty) { + (sym::copysign, F32 | F64) => Codegen(fx.bcx.ins().fcopysign(x, y)), + + (sym::copysign, F128) | (_, F16) => { + // We use the intrinsic fallback bodies for the rest + return Err(Instance::new_raw(instance.def_id(), instance.args)); + } + + _ => unreachable!(), + }; + let val = match res { + Codegen(val) => val, + Libcall(_) => { + span_bug!(source_info.span, "no libcall lowering for {:?}", intrinsic) + } + }; + let val = CValue::by_val(val, layout); + ret.write_cvalue(fx, val); + } + sym::fabs | sym::sqrt | sym::floor diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 5c616c60003b0..21f33a4599165 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -62,8 +62,6 @@ fn get_simple_intrinsic<'gcc, 'tcx>( sym::maximumf32 => return float_intrinsic(cx, cx.type_f32(), "fmaximumf"), sym::maximumf64 => return float_intrinsic(cx, cx.type_f64(), "fmaximum"), sym::maximumf128 => return float_intrinsic(cx, cx.type_f128(), "fmaximumf128"), - sym::copysignf32 => "copysignf", - sym::copysignf64 => "copysign", _ => return None, }; Some(cx.context.get_builtin_function(gcc_name)) @@ -76,6 +74,7 @@ fn get_simple_function_f128<'gcc, 'tcx>( ) -> Function<'gcc> { let f128_type = cx.type_f128(); let (func_name, args): (&str, &[gccjit::Type<'_>]) = match name { + sym::copysign => ("copysignf128", &[f128_type, f128_type]), sym::ceil => ("ceilf128", &[f128_type]), sym::cos => ("cosf128", &[f128_type]), sym::fabs => ("fabsf128", &[f128_type]), @@ -110,7 +109,7 @@ fn f16_builtin<'gcc, 'tcx>( let f32_type = cx.type_f32(); let builtin_name = match name { sym::ceil => "__builtin_ceilf", - sym::copysignf16 => "__builtin_copysignf", + sym::copysign => "__builtin_copysignf", sym::cos => "cosf", sym::exp => "expf", sym::exp2 => "exp2f", @@ -186,26 +185,6 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc &args.iter().map(|arg| arg.immediate()).collect::>(), ) } - sym::copysignf16 => f16_builtin(self, name, args), - sym::copysignf128 if self.cx.supports_f128_type => { - let f128_type = self.cx.type_f128(); - let func = self.cx.context.new_function( - None, - FunctionType::Extern, - f128_type, - &[ - self.cx.context.new_parameter(None, f128_type, "a"), - self.cx.context.new_parameter(None, f128_type, "b"), - ], - "copysignf128", - false, - ); - self.cx.context.new_call( - self.location, - func, - &args.iter().map(|arg| arg.immediate()).collect::>(), - ) - } sym::is_val_statically_known => { let a = args[0].immediate(); let builtin = self.context.get_builtin_function("__builtin_constant_p"); @@ -317,7 +296,8 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc } } } - sym::fabs + sym::copysign + | sym::fabs | sym::sqrt | sym::powf | sym::fma @@ -337,10 +317,13 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc | sym::powi => 'float_op: { let ty = args[0].layout.ty; let ty::Float(float_ty) = *ty.kind() else { - span_bug!(span, "expected float type for fabs intrinsic: {:?}", ty); + span_bug!(span, "expected float type for {:?} intrinsic: {:?}", name, ty); }; use ty::FloatTy::*; let func = match (name, float_ty) { + (sym::copysign, F32) => self.context.get_builtin_function("copysignf"), + (sym::copysign, F64) => self.context.get_builtin_function("copysign"), + (sym::fabs, F32) => self.context.get_builtin_function("fabsf"), (sym::fabs, F64) => self.context.get_builtin_function("fabs"), diff --git a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs index 3533262ee0c10..c0349b6003319 100644 --- a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs +++ b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs @@ -273,7 +273,7 @@ impl CodegenBackend for LlvmCodegenBackend { sym::round, sym::round_ties_even, sym::fma, - sym::copysignf16, sym::copysignf32, sym::copysignf64, sym::copysignf128, + sym::copysign, ]; will_not_use_fallback diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index fcc0e4818db51..1a4587133e0a7 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -70,11 +70,6 @@ fn call_simple_intrinsic<'ll, 'tcx>( sym::maximumf64 if fixed_minmax => ("llvm.maximum", &[bx.type_f64()]), sym::maximumf128 if fixed_minmax => ("llvm.maximum", &[bx.type_f128()]), - sym::copysignf16 => ("llvm.copysign", &[bx.type_f16()]), - sym::copysignf32 => ("llvm.copysign", &[bx.type_f32()]), - sym::copysignf64 => ("llvm.copysign", &[bx.type_f64()]), - sym::copysignf128 => ("llvm.copysign", &[bx.type_f128()]), - _ => return None, }; Some(bx.call_intrinsic( @@ -503,7 +498,8 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { } } - sym::fabs + sym::copysign + | sym::fabs | sym::sqrt | sym::powf | sym::fma @@ -532,6 +528,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { }; let llty = self.type_float_from_ty(*f); let llvm_name = match name { + sym::copysign => "llvm.copysign", sym::fabs => "llvm.fabs", sym::sqrt => "llvm.sqrt", sym::powf => "llvm.pow", diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index cb98672df7838..18f0f24d33194 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -626,10 +626,32 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } sym::maximumf128 => self.float_minmax_intrinsic::(args, MinMax::Maximum, dest)?, - sym::copysignf16 => self.float_copysign_intrinsic::(args, dest)?, - sym::copysignf32 => self.float_copysign_intrinsic::(args, dest)?, - sym::copysignf64 => self.float_copysign_intrinsic::(args, dest)?, - sym::copysignf128 => self.float_copysign_intrinsic::(args, dest)?, + sym::copysign => { + let arg1 = self.read_immediate(&args[0])?; + let arg2 = self.read_immediate(&args[1])?; + let ty::Float(float_ty) = arg1.layout.ty.kind() else { + span_bug!( + self.cur_span(), + "non-float type for float intrinsic: {}", + arg1.layout.ty, + ); + }; + let out_val = match float_ty { + FloatTy::F16 => { + self.binop_float_intrinsic::(intrinsic_name, arg1, arg2)? + } + FloatTy::F32 => { + self.binop_float_intrinsic::(intrinsic_name, arg1, arg2)? + } + FloatTy::F64 => { + self.binop_float_intrinsic::(intrinsic_name, arg1, arg2)? + } + FloatTy::F128 => { + self.binop_float_intrinsic::(intrinsic_name, arg1, arg2)? + } + }; + self.write_scalar(out_val, dest)?; + } sym::fabs | sym::floor | sym::ceil | sym::trunc | sym::round | sym::round_ties_even => { let arg = self.read_immediate(&args[0])?; @@ -1197,6 +1219,24 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } + fn binop_float_intrinsic( + &self, + name: Symbol, + arg1: ImmTy<'tcx, M::Provenance>, + arg2: ImmTy<'tcx, M::Provenance>, + ) -> InterpResult<'tcx, Scalar> + where + F: rustc_apfloat::Float + rustc_apfloat::FloatConvert + Into>, + { + let x: F = arg1.to_scalar().to_float()?; + let y: F = arg2.to_scalar().to_float()?; + match name { + // bitwise, no NaN adjustments + sym::copysign => interp_ok(x.copy_sign(y).into()), + _ => bug!("not a unary float intrinsic: {}", name), + } + } + fn float_minmax( &self, a: Scalar, @@ -1240,21 +1280,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { interp_ok(()) } - fn float_copysign_intrinsic( - &mut self, - args: &[OpTy<'tcx, M::Provenance>], - dest: &PlaceTy<'tcx, M::Provenance>, - ) -> InterpResult<'tcx, ()> - where - F: rustc_apfloat::Float + rustc_apfloat::FloatConvert + Into>, - { - let a: F = self.read_scalar(&args[0])?.to_float()?; - let b: F = self.read_scalar(&args[1])?.to_float()?; - // bitwise, no NaN adjustments - self.write_scalar(a.copy_sign(b), dest)?; - interp_ok(()) - } - fn float_round( &mut self, x: F, diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index cbacbd138500c..87339891e6b23 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -90,10 +90,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::contract_check_ensures | sym::contract_check_requires | sym::contract_checks - | sym::copysignf16 - | sym::copysignf32 - | sym::copysignf64 - | sym::copysignf128 + | sym::copysign | sym::cos | sym::ctlz | sym::ctpop @@ -473,10 +470,7 @@ pub(crate) fn check_intrinsic_type( sym::maximumf64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), sym::maximumf128 => (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128), - sym::copysignf16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::copysignf32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::copysignf64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::copysignf128 => (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128), + sym::copysign => (1, 0, vec![param(0), param(0)], param(0)), sym::powf => (1, 0, vec![param(0), param(0)], param(0)), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index f39cfacd6798c..9d1b01031a8b9 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -759,10 +759,7 @@ symbols! { copy, copy_closures, copy_nonoverlapping, - copysignf16, - copysignf32, - copysignf64, - copysignf128, + copysign, core, core_panic, core_panic_2015_macro, diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 5427990ec3d06..ecfea355fdea9 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -3452,47 +3452,18 @@ pub const fn fabs(x: T) -> T { T::from_bits(x.to_bits() & !T::SIGN_MASK) } -/// Copies the sign from `y` to `x` for `f16` values. +/// Copies the sign from `y` to `x` for floating-point values. /// -/// The stabilized version of this intrinsic is -/// [`f16::copysign`](../../std/primitive.f16.html#method.copysign) -#[inline] -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn copysignf16(x: f16, y: f16) -> f16 { - f16::from_bits((x.to_bits() & !f16::SIGN_MASK) | (y.to_bits() & f16::SIGN_MASK)) -} - -/// Copies the sign from `y` to `x` for `f32` values. -/// -/// The stabilized version of this intrinsic is -/// [`f32::copysign`](../../std/primitive.f32.html#method.copysign) -#[inline] -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn copysignf32(x: f32, y: f32) -> f32 { - f32::from_bits((x.to_bits() & !f32::SIGN_MASK) | (y.to_bits() & f32::SIGN_MASK)) -} -/// Copies the sign from `y` to `x` for `f64` values. -/// -/// The stabilized version of this intrinsic is -/// [`f64::copysign`](../../std/primitive.f64.html#method.copysign) -#[inline] -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn copysignf64(x: f64, y: f64) -> f64 { - f64::from_bits((x.to_bits() & !f64::SIGN_MASK) | (y.to_bits() & f64::SIGN_MASK)) -} - -/// Copies the sign from `y` to `x` for `f128` values. -/// -/// The stabilized version of this intrinsic is -/// [`f128::copysign`](../../std/primitive.f128.html#method.copysign) +/// The stabilized versions of this intrinsic are available on the float +/// primitives via the `copysign` method. For example, [`f32::copysign`]. #[inline] #[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] -pub const fn copysignf128(x: f128, y: f128) -> f128 { - f128::from_bits((x.to_bits() & !f128::SIGN_MASK) | (y.to_bits() & f128::SIGN_MASK)) +#[rustc_do_not_const_check] +#[miri::intrinsic_fallback_is_spec] +pub const fn copysign(x: T, y: T) -> T { + T::from_bits((x.to_bits() & !T::SIGN_MASK) | (y.to_bits() & T::SIGN_MASK)) } /// Generates the LLVM body for the automatic differentiation of `f` using Enzyme, diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index 74328cfdcb39f..b3eb7315d0f6b 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -1441,7 +1441,7 @@ impl f128 { #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn copysign(self, sign: f128) -> f128 { - intrinsics::copysignf128(self, sign) + intrinsics::copysign(self, sign) } /// Float addition that allows optimizations based on algebraic rules. diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index 023e6c56471ce..b63a795ece0e0 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -1425,7 +1425,7 @@ impl f16 { #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn copysign(self, sign: f16) -> f16 { - intrinsics::copysignf16(self, sign) + intrinsics::copysign(self, sign) } /// Float addition that allows optimizations based on algebraic rules. diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index 43f543c911ede..536607165a175 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -1598,7 +1598,7 @@ impl f32 { #[stable(feature = "copysign", since = "1.35.0")] #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] pub const fn copysign(self, sign: f32) -> f32 { - intrinsics::copysignf32(self, sign) + intrinsics::copysign(self, sign) } /// Float addition that allows optimizations based on algebraic rules. diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index 41a615613377a..a8cb8f2beef82 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -1577,7 +1577,7 @@ impl f64 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn copysign(self, sign: f64) -> f64 { - intrinsics::copysignf64(self, sign) + intrinsics::copysign(self, sign) } /// Float addition that allows optimizations based on algebraic rules. From 268bdaabaceb7688b974bae0f96b9c5c1b6ab991 Mon Sep 17 00:00:00 2001 From: N1ark Date: Mon, 7 Sep 2026 00:29:20 +0100 Subject: [PATCH 18/39] Make minimum/maximum generic --- .../src/intrinsics/mod.rs | 180 ++-------- .../rustc_codegen_gcc/src/intrinsic/mod.rs | 75 ++-- compiler/rustc_codegen_llvm/src/intrinsic.rs | 61 +--- .../src/interpret/intrinsics.rs | 80 +---- .../src/interpret/intrinsics/simd.rs | 8 +- .../rustc_hir_analysis/src/check/intrinsic.rs | 50 +-- compiler/rustc_span/src/symbol.rs | 20 +- library/core/src/intrinsics/bounds.rs | 53 ++- library/core/src/intrinsics/mod.rs | 334 ++---------------- library/core/src/num/f128.rs | 10 +- library/core/src/num/f16.rs | 10 +- library/core/src/num/f32.rs | 10 +- library/core/src/num/f64.rs | 10 +- src/tools/clippy/clippy_utils/src/sym.rs | 2 - .../codegen-llvm/force-intrinsic-fallback.rs | 10 +- 15 files changed, 198 insertions(+), 715 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 7a68b628c9b6c..e5cbca01aa051 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -1108,7 +1108,11 @@ fn codegen_regular_intrinsic_call<'tcx>( ret.write_cvalue(fx, val); } - sym::copysign => { + sym::copysign + | sym::minimum + | sym::maximum + | sym::minimum_number_nsz + | sym::maximum_number_nsz => { intrinsic_args!(fx, args => (arg1, arg2); intrinsic); let layout = arg1.layout(); let ty::Float(float_ty) = layout.ty.kind() else { @@ -1126,6 +1130,26 @@ fn codegen_regular_intrinsic_call<'tcx>( let res = match (intrinsic, float_ty) { (sym::copysign, F32 | F64) => Codegen(fx.bcx.ins().fcopysign(x, y)), + (sym::minimum, F32 | F64) => Codegen(fx.bcx.ins().fmin(x, y)), + (sym::maximum, F32 | F64) => Codegen(fx.bcx.ins().fmax(x, y)), + // FIXME(bytecodealliance/wasmtime#8312): Use `fmin`/`fmax` directly for `f16` and + // `f128` once the lowerings have been implemented in Cranelift. + (sym::minimum, F128) => Codegen(codegen_f16_f128::fmin_f128(fx, x, y)), + (sym::maximum, F128) => Codegen(codegen_f16_f128::fmax_f128(fx, x, y)), + (sym::minimum, F16) => { + Codegen(codegen_f16_f128::maybe_with_f16_to_f32_pair(fx, x, y, |fx, x, y| { + fx.bcx.ins().fmin(x, y) + })) + } + (sym::maximum, F16) => { + Codegen(codegen_f16_f128::maybe_with_f16_to_f32_pair(fx, x, y, |fx, x, y| { + fx.bcx.ins().fmax(x, y) + })) + } + + (sym::minimum_number_nsz, _) => Codegen(crate::num::codegen_float_min(fx, x, y)), + (sym::maximum_number_nsz, _) => Codegen(crate::num::codegen_float_max(fx, x, y)), + (sym::copysign, F128) | (_, F16) => { // We use the intrinsic fallback bodies for the rest return Err(Instance::new_raw(instance.def_id(), instance.args)); @@ -1240,160 +1264,6 @@ fn codegen_regular_intrinsic_call<'tcx>( ret.write_cvalue(fx, val); } - sym::minimumf16 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = codegen_f16_f128::maybe_with_f16_to_f32_pair(fx, a, b, |fx, a, b| { - fx.bcx.ins().fmin(a, b) - }); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f16)); - ret.write_cvalue(fx, val); - } - sym::minimumf32 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = fx.bcx.ins().fmin(a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); - ret.write_cvalue(fx, val); - } - sym::minimumf64 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = fx.bcx.ins().fmin(a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); - ret.write_cvalue(fx, val); - } - sym::minimumf128 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - // FIXME(bytecodealliance/wasmtime#8312): Use `fmin` once Cranelift - // backend lowerings are implemented. - let val = codegen_f16_f128::fmin_f128(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f128)); - ret.write_cvalue(fx, val); - } - sym::maximumf16 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = codegen_f16_f128::maybe_with_f16_to_f32_pair(fx, a, b, |fx, a, b| { - fx.bcx.ins().fmax(a, b) - }); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f16)); - ret.write_cvalue(fx, val); - } - sym::maximumf32 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = fx.bcx.ins().fmax(a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); - ret.write_cvalue(fx, val); - } - sym::maximumf64 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = fx.bcx.ins().fmax(a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); - ret.write_cvalue(fx, val); - } - sym::maximumf128 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - // FIXME(bytecodealliance/wasmtime#8312): Use `fmax` once Cranelift - // backend lowerings are implemented. - let val = codegen_f16_f128::fmax_f128(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f128)); - ret.write_cvalue(fx, val); - } - - sym::minimum_number_nsz_f16 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_min(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f16)); - ret.write_cvalue(fx, val); - } - sym::minimum_number_nsz_f32 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_min(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); - ret.write_cvalue(fx, val); - } - sym::minimum_number_nsz_f64 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_min(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); - ret.write_cvalue(fx, val); - } - sym::minimum_number_nsz_f128 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_min(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f128)); - ret.write_cvalue(fx, val); - } - sym::maximum_number_nsz_f16 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_max(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f16)); - ret.write_cvalue(fx, val); - } - sym::maximum_number_nsz_f32 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_max(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); - ret.write_cvalue(fx, val); - } - sym::maximum_number_nsz_f64 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_max(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); - ret.write_cvalue(fx, val); - } - sym::maximum_number_nsz_f128 => { - intrinsic_args!(fx, args => (a, b); intrinsic); - let a = a.load_scalar(fx); - let b = b.load_scalar(fx); - - let val = crate::num::codegen_float_max(fx, a, b); - let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f128)); - ret.write_cvalue(fx, val); - } - sym::catch_unwind => { let ret_block = fx.get_block(destination.unwrap()); diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 21f33a4599165..ca98ae6319b7f 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -35,36 +35,20 @@ use crate::context::CodegenCx; use crate::intrinsic::simd::generic_simd_intrinsic; use crate::type_of::LayoutGccExt; -fn float_intrinsic<'gcc, 'tcx>( +// GCC doesn't have the intrinsic we want so we use the compiler-builtins one +fn binop_libcall<'gcc, 'tcx>( cx: &CodegenCx<'gcc, 'tcx>, typ: Type<'gcc>, name: &str, -) -> Option> { - // GCC doesn't have the intrinsic we want so we use the compiler-builtins one - Some(cx.context.new_function( +) -> Function<'gcc> { + cx.context.new_function( None, FunctionType::Extern, typ, &[cx.context.new_parameter(None, typ, "a"), cx.context.new_parameter(None, typ, "b")], name, false, - )) -} - -fn get_simple_intrinsic<'gcc, 'tcx>( - cx: &CodegenCx<'gcc, 'tcx>, - name: Symbol, -) -> Option> { - let gcc_name = match name { - sym::minimumf32 => return float_intrinsic(cx, cx.type_f32(), "fminimumf"), - sym::minimumf64 => return float_intrinsic(cx, cx.type_f64(), "fminimum"), - sym::minimumf128 => return float_intrinsic(cx, cx.type_f128(), "fminimumf128"), - sym::maximumf32 => return float_intrinsic(cx, cx.type_f32(), "fmaximumf"), - sym::maximumf64 => return float_intrinsic(cx, cx.type_f64(), "fmaximum"), - sym::maximumf128 => return float_intrinsic(cx, cx.type_f128(), "fmaximumf128"), - _ => return None, - }; - Some(cx.context.get_builtin_function(gcc_name)) + ) } fn get_simple_function_f128<'gcc, 'tcx>( @@ -91,6 +75,8 @@ fn get_simple_function_f128<'gcc, 'tcx>( sym::sqrt => ("sqrtf128", &[f128_type]), sym::powf => ("powf128", &[f128_type, f128_type]), sym::fma => ("fmaf128", &[f128_type, f128_type, f128_type]), + sym::minimum => ("fminimumf128", &[f128_type, f128_type]), + sym::maximum => ("fmaximumf128", &[f128_type, f128_type]), _ => span_bug!(span, "used get_simple_function_f128 for unsupported f128 intrinsic"), }; let args: Vec<_> = args @@ -151,40 +137,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc let name_str = name.as_str(); let fn_args = instance.args; - let simple = get_simple_intrinsic(self, name); - let value = match name { - _ if let Some(func) = simple => self.cx.context.new_call( - self.location, - func, - &args.iter().map(|arg| arg.immediate()).collect::>(), - ), - // FIXME(antoyo): We can probably remove these and use the fallback intrinsic implementation. - sym::minimumf32 | sym::minimumf64 | sym::maximumf32 | sym::maximumf64 => { - let (ty, func_name) = match name { - sym::minimumf32 => (self.cx.float_type, "fminimumf"), - sym::maximumf32 => (self.cx.float_type, "fmaximumf"), - sym::minimumf64 => (self.cx.double_type, "fminimum"), - sym::maximumf64 => (self.cx.double_type, "fmaximum"), - _ => unreachable!(), - }; - let func = self.cx.context.new_function( - None, - FunctionType::Extern, - ty, - &[ - self.cx.context.new_parameter(None, ty, "a"), - self.cx.context.new_parameter(None, ty, "b"), - ], - func_name, - false, - ); - self.cx.context.new_call( - self.location, - func, - &args.iter().map(|arg| arg.immediate()).collect::>(), - ) - } sym::is_val_statically_known => { let a = args[0].immediate(); let builtin = self.context.get_builtin_function("__builtin_constant_p"); @@ -298,6 +251,8 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc } sym::copysign | sym::fabs + | sym::minimum + | sym::maximum | sym::sqrt | sym::powf | sym::fma @@ -327,6 +282,18 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc (sym::fabs, F32) => self.context.get_builtin_function("fabsf"), (sym::fabs, F64) => self.context.get_builtin_function("fabs"), + // FIXME(antoyo): We can probably remove these and use the fallback intrinsic implementation. + (sym::minimum, F32) => binop_libcall(self, self.type_f32(), "fminimumf"), + (sym::minimum, F64) => binop_libcall(self, self.type_f64(), "fminimum"), + (sym::maximum, F32) => binop_libcall(self, self.type_f32(), "fmaximumf"), + (sym::maximum, F64) => binop_libcall(self, self.type_f64(), "fmaximum"), + + // `f16` has no builtin for these, use the intrinsic fallback bodies instead. + (sym::minimum | sym::maximum, F16) => { + let fallback = Instance::new_raw(instance.def_id(), instance.args); + return IntrinsicResult::Fallback(fallback); + } + (sym::sqrt, F32) => self.context.get_builtin_function("sqrtf"), (sym::sqrt, F64) => self.context.get_builtin_function("sqrt"), diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 1a4587133e0a7..d2e4a15f3a8c1 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -48,37 +48,6 @@ use crate::llvm::{self, Attribute, AttributePlace, Metadata, Type, TypeKind, Val use crate::type_of::LayoutLlvmExt; use crate::va_arg::emit_va_arg; -fn call_simple_intrinsic<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - name: Symbol, - args: &[OperandRef<'tcx, Value<'ll>>], -) -> Option> { - let llvm_version = crate::llvm_util::get_version(); - // minimum/maximum were broken for f64/f128 before - // . - // We use the fallback body there. - let fixed_minmax = llvm_version >= (23, 0, 0); - - let (base_name, type_params): (&'static str, &[Type<'ll>]) = match name { - sym::minimumf16 => ("llvm.minimum", &[bx.type_f16()]), - sym::minimumf32 => ("llvm.minimum", &[bx.type_f32()]), - sym::minimumf64 if fixed_minmax => ("llvm.minimum", &[bx.type_f64()]), - sym::minimumf128 if fixed_minmax => ("llvm.minimum", &[bx.type_f128()]), - - sym::maximumf16 => ("llvm.maximum", &[bx.type_f16()]), - sym::maximumf32 => ("llvm.maximum", &[bx.type_f32()]), - sym::maximumf64 if fixed_minmax => ("llvm.maximum", &[bx.type_f64()]), - sym::maximumf128 if fixed_minmax => ("llvm.maximum", &[bx.type_f128()]), - - _ => return None, - }; - Some(bx.call_intrinsic( - base_name, - type_params, - &args.iter().map(|arg| arg.immediate()).collect::>(), - )) -} - impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { fn black_box(&mut self, result: PlaceRef<'tcx, Value<'ll>>, span: Span) { let result_val_span = [result.val.llval]; @@ -130,18 +99,9 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { let name = tcx.item_name(instance.def_id()); let fn_args = instance.args; - let simple = call_simple_intrinsic(self, name, args); let llval = match name { - _ if simple.is_some() => simple.unwrap(), - sym::minimum_number_nsz_f16 - | sym::minimum_number_nsz_f32 - | sym::minimum_number_nsz_f64 - | sym::minimum_number_nsz_f128 - | sym::maximum_number_nsz_f16 - | sym::maximum_number_nsz_f32 - | sym::maximum_number_nsz_f64 - | sym::maximum_number_nsz_f128 => { - let intrinsic_name = if name.as_str().starts_with("min") { + sym::minimum_number_nsz | sym::maximum_number_nsz => { + let intrinsic_name = if name == sym::minimum_number_nsz { "llvm.minimumnum" } else { "llvm.maximumnum" @@ -516,7 +476,9 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { | sym::log2 | sym::sin | sym::cos - | sym::powi => { + | sym::powi + | sym::minimum + | sym::maximum => { let ty = args[0].layout.ty; let ty::Float(f) = ty.kind() else { span_bug!( @@ -552,6 +514,19 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { sym::cos => "llvm.cos", sym::powi => "llvm.powi", + // minimum/maximum were broken for f64/f128 before + // . + // We use the fallback body there. + sym::minimum | sym::maximum + if llvm_version < (23, 0, 0) + && matches!(f, ty::FloatTy::F64 | ty::FloatTy::F128) => + { + let fallback = ty::Instance::new_raw(instance.def_id(), instance.args); + return IntrinsicResult::Fallback(fallback); + } + sym::minimum => "llvm.minimum", + sym::maximum => "llvm.maximum", + _ => bug!(), }; diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 18f0f24d33194..d9278c1d97a5e 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -582,51 +582,11 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?; } - sym::minimum_number_nsz_f16 => { - self.float_minmax_intrinsic::(args, MinMax::MinimumNumberNsz, dest)? - } - sym::minimum_number_nsz_f32 => { - self.float_minmax_intrinsic::(args, MinMax::MinimumNumberNsz, dest)? - } - sym::minimum_number_nsz_f64 => { - self.float_minmax_intrinsic::(args, MinMax::MinimumNumberNsz, dest)? - } - sym::minimum_number_nsz_f128 => { - self.float_minmax_intrinsic::(args, MinMax::MinimumNumberNsz, dest)? - } - - sym::minimumf16 => self.float_minmax_intrinsic::(args, MinMax::Minimum, dest)?, - sym::minimumf32 => { - self.float_minmax_intrinsic::(args, MinMax::Minimum, dest)? - } - sym::minimumf64 => { - self.float_minmax_intrinsic::(args, MinMax::Minimum, dest)? - } - sym::minimumf128 => self.float_minmax_intrinsic::(args, MinMax::Minimum, dest)?, - - sym::maximum_number_nsz_f16 => { - self.float_minmax_intrinsic::(args, MinMax::MaximumNumberNsz, dest)? - } - sym::maximum_number_nsz_f32 => { - self.float_minmax_intrinsic::(args, MinMax::MaximumNumberNsz, dest)? - } - sym::maximum_number_nsz_f64 => { - self.float_minmax_intrinsic::(args, MinMax::MaximumNumberNsz, dest)? - } - sym::maximum_number_nsz_f128 => { - self.float_minmax_intrinsic::(args, MinMax::MaximumNumberNsz, dest)? - } - - sym::maximumf16 => self.float_minmax_intrinsic::(args, MinMax::Maximum, dest)?, - sym::maximumf32 => { - self.float_minmax_intrinsic::(args, MinMax::Maximum, dest)? - } - sym::maximumf64 => { - self.float_minmax_intrinsic::(args, MinMax::Maximum, dest)? - } - sym::maximumf128 => self.float_minmax_intrinsic::(args, MinMax::Maximum, dest)?, - - sym::copysign => { + sym::minimum + | sym::maximum + | sym::minimum_number_nsz + | sym::maximum_number_nsz + | sym::copysign => { let arg1 = self.read_immediate(&args[0])?; let arg2 = self.read_immediate(&args[1])?; let ty::Float(float_ty) = arg1.layout.ty.kind() else { @@ -1233,21 +1193,20 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { match name { // bitwise, no NaN adjustments sym::copysign => interp_ok(x.copy_sign(y).into()), + + sym::minimum => self.float_minmax(x, y, MinMax::Minimum), + sym::maximum => self.float_minmax(x, y, MinMax::Maximum), + sym::minimum_number_nsz => self.float_minmax(x, y, MinMax::MinimumNumberNsz), + sym::maximum_number_nsz => self.float_minmax(x, y, MinMax::MaximumNumberNsz), + _ => bug!("not a unary float intrinsic: {}", name), } } - fn float_minmax( - &self, - a: Scalar, - b: Scalar, - op: MinMax, - ) -> InterpResult<'tcx, Scalar> + fn float_minmax(&self, a: F, b: F, op: MinMax) -> InterpResult<'tcx, Scalar> where F: rustc_apfloat::Float + rustc_apfloat::FloatConvert + Into>, { - let a: F = a.to_float()?; - let b: F = b.to_float()?; let res = if matches!(op, MinMax::MinimumNumberNsz | MinMax::MaximumNumberNsz) && a == b { // They are definitely not NaN (those are never equal), but they could be `+0` and `-0`. // Let the machine decide which one to return. @@ -1265,21 +1224,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { interp_ok(res.into()) } - fn float_minmax_intrinsic( - &mut self, - args: &[OpTy<'tcx, M::Provenance>], - op: MinMax, - dest: &PlaceTy<'tcx, M::Provenance>, - ) -> InterpResult<'tcx, ()> - where - F: rustc_apfloat::Float + rustc_apfloat::FloatConvert + Into>, - { - let res = - self.float_minmax::(self.read_scalar(&args[0])?, self.read_scalar(&args[1])?, op)?; - self.write_scalar(res, dest)?; - interp_ok(()) - } - fn float_round( &mut self, x: F, diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs index 9250aed30276e..091c732af82b4 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs @@ -808,10 +808,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let left = left.to_scalar(); let right = right.to_scalar(); interp_ok(match float_ty { - FloatTy::F16 => self.float_minmax::(left, right, op)?, - FloatTy::F32 => self.float_minmax::(left, right, op)?, - FloatTy::F64 => self.float_minmax::(left, right, op)?, - FloatTy::F128 => self.float_minmax::(left, right, op)?, + FloatTy::F16 => self.float_minmax::(left.to_float()?, right.to_float()?, op)?, + FloatTy::F32 => self.float_minmax::(left.to_float()?, right.to_float()?, op)?, + FloatTy::F64 => self.float_minmax::(left.to_float()?, right.to_float()?, op)?, + FloatTy::F128 => self.float_minmax::(left.to_float()?, right.to_float()?, op)?, }) } diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 87339891e6b23..9595d1cbb9428 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -119,22 +119,10 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::log | sym::log2 | sym::log10 - | sym::maximum_number_nsz_f16 - | sym::maximum_number_nsz_f32 - | sym::maximum_number_nsz_f64 - | sym::maximum_number_nsz_f128 - | sym::maximumf16 - | sym::maximumf32 - | sym::maximumf64 - | sym::maximumf128 - | sym::minimum_number_nsz_f16 - | sym::minimum_number_nsz_f32 - | sym::minimum_number_nsz_f64 - | sym::minimum_number_nsz_f128 - | sym::minimumf16 - | sym::minimumf32 - | sym::minimumf64 - | sym::minimumf128 + | sym::maximum + | sym::maximum_number_nsz + | sym::minimum + | sym::minimum_number_nsz | sym::mul_with_overflow | sym::needs_drop | sym::offload @@ -446,31 +434,11 @@ pub(crate) fn check_intrinsic_type( | sym::round | sym::sqrt => (1, 0, vec![param(0)], param(0)), - sym::minimum_number_nsz_f16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::minimum_number_nsz_f32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::minimum_number_nsz_f64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::minimum_number_nsz_f128 => { - (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128) - } - - sym::minimumf16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::minimumf32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::minimumf64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::minimumf128 => (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128), - - sym::maximum_number_nsz_f16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::maximum_number_nsz_f32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::maximum_number_nsz_f64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::maximum_number_nsz_f128 => { - (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128) - } - - sym::maximumf16 => (0, 0, vec![tcx.types.f16, tcx.types.f16], tcx.types.f16), - sym::maximumf32 => (0, 0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - sym::maximumf64 => (0, 0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - sym::maximumf128 => (0, 0, vec![tcx.types.f128, tcx.types.f128], tcx.types.f128), - - sym::copysign => (1, 0, vec![param(0), param(0)], param(0)), + sym::copysign + | sym::minimum + | sym::maximum + | sym::minimum_number_nsz + | sym::maximum_number_nsz => (1, 0, vec![param(0), param(0)], param(0)), sym::powf => (1, 0, vec![param(0), param(0)], param(0)), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 9d1b01031a8b9..57a5202730570 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1311,14 +1311,8 @@ symbols! { masked, match_beginning_vert, match_default_bindings, - maximum_number_nsz_f16, - maximum_number_nsz_f32, - maximum_number_nsz_f64, - maximum_number_nsz_f128, - maximumf16, - maximumf32, - maximumf64, - maximumf128, + maximum, + maximum_number_nsz, may_dangle, may_unwind, maybe_dangling, @@ -1350,14 +1344,8 @@ symbols! { min_generic_const_args, min_specialization, min_type_alias_impl_trait, - minimum_number_nsz_f16, - minimum_number_nsz_f32, - minimum_number_nsz_f64, - minimum_number_nsz_f128, - minimumf16, - minimumf32, - minimumf64, - minimumf128, + minimum, + minimum_number_nsz, mips, mips32r6, mips64, diff --git a/library/core/src/intrinsics/bounds.rs b/library/core/src/intrinsics/bounds.rs index 87d00ece91bc0..f6dfa5016c443 100644 --- a/library/core/src/intrinsics/bounds.rs +++ b/library/core/src/intrinsics/bounds.rs @@ -45,7 +45,7 @@ impl ChangePointee for *const T { /// # Safety /// Must actually *be* such a type. pub unsafe trait FloatPrimitive: - Sized + Copy + core::ops::Mul + core::ops::Add + Sized + Copy + PartialOrd + core::ops::Mul + core::ops::Add { type UInt: const core::ops::BitOr + const core::ops::BitAnd @@ -53,6 +53,9 @@ pub unsafe trait FloatPrimitive: const SIGN_MASK: Self::UInt; fn to_bits(self) -> Self::UInt; fn from_bits(bits: Self::UInt) -> Self; + fn is_nan(self) -> bool; + fn is_sign_positive(self) -> bool; + fn is_sign_negative(self) -> bool; } unsafe impl FloatPrimitive for f16 { @@ -66,6 +69,18 @@ unsafe impl FloatPrimitive for f16 { fn from_bits(bits: Self::UInt) -> Self { f16::from_bits(bits) } + #[inline] + fn is_nan(self) -> bool { + f16::is_nan(self) + } + #[inline] + fn is_sign_positive(self) -> bool { + f16::is_sign_positive(self) + } + #[inline] + fn is_sign_negative(self) -> bool { + f16::is_sign_negative(self) + } } unsafe impl FloatPrimitive for f32 { @@ -79,6 +94,18 @@ unsafe impl FloatPrimitive for f32 { fn from_bits(bits: Self::UInt) -> Self { f32::from_bits(bits) } + #[inline] + fn is_nan(self) -> bool { + f32::is_nan(self) + } + #[inline] + fn is_sign_positive(self) -> bool { + f32::is_sign_positive(self) + } + #[inline] + fn is_sign_negative(self) -> bool { + f32::is_sign_negative(self) + } } unsafe impl FloatPrimitive for f64 { @@ -92,6 +119,18 @@ unsafe impl FloatPrimitive for f64 { fn from_bits(bits: Self::UInt) -> Self { f64::from_bits(bits) } + #[inline] + fn is_nan(self) -> bool { + f64::is_nan(self) + } + #[inline] + fn is_sign_positive(self) -> bool { + f64::is_sign_positive(self) + } + #[inline] + fn is_sign_negative(self) -> bool { + f64::is_sign_negative(self) + } } unsafe impl FloatPrimitive for f128 { @@ -105,6 +144,18 @@ unsafe impl FloatPrimitive for f128 { fn from_bits(bits: Self::UInt) -> Self { f128::from_bits(bits) } + #[inline] + fn is_nan(self) -> bool { + f128::is_nan(self) + } + #[inline] + fn is_sign_positive(self) -> bool { + f128::is_sign_positive(self) + } + #[inline] + fn is_sign_negative(self) -> bool { + f128::is_sign_negative(self) + } } /// Built-in integer types (i8, i16, .., i128, isize, u8, u16, .., u128, usize). diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index ecfea355fdea9..0a170fae1e186 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -3043,7 +3043,7 @@ pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize); #[rustc_intrinsic] pub const unsafe fn write_bytes(dst: *mut T, val: u8, count: usize); -/// Returns the minimum of two `f16` values, ignoring NaN. +/// Returns the minimum of two floating-point values, ignoring NaN. /// /// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed /// zeros deterministically. In particular: @@ -3056,60 +3056,13 @@ pub const unsafe fn write_bytes(dst: *mut T, val: u8, count: usize); /// Therefore, implementations must not require the user to uphold /// any safety invariants. /// -/// The stabilized version of this intrinsic is [`f16::min`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimum_number_nsz_f16(x: f16, y: f16) -> f16 { - if x.is_nan() || y <= x { - y - } else { - // Either y > x or y is a NaN. - x - } -} - -/// Returns the minimum of two `f32` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f32::min`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimum_number_nsz_f32(x: f32, y: f32) -> f32 { - if x.is_nan() || y <= x { - y - } else { - // Either y > x or y is a NaN. - x - } -} - -/// Returns the minimum of two `f64` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f64::min`]. +/// The stabilized versions of this intrinsic are available on the float primitives via the +/// `min` method. For example, [`f32::min`]. #[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] -pub const fn minimum_number_nsz_f64(x: f64, y: f64) -> f64 { +#[rustc_do_not_const_check] +pub const fn minimum_number_nsz(x: T, y: T) -> T { if x.is_nan() || y <= x { y } else { @@ -3118,9 +3071,9 @@ pub const fn minimum_number_nsz_f64(x: f64, y: f64) -> f64 { } } -/// Returns the minimum of two `f128` values, ignoring NaN. +/// Returns the maximum of two floating-point values, ignoring NaN. /// -/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed +/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed /// zeros deterministically. In particular: /// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If /// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` @@ -3131,94 +3084,22 @@ pub const fn minimum_number_nsz_f64(x: f64, y: f64) -> f64 { /// Therefore, implementations must not require the user to uphold /// any safety invariants. /// -/// The stabilized version of this intrinsic is [`f128::min`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimum_number_nsz_f128(x: f128, y: f128) -> f128 { - if x.is_nan() || y <= x { - y - } else { - // Either y > x or y is a NaN. - x - } -} - -/// Returns the minimum of two `f16` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 minimum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimumf16(x: f16, y: f16) -> f16 { - if x < y { - x - } else if y < x { - y - } else if x == y { - if x.is_sign_negative() && y.is_sign_positive() { x } else { y } - } else { - // At least one input is NaN. Use `+` to perform NaN propagation and quieting. - x + y - } -} - -/// Returns the minimum of two `f32` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 minimum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. +/// The stabilized versions of this intrinsic are available on the float primitives via the +/// `max` method. For example, [`f32::max`]. #[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] -pub const fn minimumf32(x: f32, y: f32) -> f32 { - if x < y { - x - } else if y < x { +#[rustc_do_not_const_check] +pub const fn maximum_number_nsz(x: T, y: T) -> T { + if x.is_nan() || y >= x { y - } else if x == y { - if x.is_sign_negative() && y.is_sign_positive() { x } else { y } } else { - // At least one input is NaN. Use `+` to perform NaN propagation and quieting. - x + y - } -} - -/// Returns the minimum of two `f64` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 minimum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn minimumf64(x: f64, y: f64) -> f64 { - if x < y { + // Either y < x or y is a NaN. x - } else if y < x { - y - } else if x == y { - if x.is_sign_negative() && y.is_sign_positive() { x } else { y } - } else { - // At least one input is NaN. Use `+` to perform NaN propagation and quieting. - x + y } } -/// Returns the minimum of two `f128` values, propagating NaN. +/// Returns the minimum of two floating-point values, propagating NaN. /// /// This behaves like IEEE 754-2019 minimum. In particular: /// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. @@ -3229,8 +3110,10 @@ pub const fn minimumf64(x: f64, y: f64) -> f64 { /// Therefore, implementations must not require the user to uphold /// any safety invariants. #[rustc_nounwind] +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] -pub const fn minimumf128(x: f128, y: f128) -> f128 { +#[rustc_do_not_const_check] +pub const fn minimum(x: T, y: T) -> T { if x < y { x } else if y < x { @@ -3243,179 +3126,7 @@ pub const fn minimumf128(x: f128, y: f128) -> f128 { } } -/// Returns the maximum of two `f16` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f16::max`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximum_number_nsz_f16(x: f16, y: f16) -> f16 { - if x.is_nan() || y >= x { - y - } else { - // Either y < x or y is a NaN. - x - } -} - -/// Returns the maximum of two `f32` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f32::max`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximum_number_nsz_f32(x: f32, y: f32) -> f32 { - if x.is_nan() || y >= x { - y - } else { - // Either y < x or y is a NaN. - x - } -} - -/// Returns the maximum of two `f64` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f64::max`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximum_number_nsz_f64(x: f64, y: f64) -> f64 { - if x.is_nan() || y >= x { - y - } else { - // Either y < x or y is a NaN. - x - } -} - -/// Returns the maximum of two `f128` values, ignoring NaN. -/// -/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed -/// zeros deterministically. In particular: -/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If -/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` -/// and `-0.0`), either input may be returned non-deterministically. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -/// -/// The stabilized version of this intrinsic is [`f128::max`]. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximum_number_nsz_f128(x: f128, y: f128) -> f128 { - if x.is_nan() || y >= x { - y - } else { - // Either y < x or y is a NaN. - x - } -} - -/// Returns the maximum of two `f16` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 maximum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximumf16(x: f16, y: f16) -> f16 { - if x > y { - x - } else if y > x { - y - } else if x == y { - if x.is_sign_positive() && y.is_sign_negative() { x } else { y } - } else { - x + y - } -} - -/// Returns the maximum of two `f32` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 maximum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximumf32(x: f32, y: f32) -> f32 { - if x > y { - x - } else if y > x { - y - } else if x == y { - if x.is_sign_positive() && y.is_sign_negative() { x } else { y } - } else { - x + y - } -} - -/// Returns the maximum of two `f64` values, propagating NaN. -/// -/// This behaves like IEEE 754-2019 maximum. In particular: -/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. -/// For this operation, -0.0 is considered to be strictly less than +0.0. -/// -/// Note that, unlike most intrinsics, this is safe to call; -/// it does not require an `unsafe` block. -/// Therefore, implementations must not require the user to uphold -/// any safety invariants. -#[rustc_nounwind] -#[rustc_intrinsic] -pub const fn maximumf64(x: f64, y: f64) -> f64 { - if x > y { - x - } else if y > x { - y - } else if x == y { - if x.is_sign_positive() && y.is_sign_negative() { x } else { y } - } else { - x + y - } -} - -/// Returns the maximum of two `f128` values, propagating NaN. +/// Returns the maximum of two floating-point values, propagating NaN. /// /// This behaves like IEEE 754-2019 maximum. In particular: /// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. @@ -3426,8 +3137,10 @@ pub const fn maximumf64(x: f64, y: f64) -> f64 { /// Therefore, implementations must not require the user to uphold /// any safety invariants. #[rustc_nounwind] +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] -pub const fn maximumf128(x: f128, y: f128) -> f128 { +#[rustc_do_not_const_check] +pub const fn maximum(x: T, y: T) -> T { if x > y { x } else if y > x { @@ -3435,6 +3148,7 @@ pub const fn maximumf128(x: f128, y: f128) -> f128 { } else if x == y { if x.is_sign_positive() && y.is_sign_negative() { x } else { y } } else { + // At least one input is NaN. Use `+` to perform NaN propagation and quieting. x + y } } diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index b3eb7315d0f6b..6b1622b21773f 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -620,7 +620,7 @@ impl f128 { #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn max(self, other: f128) -> f128 { - intrinsics::maximum_number_nsz_f128(self, other) + intrinsics::maximum_number_nsz(self, other) } /// Returns the minimum of the two numbers, ignoring NaN. @@ -651,7 +651,7 @@ impl f128 { #[rustc_const_unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn min(self, other: f128) -> f128 { - intrinsics::minimum_number_nsz_f128(self, other) + intrinsics::minimum_number_nsz(self, other) } /// Returns the maximum of the two numbers, propagating NaN. @@ -680,10 +680,11 @@ impl f128 { /// ``` #[inline] #[unstable(feature = "f128", issue = "116909")] + #[rustc_const_unstable(feature = "f128", issue = "116909")] // #[unstable(feature = "float_minimum_maximum", issue = "91079")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn maximum(self, other: f128) -> f128 { - intrinsics::maximumf128(self, other) + intrinsics::maximum(self, other) } /// Returns the minimum of the two numbers, propagating NaN. @@ -712,10 +713,11 @@ impl f128 { /// ``` #[inline] #[unstable(feature = "f128", issue = "116909")] + #[rustc_const_unstable(feature = "f128", issue = "116909")] // #[unstable(feature = "float_minimum_maximum", issue = "91079")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn minimum(self, other: f128) -> f128 { - intrinsics::minimumf128(self, other) + intrinsics::minimum(self, other) } /// Calculates the midpoint (average) between `self` and `rhs`. diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index b63a795ece0e0..32a37b6329dc2 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -614,7 +614,7 @@ impl f16 { #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn max(self, other: f16) -> f16 { - intrinsics::maximum_number_nsz_f16(self, other) + intrinsics::maximum_number_nsz(self, other) } /// Returns the minimum of the two numbers, ignoring NaN. @@ -645,7 +645,7 @@ impl f16 { #[rustc_const_unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn min(self, other: f16) -> f16 { - intrinsics::minimum_number_nsz_f16(self, other) + intrinsics::minimum_number_nsz(self, other) } /// Returns the maximum of the two numbers, propagating NaN. @@ -674,10 +674,11 @@ impl f16 { /// ``` #[inline] #[unstable(feature = "f16", issue = "116909")] + #[rustc_const_unstable(feature = "f16", issue = "116909")] // #[unstable(feature = "float_minimum_maximum", issue = "91079")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn maximum(self, other: f16) -> f16 { - intrinsics::maximumf16(self, other) + intrinsics::maximum(self, other) } /// Returns the minimum of the two numbers, propagating NaN. @@ -706,10 +707,11 @@ impl f16 { /// ``` #[inline] #[unstable(feature = "f16", issue = "116909")] + #[rustc_const_unstable(feature = "f16", issue = "116909")] // #[unstable(feature = "float_minimum_maximum", issue = "91079")] #[must_use = "this returns the result of the comparison, without modifying either input"] pub const fn minimum(self, other: f16) -> f16 { - intrinsics::minimumf16(self, other) + intrinsics::minimum(self, other) } /// Calculates the midpoint (average) between `self` and `rhs`. diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index 536607165a175..722c3c32976a4 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -832,7 +832,7 @@ impl f32 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn max(self, other: f32) -> f32 { - intrinsics::maximum_number_nsz_f32(self, other) + intrinsics::maximum_number_nsz(self, other) } /// Returns the minimum of the two numbers, ignoring NaN. @@ -859,7 +859,7 @@ impl f32 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn min(self, other: f32) -> f32 { - intrinsics::minimum_number_nsz_f32(self, other) + intrinsics::minimum_number_nsz(self, other) } /// Returns the maximum of the two numbers, propagating NaN. @@ -884,9 +884,10 @@ impl f32 { /// ``` #[must_use = "this returns the result of the comparison, without modifying either input"] #[unstable(feature = "float_minimum_maximum", issue = "91079")] + #[rustc_const_unstable(feature = "float_minimum_maximum", issue = "91079")] #[inline] pub const fn maximum(self, other: f32) -> f32 { - intrinsics::maximumf32(self, other) + intrinsics::maximum(self, other) } /// Returns the minimum of the two numbers, propagating NaN. @@ -911,9 +912,10 @@ impl f32 { /// ``` #[must_use = "this returns the result of the comparison, without modifying either input"] #[unstable(feature = "float_minimum_maximum", issue = "91079")] + #[rustc_const_unstable(feature = "float_minimum_maximum", issue = "91079")] #[inline] pub const fn minimum(self, other: f32) -> f32 { - intrinsics::minimumf32(self, other) + intrinsics::minimum(self, other) } /// Calculates the midpoint (average) between `self` and `rhs`. diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index a8cb8f2beef82..af7217d7d3293 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -833,7 +833,7 @@ impl f64 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn max(self, other: f64) -> f64 { - intrinsics::maximum_number_nsz_f64(self, other) + intrinsics::maximum_number_nsz(self, other) } /// Returns the minimum of the two numbers, ignoring NaN. @@ -860,7 +860,7 @@ impl f64 { #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")] #[inline] pub const fn min(self, other: f64) -> f64 { - intrinsics::minimum_number_nsz_f64(self, other) + intrinsics::minimum_number_nsz(self, other) } /// Returns the maximum of the two numbers, propagating NaN. @@ -885,9 +885,10 @@ impl f64 { /// ``` #[must_use = "this returns the result of the comparison, without modifying either input"] #[unstable(feature = "float_minimum_maximum", issue = "91079")] + #[rustc_const_unstable(feature = "float_minimum_maximum", issue = "91079")] #[inline] pub const fn maximum(self, other: f64) -> f64 { - intrinsics::maximumf64(self, other) + intrinsics::maximum(self, other) } /// Returns the minimum of the two numbers, propagating NaN. @@ -912,9 +913,10 @@ impl f64 { /// ``` #[must_use = "this returns the result of the comparison, without modifying either input"] #[unstable(feature = "float_minimum_maximum", issue = "91079")] + #[rustc_const_unstable(feature = "float_minimum_maximum", issue = "91079")] #[inline] pub const fn minimum(self, other: f64) -> f64 { - intrinsics::minimumf64(self, other) + intrinsics::minimum(self, other) } /// Calculates the midpoint (average) between `self` and `rhs`. diff --git a/src/tools/clippy/clippy_utils/src/sym.rs b/src/tools/clippy/clippy_utils/src/sym.rs index 3b5ddbbaf6420..79ebe78ceb764 100644 --- a/src/tools/clippy/clippy_utils/src/sym.rs +++ b/src/tools/clippy/clippy_utils/src/sym.rs @@ -438,7 +438,6 @@ generate! { max_by, max_by_key, max_value, - maximum, may_panic, mem_align_of, mem_replace, @@ -448,7 +447,6 @@ generate! { min_by, min_by_key, min_value, - minimum, mode, module_name_repetitions, msrv, diff --git a/tests/codegen-llvm/force-intrinsic-fallback.rs b/tests/codegen-llvm/force-intrinsic-fallback.rs index 3a934b27f828e..a43cfbda244d8 100644 --- a/tests/codegen-llvm/force-intrinsic-fallback.rs +++ b/tests/codegen-llvm/force-intrinsic-fallback.rs @@ -10,15 +10,15 @@ // With the flag, the fallback body is called instead. #[no_mangle] -pub fn call_minimumf32(x: f32, y: f32) -> f32 { - // CHECK-LABEL: @call_minimumf32 +pub fn call_minimum_f32(x: f32, y: f32) -> f32 { + // CHECK-LABEL: @call_minimum_f32 // NORMAL: call float @llvm.minimum.f32 - // NORMAL-NOT: minimumf32 + // NORMAL-NOT: intrinsics{{.*}}minimum // FALLBACK-NOT: @llvm.minimum - // FALLBACK: call {{.*}}minimumf32 - core::intrinsics::minimumf32(x, y) + // FALLBACK: call {{.*}}intrinsics{{.*}}minimum + core::intrinsics::minimum(x, y) } // Codegen backends can return a list of `replaced_intrinsics`, for which codegen of the fallback is From cc56d88e74855d3c2265a9f0f77a7c34c62dc75a Mon Sep 17 00:00:00 2001 From: N1ark Date: Mon, 7 Sep 2026 12:00:09 +0100 Subject: [PATCH 19/39] Replace float bound impls with a macro --- library/core/src/intrinsics/bounds.rs | 128 ++++-------------- ...d-intrinsic-monomorphization-bounds.stderr | 7 +- 2 files changed, 33 insertions(+), 102 deletions(-) diff --git a/library/core/src/intrinsics/bounds.rs b/library/core/src/intrinsics/bounds.rs index f6dfa5016c443..4f50c328e22fb 100644 --- a/library/core/src/intrinsics/bounds.rs +++ b/library/core/src/intrinsics/bounds.rs @@ -58,105 +58,35 @@ pub unsafe trait FloatPrimitive: fn is_sign_negative(self) -> bool; } -unsafe impl FloatPrimitive for f16 { - type UInt = u16; - const SIGN_MASK: Self::UInt = f16::SIGN_MASK; - #[inline] - fn to_bits(self) -> Self::UInt { - f16::to_bits(self) - } - #[inline] - fn from_bits(bits: Self::UInt) -> Self { - f16::from_bits(bits) - } - #[inline] - fn is_nan(self) -> bool { - f16::is_nan(self) - } - #[inline] - fn is_sign_positive(self) -> bool { - f16::is_sign_positive(self) - } - #[inline] - fn is_sign_negative(self) -> bool { - f16::is_sign_negative(self) - } -} - -unsafe impl FloatPrimitive for f32 { - type UInt = u32; - const SIGN_MASK: Self::UInt = f32::SIGN_MASK; - #[inline] - fn to_bits(self) -> Self::UInt { - f32::to_bits(self) - } - #[inline] - fn from_bits(bits: Self::UInt) -> Self { - f32::from_bits(bits) - } - #[inline] - fn is_nan(self) -> bool { - f32::is_nan(self) - } - #[inline] - fn is_sign_positive(self) -> bool { - f32::is_sign_positive(self) - } - #[inline] - fn is_sign_negative(self) -> bool { - f32::is_sign_negative(self) - } -} - -unsafe impl FloatPrimitive for f64 { - type UInt = u64; - const SIGN_MASK: Self::UInt = f64::SIGN_MASK; - #[inline] - fn to_bits(self) -> Self::UInt { - f64::to_bits(self) - } - #[inline] - fn from_bits(bits: Self::UInt) -> Self { - f64::from_bits(bits) - } - #[inline] - fn is_nan(self) -> bool { - f64::is_nan(self) - } - #[inline] - fn is_sign_positive(self) -> bool { - f64::is_sign_positive(self) - } - #[inline] - fn is_sign_negative(self) -> bool { - f64::is_sign_negative(self) - } -} - -unsafe impl FloatPrimitive for f128 { - type UInt = u128; - const SIGN_MASK: Self::UInt = f128::SIGN_MASK; - #[inline] - fn to_bits(self) -> Self::UInt { - f128::to_bits(self) - } - #[inline] - fn from_bits(bits: Self::UInt) -> Self { - f128::from_bits(bits) - } - #[inline] - fn is_nan(self) -> bool { - f128::is_nan(self) - } - #[inline] - fn is_sign_positive(self) -> bool { - f128::is_sign_positive(self) - } - #[inline] - fn is_sign_negative(self) -> bool { - f128::is_sign_negative(self) - } -} +macro_rules! impl_float_primitive { + ($($float:ident => $bits:ident),+) => {$( + unsafe impl FloatPrimitive for $float { + type UInt = $bits; + const SIGN_MASK: Self::UInt = $float::SIGN_MASK; + #[inline] + fn to_bits(self) -> Self::UInt { + $float::to_bits(self) + } + #[inline] + fn from_bits(bits: Self::UInt) -> Self { + $float::from_bits(bits) + } + #[inline] + fn is_nan(self) -> bool { + $float::is_nan(self) + } + #[inline] + fn is_sign_positive(self) -> bool { + $float::is_sign_positive(self) + } + #[inline] + fn is_sign_negative(self) -> bool { + $float::is_sign_negative(self) + } + } + )+}; +} +impl_float_primitive!(f16 => u16, f32 => u32, f64 => u64, f128 => u128); /// Built-in integer types (i8, i16, .., i128, isize, u8, u16, .., u128, usize). /// diff --git a/tests/ui/intrinsics/bad-intrinsic-monomorphization-bounds.stderr b/tests/ui/intrinsics/bad-intrinsic-monomorphization-bounds.stderr index 148e6ea1e6aca..37a10e8fe35d1 100644 --- a/tests/ui/intrinsics/bad-intrinsic-monomorphization-bounds.stderr +++ b/tests/ui/intrinsics/bad-intrinsic-monomorphization-bounds.stderr @@ -14,19 +14,20 @@ LL | pub struct Foo(i64); | ^^^^^^^^^^^^^^ help: the following other types implement trait `intrinsics::bounds::FloatPrimitive` --> $SRC_DIR/core/src/intrinsics/bounds.rs:LL:COL + | + = note: `f128` | = note: `f16` - ::: $SRC_DIR/core/src/intrinsics/bounds.rs:LL:COL | = note: `f32` - ::: $SRC_DIR/core/src/intrinsics/bounds.rs:LL:COL | = note: `f64` ::: $SRC_DIR/core/src/intrinsics/bounds.rs:LL:COL | - = note: `f128` + = note: in this macro invocation note: required by a bound in `fadd_fast` --> $SRC_DIR/core/src/intrinsics/mod.rs:LL:COL + = note: this error originates in the macro `impl_float_primitive` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error From 6054bc3f5fab59aadd4f6a6be2c31a04558ea10a Mon Sep 17 00:00:00 2001 From: N1ark Date: Mon, 7 Sep 2026 13:11:43 +0100 Subject: [PATCH 20/39] De-constify the `FloatPrimitive` sealed trait --- library/core/src/intrinsics/bounds.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/core/src/intrinsics/bounds.rs b/library/core/src/intrinsics/bounds.rs index 4f50c328e22fb..1a7f5d5e8c5af 100644 --- a/library/core/src/intrinsics/bounds.rs +++ b/library/core/src/intrinsics/bounds.rs @@ -47,9 +47,9 @@ impl ChangePointee for *const T { pub unsafe trait FloatPrimitive: Sized + Copy + PartialOrd + core::ops::Mul + core::ops::Add { - type UInt: const core::ops::BitOr - + const core::ops::BitAnd - + const core::ops::Not; + type UInt: core::ops::BitOr + + core::ops::BitAnd + + core::ops::Not; const SIGN_MASK: Self::UInt; fn to_bits(self) -> Self::UInt; fn from_bits(bits: Self::UInt) -> Self; From 4b1ebeb931b6549e3153eda2ec8bd661eb45893c Mon Sep 17 00:00:00 2001 From: N1ark Date: Mon, 7 Sep 2026 13:12:14 +0100 Subject: [PATCH 21/39] Add test --- tests/ui/consts/const-float-intrinsics.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/tests/ui/consts/const-float-intrinsics.rs b/tests/ui/consts/const-float-intrinsics.rs index d0678f3a7985a..56c47e8c5791a 100644 --- a/tests/ui/consts/const-float-intrinsics.rs +++ b/tests/ui/consts/const-float-intrinsics.rs @@ -1,16 +1,27 @@ //@ check-pass // Check that the float intrinsics carrying `#[rustc_do_not_const_check]` can actually be called in -// a const context, for every float width. Their fallback bodies call into `libm`, but const-eval -// overrides them. +// a const context, for every float width. Their bodies are never const-checked and never run by +// const-eval, which has to implement each of these intrinsics itself. #![feature(core_intrinsics, f16, f128)] -use std::intrinsics::{ceil, floor, fma, fmuladd, round, round_ties_even, trunc}; +use std::intrinsics::{ + ceil, copysign, fabs, floor, fma, fmuladd, maximum, maximum_number_nsz, minimum, + minimum_number_nsz, round, round_ties_even, trunc, +}; macro_rules! check { ($ty:ident) => { const _: () = { + assert!(fabs(-2.5 as $ty) == 2.5); + assert!(copysign(2.5 as $ty, -1.0) == -2.5); + + assert!(minimum(1.0 as $ty, 2.0) == 1.0); + assert!(maximum(1.0 as $ty, 2.0) == 2.0); + assert!(minimum_number_nsz($ty::NAN, 2.0) == 2.0); + assert!(maximum_number_nsz($ty::NAN, 2.0) == 2.0); + assert!(floor(-2.5 as $ty) == -3.0); assert!(ceil(-2.5 as $ty) == -2.0); assert!(trunc(-2.5 as $ty) == -2.0); From 8b24bbd99072010b8ffc57e98ad7b5848e232866 Mon Sep 17 00:00:00 2001 From: Romain Perier Date: Wed, 7 Oct 2026 17:33:33 +0200 Subject: [PATCH 22/39] Improve collapsed suggestions for trait impls tuples Currently this collapsed output only works when all the candidates implement the same trait and are continious over their arity by step of 1. Sometimes we might find candidates that do not all implement the same trait but which contains subsets of continious tuples all implementing the same trait. --- .../traits/fulfillment_errors.rs | 123 +++++++++++++----- ...ment_different_trait_continuous_arities.rs | 21 +++ ..._different_trait_continuous_arities.stderr | 28 ++++ ...ement_same_trait_continuous_arities.stderr | 4 +- 4 files changed, 138 insertions(+), 38 deletions(-) create mode 100644 tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.rs create mode 100644 tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.stderr diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 13ee44fd6bb5e..fd9f76fbeded6 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -2680,11 +2680,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { types.dedup(); let all_types_equal = types.len() == 1; - let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose { - candidates.len() - } else { - 8 - }; if candidates.len() < 5 { let spans: Vec<_> = candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect(); @@ -2728,7 +2723,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let mut tuple_min_arity = usize::MAX; let mut tuple_max_arity = 0_usize; let mut last_arity = None; - let mut all_types_tuples_cont_arity = true; + let mut all_tuples_cont_arity = true; candidates.sort_by(|(c1, _), (c2, _)| { if let ty::Tuple(tys1) = c1.self_ty().kind() && let ty::Tuple(tys2) = c2.self_ty().kind() @@ -2738,24 +2733,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { std::cmp::Ordering::Equal } }); - let candidate_names: Vec = candidates + + let mut candidate_names: Vec = candidates .iter() .map(|(c, _)| { if all_traits_equal { - if all_types_tuples_cont_arity - && let ty::Tuple(tys) = c.self_ty().kind() - && last_arity.map_or(1, |a: usize| a.abs_diff(tys.len())) == 1 - { - last_arity = Some(tys.len()); - if tys.len() > tuple_max_arity { - tuple_max_arity = tys.len(); - } - if tys.len() < tuple_min_arity { - tuple_min_arity = tys.len(); - } - } else { - all_types_tuples_cont_arity = false; - } format!( "\n {}", self.tcx.short_string(c.self_ty(), err.long_ty_path()) @@ -2777,28 +2759,97 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }) .collect(); - let details = if all_traits_equal && all_types_tuples_cont_arity { - if tuple_min_arity == 0 { + let mut all_tuples_impl_the_same_trait = true; + let mut last_tuple_trait_ref = None; + + fn have_same_trait_path(a: &TraitRef<'_>, b: &TraitRef<'_>) -> bool { + a.print_only_trait_path().to_string() == b.print_only_trait_path().to_string() + } + // `candidates` can contain only tuples or a variety of other types that include tuples. + // Find and locates tuples in `candidates` and computes some metrics: checks if they + // are continuous by arity, if so compute the min and the max arity of these tuples and + // check if they implement all the same trait or not. + let (tuples_candidates, tuples_range) = { + let tuples_indexes: Vec = candidates + .iter() + .enumerate() + .filter_map(|(idx, (c, _))| { + if let ty::Tuple(tys) = c.self_ty().kind() { + if all_tuples_cont_arity + && last_arity.map_or(1, |a: usize| a.abs_diff(tys.len())) == 1 + { + last_arity = Some(tys.len()); + if tys.len() > tuple_max_arity { + tuple_max_arity = tys.len(); + } + if tys.len() < tuple_min_arity { + tuple_min_arity = tys.len(); + } + if all_tuples_impl_the_same_trait + && have_same_trait_path( + last_tuple_trait_ref.map_or(c, |e: &TraitRef<'_>| e), + c, + ) + { + last_tuple_trait_ref = Some(c); + } else { + all_tuples_impl_the_same_trait = false; + } + } else { + all_tuples_cont_arity = false; + } + Some(idx) + } else { + None + } + }) + .collect(); + let (start, end) = ( + tuples_indexes.first().map_or_default(|idx| *idx), + tuples_indexes.last().map_or_default(|idx| *idx + 1), + ); + (&candidates[start..end], start..end) + }; + + // When all the types contained in `candidates` are tuples that are contiguous by arity + // and implement the same trait, or when there exists a subset of tuples in `candidates` + // that are contiguous by arity and implement the same trait, then the list of tuples can + // be factorized from `candidates_names`. + if !tuples_candidates.is_empty() + && all_tuples_cont_arity + && (all_traits_equal || all_tuples_impl_the_same_trait) + { + let details = if tuple_min_arity == 0 { format!("up to tuples of arity {tuple_max_arity}") + } else if !all_traits_equal { + format!("for tuples of arity {tuple_min_arity} to {tuple_max_arity}") } else { format!( "for tuples of arity {tuple_min_arity} up to and including {tuple_max_arity}" ) - } - } else { - String::new() - }; - let (candidate_names, end) = if all_traits_equal && all_types_tuples_cont_arity { - ( - vec![ - // (T₁, T₂, …, Tₙ) - format!("\n (T\u{2081}, T\u{2082}, …, T\u{2099}) {details}"), - ], - 1, - ) + }; + let impl_trait = if all_traits_equal { + String::new() + } else { + let c = tuples_candidates[0].0; + format!( + " implements `{}`", + self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()) + ) + }; + let simplified_output = [ + // (T₁, T₂, …, Tₙ) + format!("\n `(T\u{2081}, T\u{2082}, …, T\u{2099})` {details}{impl_trait}"), + ]; + candidate_names.splice(tuples_range, simplified_output); + } + + let end = if candidate_names.len() <= 9 || self.tcx.sess.opts.verbose { + candidate_names.len() } else { - (candidate_names, end) + 8 }; + let msg = if all_types_equal { format!( "`{}` implements trait `{}`", diff --git a/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.rs b/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.rs new file mode 100644 index 0000000000000..e26ab7f62a2ba --- /dev/null +++ b/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.rs @@ -0,0 +1,21 @@ +fn testing_mytrait(_: T) where T: MyTrait {} + +trait MyTrait {} + +impl MyTrait for Vec where T: MyTrait {} +impl MyTrait for &T where T: MyTrait {} +impl MyTrait for [T] where T: MyTrait {} +impl MyTrait for [T;2] where T: MyTrait {} + +impl MyTrait for (T1,) where T1: MyTrait {} +impl MyTrait for (T1, T2) where T1: MyTrait {} +impl MyTrait for (T1, T2, T3) where T1: MyTrait {} +impl MyTrait for (T1, T2, T3, T4) where T1: MyTrait {} +impl MyTrait for (T1, T2, T3, T4, T5) where T1: MyTrait {} + +struct Foo; + +fn main() { + testing_mytrait(Foo); + //~^ ERROR the trait bound `Foo: MyTrait` is not satisfied [E0277] +} diff --git a/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.stderr b/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.stderr new file mode 100644 index 0000000000000..366e204948974 --- /dev/null +++ b/tests/ui/suggestions/multiple_tuples_implement_different_trait_continuous_arities.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `Foo: MyTrait` is not satisfied + --> $DIR/multiple_tuples_implement_different_trait_continuous_arities.rs:19:21 + | +LL | testing_mytrait(Foo); + | --------------- ^^^ unsatisfied trait bound + | | + | required by a bound introduced by this call + | +help: the trait `MyTrait` is not implemented for `Foo` + --> $DIR/multiple_tuples_implement_different_trait_continuous_arities.rs:16:1 + | +LL | struct Foo; + | ^^^^^^^^^^ + = help: the following other types implement trait `MyTrait`: + `&T` implements `MyTrait` + `(T₁, T₂, …, Tₙ)` for tuples of arity 1 to 5 implements `MyTrait` + `Vec` implements `MyTrait` + `[T; 2]` implements `MyTrait` + `[T]` implements `MyTrait` +note: required by a bound in `testing_mytrait` + --> $DIR/multiple_tuples_implement_different_trait_continuous_arities.rs:1:38 + | +LL | fn testing_mytrait(_: T) where T: MyTrait {} + | ^^^^^^^^^^^ required by this bound in `testing_mytrait` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/suggestions/multiple_tuples_implement_same_trait_continuous_arities.stderr b/tests/ui/suggestions/multiple_tuples_implement_same_trait_continuous_arities.stderr index fb9bb2642971a..3f30990827527 100644 --- a/tests/ui/suggestions/multiple_tuples_implement_same_trait_continuous_arities.stderr +++ b/tests/ui/suggestions/multiple_tuples_implement_same_trait_continuous_arities.stderr @@ -7,7 +7,7 @@ LL | testing_debug((1, Foo)); | required by a bound introduced by this call | = help: the following other types implement trait `Debug`: - (T₁, T₂, …, Tₙ) up to tuples of arity 12 + `(T₁, T₂, …, Tₙ)` up to tuples of arity 12 and 5 others = note: required for `({integer}, Foo)` to implement `Debug` note: required by a bound in `testing_debug` @@ -30,7 +30,7 @@ LL | testing_mytrait((1, Foo)); | required by a bound introduced by this call | = help: the following other types implement trait `MyTrait`: - (T₁, T₂, …, Tₙ) for tuples of arity 1 up to and including 5 + `(T₁, T₂, …, Tₙ)` for tuples of arity 1 up to and including 5 note: required by a bound in `testing_mytrait` --> $DIR/multiple_tuples_implement_same_trait_continuous_arities.rs:4:23 | From e8c680bdfda85386276b4608a505ad60d113da23 Mon Sep 17 00:00:00 2001 From: Gennaro Biondi Date: Sat, 14 Nov 2026 17:04:35 +0000 Subject: [PATCH 23/39] Document wide pointers in core::ptr module * Add "Thin and wide pointers" section to ptr module documentation this new section explains the difference between a thin pointer and a wide pointer * Make pointer methods documentation define thin and wide pointers this commit makes documentation for: - `std::ptr::addr_eq` - `std::ptr::from_raw_parts` - `<*const T>::is_null` link the definition of thin/wide pointers added to the module level docs * Document guarantee that all pointers to a sized type are thin * Simplify phrasing in addr_eq notably just adds an intralink to wide instead of linking separately --- library/core/src/ptr/docs/is_null.md | 6 ++++-- library/core/src/ptr/metadata.rs | 3 ++- library/core/src/ptr/mod.rs | 16 +++++++++++++++- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/library/core/src/ptr/docs/is_null.md b/library/core/src/ptr/docs/is_null.md index 7368ab9b57630..074ecde056221 100644 --- a/library/core/src/ptr/docs/is_null.md +++ b/library/core/src/ptr/docs/is_null.md @@ -1,10 +1,12 @@ Returns `true` if the pointer is null. -Note that unsized types have many possible null pointers, as only the -raw data pointer is considered, not their length, vtable, etc. +Note that, for [wide] pointers, only the address of the pointee is considered, +ignoring the metadata (such as a slice's length or a trait object's vtable). Therefore, two pointers that are null may still not compare equal to each other. +[wide]: core::ptr#thin-and-wide-pointers + # Panics during const evaluation If this method is used during const evaluation, and `self` is a pointer diff --git a/library/core/src/ptr/metadata.rs b/library/core/src/ptr/metadata.rs index 1eeadf1217b5f..1a0e71dc349ca 100644 --- a/library/core/src/ptr/metadata.rs +++ b/library/core/src/ptr/metadata.rs @@ -101,7 +101,7 @@ pub const fn metadata(ptr: *const T) -> ::Metadat ptr_metadata(ptr) } -/// Forms a (possibly-wide) raw pointer from a data pointer and metadata. +/// Forms a (possibly-[wide]) raw pointer from a data pointer and metadata. /// /// This function is safe but the returned pointer is not necessarily safe to dereference. /// For slices, see the documentation of [`slice::from_raw_parts`] for safety requirements. @@ -111,6 +111,7 @@ pub const fn metadata(ptr: *const T) -> ::Metadat /// a thin pointer can always be obtained by casting `*const T` to `*const ()`. /// /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts +/// [wide]: core::ptr#thin-and-wide-pointers #[unstable(feature = "ptr_metadata", issue = "81513")] #[inline] pub const fn from_raw_parts( diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 99aa9cf5ab741..443b518284e87 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -166,6 +166,20 @@ //! //! [`null()`]: null //! +//! # Thin and wide pointers +//! +//! Some pointers can also carry additional metadata alongside the address of the pointee. These are called +//! **wide pointers** (or **fat pointers**). +//! Pointers that only store the address of the pointee are instead called **thin pointers**, every +//! pointer to a sized type is guaranteed to be thin. +//! +//! Currently, wide pointers are twice as big as the size of a thin pointer, +//! however, this could be changed in the future. +//! +//! Wide pointers are commonly used when working with [`DSTs`]. +//! +//! [`DSTs`]: https://doc.rust-lang.org/reference/dynamically-sized-types.html +//! //! # Provenance //! //! Pointers are not *simply* an "integer" or "address". For instance, it's uncontroversial @@ -2503,7 +2517,7 @@ pub fn eq(a: *const T, b: *const T) -> bool { } /// Compares the *addresses* of the two pointers for equality, -/// ignoring any metadata in fat pointers. +/// ignoring any metadata in [wide](core::ptr#thin-and-wide-pointers) pointers. /// /// If the arguments are thin pointers of the same type, /// then this is the same as [`eq`]. From 5e71be357cfdca27fd280038ce11adbb89d6ea5e Mon Sep 17 00:00:00 2001 From: Gennaro Biondi Date: Sat, 14 Nov 2026 21:59:43 +0100 Subject: [PATCH 24/39] Mention `#![doc = include_str!(...)]` trick in intro page --- src/doc/rustdoc/src/what-is-rustdoc.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/doc/rustdoc/src/what-is-rustdoc.md b/src/doc/rustdoc/src/what-is-rustdoc.md index cb4ec51caf208..fd1cb53063dbb 100644 --- a/src/doc/rustdoc/src/what-is-rustdoc.md +++ b/src/doc/rustdoc/src/what-is-rustdoc.md @@ -158,7 +158,18 @@ $ rustdoc README.md You will find an HTML file in `docs/doc/README.html` generated from its Markdown contents. -Cargo currently does not understand standalone Markdown files, unfortunately. +Cargo currently does not understand standalone Markdown files, unfortunately, +but doc comments can copy the contents of external files by using the `include_str!` macro +and `#[doc]` attribute. + +for example: + +```rust +#![doc = include_str!("../README.md")] +``` + +This will copy the contents of `README.md` in the doc comment. +Check out the [`#[doc]` attribute chapter](write-documentation/the-doc-attribute.md) ## Summary From 20961e9a4e6311e1278ad13b3db49776a0da88c9 Mon Sep 17 00:00:00 2001 From: Folkert de Vries Date: Wed, 4 Nov 2026 21:45:02 +0100 Subject: [PATCH 25/39] add !type annotations for each (super)trait that is a prefix of a given vtable --- compiler/rustc_codegen_ssa/src/meth.rs | 13 ++- .../src/traits/vtable.rs | 35 +++++++ tests/codegen-llvm/vfe-annotate-supertrait.rs | 95 +++++++++++++++++++ tests/codegen-llvm/vfe-upcast.rs | 54 +++++++++++ .../virtual-function-elimination.rs | 8 +- .../drop-meta-sized.rs | 58 +++++++++++ 6 files changed, 259 insertions(+), 4 deletions(-) create mode 100644 tests/codegen-llvm/vfe-annotate-supertrait.rs create mode 100644 tests/codegen-llvm/vfe-upcast.rs create mode 100644 tests/ui/codegen/virtual-function-elimination/drop-meta-sized.rs diff --git a/compiler/rustc_codegen_ssa/src/meth.rs b/compiler/rustc_codegen_ssa/src/meth.rs index 3705a9f79bf56..ea1a7d9724d07 100644 --- a/compiler/rustc_codegen_ssa/src/meth.rs +++ b/compiler/rustc_codegen_ssa/src/meth.rs @@ -3,6 +3,7 @@ use rustc_session::config::Lto; use rustc_span::bug; use rustc_symbol_mangling::typeid_for_trait_ref; use rustc_target::callconv::FnAbi; +use rustc_trait_selection::traits::vtable; use tracing::{debug, instrument}; use crate::traits::*; @@ -157,8 +158,18 @@ pub(crate) fn get_vtable<'tcx, Cx: CodegenMethods<'tcx>>( let vtable_allocation = tcx.global_alloc(vtable_alloc_id).unwrap_memory(); let vtable = cx.static_addr_of(vtable_allocation, Some("vtable")); - cx.apply_vcall_visibility_metadata(trait_ref.as_slice(), vtable); + if let Some(trait_ref) = trait_ref + && cx.sess().opts.unstable_opts.virtual_function_elimination + && cx.sess().lto() == Lto::Fat + { + let key = trait_ref.with_self_ty(tcx, self_ty); + let trait_hierarchy = vtable::vtable_prefix_traits(tcx, key); + + cx.apply_vcall_visibility_metadata(&trait_hierarchy, vtable); + } + cx.create_vtable_debuginfo(self_ty, trait_ref, vtable); cx.vtables().borrow_mut().insert((self_ty, trait_ref), vtable); + vtable } diff --git a/compiler/rustc_trait_selection/src/traits/vtable.rs b/compiler/rustc_trait_selection/src/traits/vtable.rs index 6dd998791d2dd..05caf4aa1adf0 100644 --- a/compiler/rustc_trait_selection/src/traits/vtable.rs +++ b/compiler/rustc_trait_selection/src/traits/vtable.rs @@ -16,7 +16,9 @@ use crate::traits::is_vtable_safe_method; #[derive(Clone, Debug)] pub enum VtblSegment<'tcx> { + /// The segment containing Drop, Size and Align. MetadataDSA, + /// A segment with the methods of a particular trait. TraitOwnEntries { trait_ref: ty::TraitRef<'tcx>, emit_vptr: bool }, } @@ -453,6 +455,39 @@ pub(crate) fn supertrait_vtable_slot<'tcx>( }) } +/// Returns the traits that are prefixes of this vtable, such that upcasting to these traits +/// reuses the vtable pointer unchanged. +/// +/// For a `trait Foo: A + B`, the methods for A are stored as a prefix to the vtable for Foo. +/// If B has no methods, it is also part of this prefix (although it takes up no space). +/// +/// This function returns the full set of these traits (A might have its own supertrait, etc.). +/// The input trait is the last element of the output vector. +pub fn vtable_prefix_traits<'tcx>( + tcx: TyCtxt<'tcx>, + key: ty::TraitRef<'tcx>, +) -> Vec> { + debug_assert!(!key.has_non_region_infer() && !key.has_non_region_param()); + + let mut entries = vec![]; + + let vtable_segment_callback = |segment| -> ControlFlow<()> { + // When `emit_vptr: false`, this trait's vtable is a prefix of `key`'s vtable. + if let VtblSegment::TraitOwnEntries { trait_ref, emit_vptr: false } = segment { + entries.push(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)); + } + + ControlFlow::Continue(()) + }; + + let _ = prepare_vtable_segments(tcx, key, vtable_segment_callback); + + // The input trait is the last element in the output vector. + debug_assert_eq!(entries.last(), Some(&ty::ExistentialTraitRef::erase_self_ty(tcx, key))); + + entries +} + pub(super) fn provide(providers: &mut Providers) { *providers = Providers { own_existential_vtable_entries, diff --git a/tests/codegen-llvm/vfe-annotate-supertrait.rs b/tests/codegen-llvm/vfe-annotate-supertrait.rs new file mode 100644 index 0000000000000..a1777c19bc864 --- /dev/null +++ b/tests/codegen-llvm/vfe-annotate-supertrait.rs @@ -0,0 +1,95 @@ +//@ compile-flags: -Zvirtual-function-elimination -Clto=fat -Copt-level=3 -Zverify-llvm-ir +//@ no-prefer-dynamic +//@ min-llvm-version: 23 +#![crate_type = "staticlib"] + +// Check that vtables include a !type annotation for supertraits whose vtable are a prefix. +// +// What is still missing is that for any supertrait whose vtable is not a prefix, its vtable does +// not get any !type annotation. That means we provide incomplete information to VFE and it may +// incorrectly replace a virtual call with a direct call to the only callee VFE knows about. + +use std::hint::black_box; + +// FIXME: C_VTABLE should have a !type annotation for C, but it currently has none. +// CHECK: @vtable.{{[0-9]+}} = {{.*}}3Foo3foo{{.*}} !type ![[META_SIZED:[0-9]+]], !type ![[A:[0-9]+]], !type ![[B:[0-9]+]], !type ![[FOO:[0-9]+]], !guid +// CHECK: @[[C_VTABLE:alloc_[0-9a-f]+]] = {{.*}}1C1c }>, align {{[0-9]+}}, !guid +// CHECK: @vtable.{{[0-9]+}} = {{.*}}1C1c, ptr @[[C_VTABLE]], ptr {{.*}}3Bar3bar{{.*}} !type ![[META_SIZED]], !type ![[A]], !type ![[BAR:[0-9]+]], !guid + +// CHECK-DAG: ![[META_SIZED]] = !{i64 0, !"{{.*}}9MetaSized"} +// CHECK-DAG: ![[A]] = !{i64 0, !"{{.*}}1A"} +// CHECK-DAG: ![[B]] = !{i64 0, !"{{.*}}1B"} +// CHECK-DAG: ![[FOO]] = !{i64 0, !"{{.*}}3Foo"} +// CHECK-DAG: ![[BAR]] = !{i64 0, !"{{.*}}3Bar"} + +pub trait A { + fn a(&self) -> i32; +} + +pub trait B {} + +pub trait C { + fn c(&self) -> i32; +} + +/// A trait with two supertraits: +/// +/// - A is a prefix of Foo, because it is the first supertrait in the list +/// - B is a prefix of Foo, because it has no methods +pub trait Foo: A + B { + fn foo(&self) -> i32; +} + +/// A trait with two supertraits: +/// +/// - A is a prefix of Bar, because it is the first supertrait in the list +/// - C is a NOT a prefix of Bar, because it has methods +pub trait Bar: A + C { + fn bar(&self) -> i32; +} + +// The remainder is uninteresting, and only here so that the optimizer can't optimize out the +// interesting bits. + +pub struct S; + +impl A for S { + fn a(&self) -> i32 { + black_box(1) + } +} + +impl B for S {} + +impl C for S { + fn c(&self) -> i32 { + black_box(2) + } +} + +impl Foo for S { + fn foo(&self) -> i32 { + black_box(3) + } +} + +impl Bar for S { + fn bar(&self) -> i32 { + black_box(4) + } +} + +#[unsafe(no_mangle)] +pub fn use_foo(x: &dyn Foo) -> i32 { + x.foo() + x.a() +} + +#[unsafe(no_mangle)] +pub fn use_bar(x: &dyn Bar) -> i32 { + x.bar() + x.a() + x.c() +} + +#[unsafe(no_mangle)] +pub fn use_s() -> i32 { + use_foo(black_box(&S)) + use_bar(black_box(&S)) +} diff --git a/tests/codegen-llvm/vfe-upcast.rs b/tests/codegen-llvm/vfe-upcast.rs new file mode 100644 index 0000000000000..4216dae92b622 --- /dev/null +++ b/tests/codegen-llvm/vfe-upcast.rs @@ -0,0 +1,54 @@ +//@ compile-flags: -Zvirtual-function-elimination -Clto=fat -Copt-level=3 -Zverify-llvm-ir +//@ no-prefer-dynamic +#![crate_type = "staticlib"] + +// Check that a vtable also gets a !type annotation for any supertraits it has whose vtable is a +// prefix of the base trait's. For `trait Foo: A + B` this is true for A because it is the first, +// and also for B if it has no trait methods. +// +// Without this annotation, -Zvirtual-function-elimination may incorrectly remove a vtable if it +// only used by the supertrait. + +use std::hint::black_box; + +pub trait Super { + fn s(&self) -> i32; +} + +pub trait Sub: Super {} + +pub struct A; +pub struct B; + +impl Super for A { + fn s(&self) -> i32 { + black_box(1) + } +} + +impl Sub for A {} + +impl Super for B { + fn s(&self) -> i32 { + black_box(2) + } +} + +// CHECK-LABEL: @call_super +#[unsafe(no_mangle)] +pub fn call_super(x: &dyn Super) -> i32 { + // This call should not be devirtualized, x might be either A or B. + // CHECK: call noundef i32 %{{.*}}(ptr + x.s() +} + +#[unsafe(no_mangle)] +pub fn call_a() -> i32 { + let a: &dyn Sub = black_box(&A); + call_super(a) +} + +#[unsafe(no_mangle)] +pub fn call_b() -> i32 { + call_super(black_box(&B)) +} diff --git a/tests/codegen-llvm/virtual-function-elimination.rs b/tests/codegen-llvm/virtual-function-elimination.rs index 90331a4c59f3e..327b3226a77d8 100644 --- a/tests/codegen-llvm/virtual-function-elimination.rs +++ b/tests/codegen-llvm/virtual-function-elimination.rs @@ -2,7 +2,7 @@ // CHECK: @vtable.0 = {{.*}}, !type ![[TYPE0:[0-9]+]], !vcall_visibility ![[VCALL_VIS0:[0-9]+]] // CHECK: @vtable.1 = {{.*}}, !type ![[TYPE1:[0-9]+]], !vcall_visibility ![[VCALL_VIS0]] -// CHECK: @vtable.2 = {{.*}}, !type ![[TYPE2:[0-9]+]], !vcall_visibility ![[VCALL_VIS2:[0-9]+]] +// CHECK: @vtable.2 = {{.*}}, !type ![[TYPE2:[0-9]+]], !vcall_visibility ![[VCALL_VIS0]] #![crate_type = "lib"] @@ -98,8 +98,10 @@ pub fn main() { taking_v(&s); } +// MetaSized is an implicit supertrait of all dyn-compatible traits. +// CHECK: !0 = !{i64 0, !"[[MANGLED_CORE_MARKER:[0-9a-zA-Z_]+]]MetaSized"} +// // CHECK: ![[TYPE0]] = !{i64 0, !"[[MANGLED_TYPE0]]"} -// CHECK: ![[VCALL_VIS0]] = !{i64 2} +// CHECK: ![[VCALL_VIS0]] = !{i64 1} // CHECK: ![[TYPE1]] = !{i64 0, !"[[MANGLED_TYPE1]]"} // CHECK: ![[TYPE2]] = !{i64 0, !"NtC[[CRATE_IDENT]]_28virtual_function_elimination1V"} -// CHECK: ![[VCALL_VIS2]] = !{i64 1} diff --git a/tests/ui/codegen/virtual-function-elimination/drop-meta-sized.rs b/tests/ui/codegen/virtual-function-elimination/drop-meta-sized.rs new file mode 100644 index 0000000000000..540c41ae8b9cd --- /dev/null +++ b/tests/ui/codegen/virtual-function-elimination/drop-meta-sized.rs @@ -0,0 +1,58 @@ +//@ run-pass +//@ compile-flags: -Zvirtual-function-elimination -Clto=fat -Copt-level=3 -Zverify-llvm-ir +//@ no-prefer-dynamic +//@ ignore-backends: gcc +#![feature(sized_hierarchy)] +#![no_main] + +// Check that the Drop implementation actually runs. +// +// Before, vtables were not annotated with `!type` annotations for supertraits. Hence, when only +// methods from the supertrait were used, VFE considered the vtable unused and hence the drop +// implementation would be seen as dead and removed. +// +// Checking this on MetaSized is interesting because it is a supertrait to most dyn-compatible +// traits, and it has no methods itself so its vtable is always a prefix of the subtrait's vtable. +// +// This test uses #[no_main] because the standard library is compiled without +// -Zvirtual-function-elimination and therefore virtual calls can miscompile. +// +// Usually this shows up first in `lang_start`, because in `lang_start_internal` we coerce main +// to a `&dyn Fn() -> i32`. But the slot for the function in the vtable is considered dead +// and nulled. The call to the NULL function pointer traps. + +use std::hint::black_box; +use std::marker::MetaSized; +use std::sync::atomic::{AtomicBool, Ordering}; + +static DROPPED: AtomicBool = AtomicBool::new(false); + +#[allow(dead_code)] +trait T { + fn method(&self) -> i32; +} + +struct S; + +impl T for S { + fn method(&self) -> i32 { + 4 + } +} + +impl Drop for S { + fn drop(&mut self) { + DROPPED.store(true, Ordering::Relaxed); + } +} + +#[unsafe(no_mangle)] +extern "C" fn main() -> i32 { + let t: Box = Box::new(S); + let m: Box = black_box(t); + drop(m); + + assert!(DROPPED.load(Ordering::Relaxed)); + + 0 +} From 71e61037f810e74472b5a8c9fe07ee86818230f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kondzior?= Date: Sat, 14 Nov 2026 22:14:57 +0100 Subject: [PATCH 26/39] Improve index inference diagnostics --- compiler/rustc_hir_typeck/src/method/probe.rs | 34 +++++++++++---- .../index-closure-return-type-issue-105329.rs | 32 +++++++++++++++ ...ex-closure-return-type-issue-105329.stderr | 41 +++++++++++++++++++ 3 files changed, 100 insertions(+), 7 deletions(-) create mode 100644 tests/ui/type-inference/index-closure-return-type-issue-105329.rs create mode 100644 tests/ui/type-inference/index-closure-return-type-issue-105329.stderr diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index f86f34489e9d7..bdad342b52de5 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -529,32 +529,52 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let guar = match *ty.kind() { _ if let Some(guar) = self.tainted_by_errors() => guar, ty::Infer(ty::TyVar(_)) => { - // We want to get the variable name that the method - // is being called on. If it is a method call. - let err_span = match (mode, self.tcx.hir_node(scope_expr_id)) { + // Keep the method receiver so its span remains available when the + // index-specific diagnostic does not apply. + let receiver = match (mode, self.tcx.hir_node(scope_expr_id)) { ( Mode::MethodCall, Node::Expr(hir::Expr { kind: ExprKind::MethodCall(_, recv, ..), .. }), - ) => recv.span, - _ => span, + ) => Some(recv), + _ => None, + }; + + // A known index can still yield an unknown element type. Only redirect + // the diagnostic when both the indexing result and the index are unknown. + let (err_span, diagnostic_ty) = if let Some(recv) = receiver + && let ExprKind::Index(_, idx, _) = recv.kind + && self.shallow_resolve(self.node_ty(recv.hir_id)).is_ty_var() + && let index_ty = self.shallow_resolve(self.node_ty(idx.hir_id)) + && index_ty.is_ty_var() + { + (idx.span, index_ty) + } else { + (receiver.map_or(span, |recv| recv.span), ty) }; let raw_ptr_call = bad_ty.reached_raw_pointer && !self.tcx.features().arbitrary_self_types(); + // Suppress the generic secondary label when the pointer-specific label + // below will explain the failure. let mut err = self.err_ctxt().emit_inference_failure_err( self.body_def_id, err_span, - ty.into(), + diagnostic_ty.into(), TypeAnnotationNeeded::E0282, !raw_ptr_call, ); + if raw_ptr_call { - err.span_label(span, "cannot call a method on a raw pointer with an unknown pointee type"); + err.span_label( + span, + "cannot call a method on a raw pointer with an unknown pointee type", + ); } + err.emit_err() } ty::Error(guar) => guar, diff --git a/tests/ui/type-inference/index-closure-return-type-issue-105329.rs b/tests/ui/type-inference/index-closure-return-type-issue-105329.rs new file mode 100644 index 0000000000000..3692a99558e12 --- /dev/null +++ b/tests/ui/type-inference/index-closure-return-type-issue-105329.rs @@ -0,0 +1,32 @@ +//@ edition:2024 +// Regression test for https://github.com/rust-lang/rust/issues/105329 +// +// When the index type comes from an ambiguous parsing call in a closure, +// report the error at the parsing call and label the index expression. +// Previously, the error only highlighted the whole indexing expression. + +fn known_index_unknown_element() { + let rows = vec![Vec::new()]; + //~^ ERROR type annotations needed + rows[0usize].clone(); +} + +fn known_index_unknown_receiver() { + let values = Vec::new(); + //~^ ERROR type annotations needed + let _ = values[0usize].len(); +} + +fn explicit_index_type() { + let mut rows: Vec> = vec![vec![]; 10]; + let f = |text: &str| text.parse::().unwrap(); + rows[f("2")].push(10); +} + +fn main() { + let s = "2"; + let mut vec: Vec> = vec![vec![]; 10]; + let f = |x: &str| x.parse().unwrap(); + vec[f(s)].push(10); + //~^^ ERROR type annotations needed +} diff --git a/tests/ui/type-inference/index-closure-return-type-issue-105329.stderr b/tests/ui/type-inference/index-closure-return-type-issue-105329.stderr new file mode 100644 index 0000000000000..851e81391dca1 --- /dev/null +++ b/tests/ui/type-inference/index-closure-return-type-issue-105329.stderr @@ -0,0 +1,41 @@ +error[E0282]: type annotations needed + --> $DIR/index-closure-return-type-issue-105329.rs:9:21 + | +LL | let rows = vec![Vec::new()]; + | ^^^^^^^^ cannot infer type of the type parameter `T` declared on the struct `Vec` + | +help: consider specifying a concrete type for the type parameter `T` + | +LL | let rows = vec![Vec::::new()]; + | ++++++++++++++ + +error[E0282]: type annotations needed for `Vec<_>` + --> $DIR/index-closure-return-type-issue-105329.rs:15:9 + | +LL | let values = Vec::new(); + | ^^^^^^ +LL | +LL | let _ = values[0usize].len(); + | -------------- type must be known at this point + | +help: consider giving `values` an explicit type, where the type for type parameter `T` is specified + | +LL | let values: Vec = Vec::new(); + | ++++++++ + +error[E0282]: type annotations needed + --> $DIR/index-closure-return-type-issue-105329.rs:29:25 + | +LL | let f = |x: &str| x.parse().unwrap(); + | ^^^^^ cannot infer type of the type parameter `F` declared on the method `parse` +LL | vec[f(s)].push(10); + | ---- type must be known at this point + | +help: consider specifying a concrete type for the type parameter `F` + | +LL | let f = |x: &str| x.parse::().unwrap(); + | ++++++++++++++ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0282`. From b2d81b9fb25f60b36926463ad56907e519eb1c48 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 15 Nov 2026 00:18:50 +0100 Subject: [PATCH 27/39] Update `minifier-rs` dependency version to `0.5.0` --- Cargo.lock | 4 ++-- src/librustdoc/Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5a9da2a0c0bae..a1eb7b0164f9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2504,9 +2504,9 @@ dependencies = [ [[package]] name = "minifier" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245c950e30794ed20f72ff60c85ae1cddb0ba54fda4623017a678943f98f636c" +checksum = "56b6ef9682ae78237a99dde4f4060d556c2be0d50573361dd17b20d6f500b609" [[package]] name = "minimal-lexical" diff --git a/src/librustdoc/Cargo.toml b/src/librustdoc/Cargo.toml index 64fff96201939..4a22ecc60cb94 100644 --- a/src/librustdoc/Cargo.toml +++ b/src/librustdoc/Cargo.toml @@ -14,7 +14,7 @@ askama = { version = "0.16.1", default-features = false, features = ["alloc", "c indexmap = { version = "2", features = ["serde"] } itertools = "0.15" libc = "0.2" -minifier = { version = "0.4.0", default-features = false } +minifier = { version = "0.5.0", default-features = false } proc-macro2 = "1.0.103" pulldown-cmark-escape = { version = "0.11.0", features = ["simd"] } regex = "1" @@ -37,7 +37,7 @@ features = ["fmt", "env-filter", "smallvec", "parking_lot", "ansi"] [build-dependencies] sha2 = "0.10.8" -minifier = { version = "0.4.0", default-features = false } +minifier = { version = "0.5.0", default-features = false } [dev-dependencies] expect-test = "1.4.0" From 2c79d71c1f9fe17fc366b934edc7b8154b81b985 Mon Sep 17 00:00:00 2001 From: Takayuki Maeda Date: Sun, 15 Nov 2026 11:19:04 +0900 Subject: [PATCH 28/39] do not panic on non-UTF-8 arguments in `install_ice_hook` --- compiler/rustc_driver_impl/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index f1919cab3957e..c059b1d1ccaa3 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -1467,7 +1467,7 @@ pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(DiagCtxtHan // (e.g. `RUST_BACKTRACE=1`) if env::var_os("RUST_BACKTRACE").is_none() { // HACK: this check is extremely dumb, but we don't really need it to be smarter since this should only happen in the test suite anyway. - let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing"); + let ui_testing = env::args_os().any(|arg| arg == "-Zui-testing"); if env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing { panic::set_backtrace_style(panic::BacktraceStyle::Short); } else { From 84661ca8aba481d9705cbc7ac678689436603b71 Mon Sep 17 00:00:00 2001 From: Takayuki Maeda Date: Sun, 15 Nov 2026 11:19:08 +0900 Subject: [PATCH 29/39] add a regression test for non-UTF-8 command-line arguments --- tests/run-make/non-unicode-argument/rmake.rs | 25 ++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 tests/run-make/non-unicode-argument/rmake.rs diff --git a/tests/run-make/non-unicode-argument/rmake.rs b/tests/run-make/non-unicode-argument/rmake.rs new file mode 100644 index 0000000000000..43064daa79b43 --- /dev/null +++ b/tests/run-make/non-unicode-argument/rmake.rs @@ -0,0 +1,25 @@ +// Regression test for https://github.com/rust-lang/rust/issues/164585 + +use run_make_support::rustc; + +fn main() { + #[cfg(unix)] + let non_unicode: &std::ffi::OsStr = std::os::unix::ffi::OsStrExt::from_bytes(&[0xFF]); + #[cfg(windows)] + let non_unicode: std::ffi::OsString = std::os::windows::ffi::OsStringExt::from_wide(&[0xD800]); + + rustc() + .env_remove("RUST_BACKTRACE") + .arg(&non_unicode) + .run_fail() + .assert_exit_code(1) + .assert_stderr_contains("is not valid Unicode") + .assert_stderr_not_contains("panicked at"); + + rustc() + .env("RUST_BACKTRACE", "0") + .arg(&non_unicode) + .run_fail() + .assert_exit_code(1) + .assert_stderr_contains("is not valid Unicode"); +} From dcf41ce932c86dc9bddeeded3d65b256420b770b Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 15 Nov 2026 11:54:49 +0100 Subject: [PATCH 30/39] pipe_subprocess test: use libtest harness --- library/std/tests/pipe_subprocess.rs | 117 +++++++++++++++++---------- 1 file changed, 74 insertions(+), 43 deletions(-) diff --git a/library/std/tests/pipe_subprocess.rs b/library/std/tests/pipe_subprocess.rs index 35ad327ef4f48..5289c819835e3 100644 --- a/library/std/tests/pipe_subprocess.rs +++ b/library/std/tests/pipe_subprocess.rs @@ -1,49 +1,80 @@ -fn main() { +#![feature(test)] + +use std::io::{Read, pipe}; +use std::process::ExitCode; +use std::{env, process}; + +// We invoke the test harness manually so that the same binary can also serve as the child +// process that sits on the other end of the pipe. +extern crate test; + +static TESTS: &[&test::TestDescAndFn] = &[&test::TestDescAndFn { + testfn: test::TestFn::StaticTestFn(pipe_subprocess), + desc: test::TestDesc { + name: test::StaticTestName("pipe_subprocess"), + ignore: false, + ignore_message: None, + source_file: file!(), + start_line: 0, + start_col: 0, + end_line: 0, + end_col: 0, + compile_fail: false, + no_run: false, + should_panic: test::ShouldPanic::No, + test_type: test::TestType::IntegrationTest, + }, +}]; + +fn parent() { + let me = env::current_exe().unwrap(); + // If a custom `runner` is set up for the current target, we'll be + // executing `./runner ./test`, not just `./test`. For such a case, + // use the same arguments for child to avoid executing `runner` + // without an actual executable. + let args = env::args(); + + let (rx, tx) = pipe().unwrap(); + assert!( + process::Command::new(me) + .args(args) + .env("I_AM_THE_CHILD", "1") + .stdout(tx) + .status() + .unwrap() + .success() + ); + + let mut s = String::new(); + (&rx).read_to_string(&mut s).unwrap(); + drop(rx); + assert_eq!(s, "Heloo,\n"); + + println!("Test pipe_subprocess.rs success"); +} + +fn child() { + println!("Heloo,"); +} + +fn pipe_subprocess() -> Result<(), String> { // No `Command` on Miri, emscripten or L4Re - #[cfg(all( + if cfg!(all( not(skip_unsupported_miri_tests), any(unix, windows), not(any(target_os = "emscripten", target_os = "l4re")) - ))] - { - use std::io::{Read, pipe}; - use std::{env, process}; - - if env::var("I_AM_THE_CHILD").is_ok() { - child(); - } else { - parent(); - } - - fn parent() { - let me = env::current_exe().unwrap(); - // If a custom `runner` is set up for the current target, we'll be - // executing `./runner ./test`, not just `./test`. For such a case, - // use the same arguments for child to avoid executing `runner` - // without an actual executable. - let args = env::args(); - - let (rx, tx) = pipe().unwrap(); - assert!( - process::Command::new(me) - .args(args) - .env("I_AM_THE_CHILD", "1") - .stdout(tx) - .status() - .unwrap() - .success() - ); - - let mut s = String::new(); - (&rx).read_to_string(&mut s).unwrap(); - drop(rx); - assert_eq!(s, "Heloo,\n"); - - println!("Test pipe_subprocess.rs success"); - } - - fn child() { - println!("Heloo,"); - } + )) { + parent(); + } + Ok(()) +} + +fn main() -> ExitCode { + if env::var("I_AM_THE_CHILD").is_ok() { + child(); + ExitCode::SUCCESS + } else { + // Go via libtest runner so test filtering and nextest work properly. + test::test_main_env_args(TESTS) } } From f4e35f8f2378313547c504d1925a6946b8ae77ce Mon Sep 17 00:00:00 2001 From: suryansh-dey Date: Sun, 15 Nov 2026 17:13:39 +0530 Subject: [PATCH 31/39] Fix(docs): Correct discard behavior in datagram peek docs --- library/std/src/net/udp.rs | 18 ++++++++++++++++-- library/std/src/os/unix/net/datagram.rs | 5 ++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/library/std/src/net/udp.rs b/library/std/src/net/udp.rs index 914c400fb05f1..1cbc07f4183de 100644 --- a/library/std/src/net/udp.rs +++ b/library/std/src/net/udp.rs @@ -155,7 +155,14 @@ impl UdpSocket { /// /// The function must be called with valid byte array `buf` of sufficient size to /// hold the message bytes. If a message is too long to fit in the supplied buffer, - /// excess bytes may be discarded. + /// only the bytes that fit are copied into `buf`; the excess bytes are not returned + /// by this call. The datagram itself is left in the queue in full, so a later call + /// to [`UdpSocket::recv_from`] with a large enough buffer still receives the whole + /// message. + /// + /// Whether peeking with a too-small buffer succeeds with a truncated length or + /// fails is platform-specific. For example, Windows returns an error + /// (`WSAEMSGSIZE`) in this case. /// /// Successive calls return the same data. This is accomplished by passing /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call. @@ -823,7 +830,14 @@ impl UdpSocket { /// /// The function must be called with valid byte array `buf` of sufficient size to /// hold the message bytes. If a message is too long to fit in the supplied buffer, - /// excess bytes may be discarded. + /// only the bytes that fit are copied into `buf`; the excess bytes are not returned + /// by this call. The datagram itself is left in the queue in full, so a later call + /// to [`UdpSocket::recv`] with a large enough buffer still receives the whole + /// message. + /// + /// Whether peeking with a too-small buffer succeeds with a truncated length or + /// fails is platform-specific. For example, Windows returns an error + /// (`WSAEMSGSIZE`) in this case. /// /// Successive calls return the same data. This is accomplished by passing /// `MSG_PEEK` as a flag to the underlying `recv` system call. diff --git a/library/std/src/os/unix/net/datagram.rs b/library/std/src/os/unix/net/datagram.rs index 901263a7aa123..ce5654b5576c7 100644 --- a/library/std/src/os/unix/net/datagram.rs +++ b/library/std/src/os/unix/net/datagram.rs @@ -965,7 +965,10 @@ impl UnixDatagram { /// /// The function must be called with valid byte array `buf` of sufficient size to /// hold the message bytes. If a message is too long to fit in the supplied buffer, - /// excess bytes may be discarded. + /// only the bytes that fit are copied into `buf`; the excess bytes are not returned + /// by this call. The datagram itself is left in the queue in full, so a later call + /// to [`UnixDatagram::recv_from`] with a large enough buffer still receives the + /// whole message. /// /// Successive calls return the same data. This is accomplished by passing /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call. From 2d99d576cc58438c6a64cee4b848ae7829ab2b41 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 15 Nov 2026 17:29:19 +0100 Subject: [PATCH 32/39] attribute #[optimize]: keep low opt levels unoptimized --- .../rustc_mir_transform/src/pass_manager.rs | 18 ++++++++++-------- tests/mir-opt/optimize_attr.rs | 6 ++++-- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_mir_transform/src/pass_manager.rs b/compiler/rustc_mir_transform/src/pass_manager.rs index b5fbe5facc481..593124d9c696b 100644 --- a/compiler/rustc_mir_transform/src/pass_manager.rs +++ b/compiler/rustc_mir_transform/src/pass_manager.rs @@ -141,16 +141,18 @@ impl<'sess> PassCtx<'sess> { let body_mir_opt_level = if !tcx.def_kind(def_id).has_codegen_attrs() { tcx.sess.mir_opt_level() } else { - match tcx.codegen_fn_attrs(def_id).optimize { + let attr_opt_level = match tcx.codegen_fn_attrs(def_id).optimize { OptimizeAttr::Default => tcx.sess.mir_opt_level(), OptimizeAttr::Speed => OptLevel::Aggressive.mir_opt_level(), - // `optimize(none)`/`optimize(size)` should not increase the MIR opt level. - // (This can be relevant when `-Zmir-opt-level=0` was manually set.) - OptimizeAttr::DoNotOptimize => { - OptLevel::No.mir_opt_level().min(tcx.sess.mir_opt_level()) - } - OptimizeAttr::Size => OptLevel::Size.mir_opt_level().min(tcx.sess.mir_opt_level()), - } + OptimizeAttr::Size => OptLevel::SizeMin.mir_opt_level(), + OptimizeAttr::DoNotOptimize => OptLevel::No.mir_opt_level(), + }; + // The LLVM backend only makes the `optimize` attribute really do anything in optimized + // builds: at opt-level 2 or 3, we can choose some functions to optimize for size + // instead; at opt-level s or z, we can choose some functions to optimize for speed. For + // consistency, we do something similar for MIR-opts, by letting the attribute only + // decrease the opt-level, not increase it. + attr_opt_level.min(tcx.sess.mir_opt_level()) }; Self { session: tcx.sess, body_mir_opt_level } } diff --git a/tests/mir-opt/optimize_attr.rs b/tests/mir-opt/optimize_attr.rs index 2f748a3e8cda7..1372101972cf2 100644 --- a/tests/mir-opt/optimize_attr.rs +++ b/tests/mir-opt/optimize_attr.rs @@ -43,13 +43,15 @@ pub fn align_of_val_noopt() -> usize { } } -// With optimize(speed), we optimize this all the way to a constant +// Even with optimize(speed), a mir-opt-level of 0 suppresses MIR opts. #[optimize(speed)] pub fn align_of_val_opt() -> usize { // CHECK-LABEL: fn align_of_val_opt( unsafe { let ptr: *const [u8] = std::mem::transmute((42usize, usize::MAX)); - // CHECK: _0 = const 1_usize; + // ABSOLUTELY-NO-OPT: align_of_val + // NO-OPT: _0 = const 1_usize; + // SPEED-OPT: _0 = const 1_usize; std::intrinsics::align_of_val(ptr) } } From 8958ef8bf1659e27ce39ee960f1ad37634571717 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 15 Nov 2026 19:42:22 +0100 Subject: [PATCH 33/39] expose f16b via std::num, not just core::num --- library/std/src/num/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/library/std/src/num/mod.rs b/library/std/src/num/mod.rs index 9d713ab812829..2feaae34135fe 100644 --- a/library/std/src/num/mod.rs +++ b/library/std/src/num/mod.rs @@ -24,6 +24,8 @@ pub use core::num::Wrapping; issue = "none" )] pub use core::num::ZeroablePrimitive; +#[unstable(feature = "f16b", issue = "160630")] +pub use core::num::f16b; #[stable(feature = "rust1", since = "1.0.0")] pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError}; #[stable(feature = "signed_nonzero", since = "1.34.0")] From a6844d5d43d7dbb5d5a906be9834ff13d9b07d36 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 15 Nov 2026 19:42:35 +0100 Subject: [PATCH 34/39] add ABI compat checks for new float types --- .../tests/pass/function_calls/abi_compat.rs | 41 ++++++++++++------- tests/ui/abi/compatibility.rs | 25 +++++++++-- 2 files changed, 48 insertions(+), 18 deletions(-) diff --git a/src/tools/miri/tests/pass/function_calls/abi_compat.rs b/src/tools/miri/tests/pass/function_calls/abi_compat.rs index a763c300cc1a6..197839688b36f 100644 --- a/src/tools/miri/tests/pass/function_calls/abi_compat.rs +++ b/src/tools/miri/tests/pass/function_calls/abi_compat.rs @@ -1,8 +1,16 @@ #![feature(cfi_encoding)] +#![feature(f16, complex_numbers, f16b)] +#![cfg_attr(any(target_arch = "x86", target_arch = "x86_64"), feature(x87_f80))] use std::rc::Rc; use std::{mem, num, ptr}; +#[rustfmt::skip] +#[cfg(target_arch = "x86")] +use std::arch::x86::*; +#[cfg(target_arch = "x86_64")] +use std::arch::x86_64::*; + #[derive(Copy, Clone, Default)] struct Zst; @@ -61,7 +69,7 @@ fn test_abi_compat(t: T, u: U) { } /// Ensure that `T` is compatible with various repr(transparent) wrappers around `T`. -fn test_abi_newtype() { +fn test_abi_newtype(t: T) { #[repr(transparent)] #[derive(Copy, Clone)] struct Wrapper2(T, ()); @@ -77,7 +85,6 @@ fn test_abi_newtype() { V(Zst, T, [(); 10]), } - let t = T::default(); test_abi_compat(t, Wrapper(t)); test_abi_compat(t, Wrapper2(t, ())); test_abi_compat(t, Wrapper2a((), t)); @@ -165,19 +172,23 @@ fn main() { // These must work for *any* type, since we guarantee that `repr(transparent)` is ABI-compatible // with the wrapped field. - test_abi_newtype::<()>(); - test_abi_newtype::(); - test_abi_newtype::(); - test_abi_newtype::(); - test_abi_newtype::(); - test_abi_newtype::(); - test_abi_newtype::<(u8, u16, f32)>(); - test_abi_newtype::<[u8; 0]>(); - test_abi_newtype::<[u32; 0]>(); - test_abi_newtype::<[u32; 2]>(); - test_abi_newtype::<[u32; 32]>(); - test_abi_newtype::>(); - test_abi_newtype::>>(); + test_abi_newtype::<()>(Default::default()); + test_abi_newtype::(Default::default()); + test_abi_newtype::(Default::default()); + test_abi_newtype::(Default::default()); + test_abi_newtype::(Default::default()); + test_abi_newtype::(Default::default()); + test_abi_newtype::>(Default::default()); + test_abi_newtype::(Default::default()); + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + test_abi_newtype::(x87_f80::from_ne_bytes([0u8; 10])); + test_abi_newtype::<(u8, u16, f32)>(Default::default()); + test_abi_newtype::<[u8; 0]>(Default::default()); + test_abi_newtype::<[u32; 0]>(Default::default()); + test_abi_newtype::<[u32; 2]>(Default::default()); + test_abi_newtype::<[u32; 32]>(Default::default()); + test_abi_newtype::>(Default::default()); + test_abi_newtype::>>(Default::default()); // Extra test for assumptions made by arbitrary-self-dyn-receivers. // This is interesting since these types are not `repr(transparent)`. So this is not part of our diff --git a/tests/ui/abi/compatibility.rs b/tests/ui/abi/compatibility.rs index 1116cb1a7e0fb..37139f0e633cf 100644 --- a/tests/ui/abi/compatibility.rs +++ b/tests/ui/abi/compatibility.rs @@ -85,10 +85,10 @@ //@ revisions: nvptx64 //@[nvptx64] compile-flags: --target nvptx64-nvidia-cuda //@[nvptx64] needs-llvm-components: nvptx -#![feature(no_core, rustc_attrs, lang_items)] -#![feature(unsized_fn_params, transparent_unions)] +#![feature(no_core, rustc_attrs, lang_items, f16, f128)] +#![feature(unsized_fn_params, transparent_unions, cfg_target_has_reliable_f16b)] #![no_core] -#![expect(unused, improper_ctypes_definitions, internal_features)] +#![expect(unused, improper_ctypes_definitions, internal_features, unexpected_cfgs)] // FIXME: some targets are broken in various ways. // Hence there are `cfg` throughout this test to disable parts of it on those targets. @@ -97,6 +97,15 @@ extern crate minicore; use minicore::*; +#[cfg(target_arch = "x86")] +use arch::x86::*; +#[cfg(target_arch = "x86_64")] +use arch::x86_64::*; +#[cfg(target_arch = "powerpc")] +use arch::powerpc::*; +#[cfg(target_arch = "powerpc64")] +use arch::powerpc64::*; + /// To work cross-target this test must be no_core. This little prelude supplies what we need. /// /// Note that `minicore` provides a very minimal subset of `core` items (not yet complete). This @@ -272,6 +281,16 @@ macro_rules! test_transparent { test_transparent!(simple, i32); test_transparent!(float, f32); +test_transparent!(complex, num::Complex); +test_transparent!(f16, f16); +test_transparent!(f128, f128); +#[cfg(target_has_reliable_f16b)] +test_transparent!(f16b, num::f16b); +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +test_transparent!(float_x87, x87_f80); +#[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))] +test_transparent!(float_ppc, ppcf128); + test_transparent!(reference, &'static i32); test_transparent!(zst, Zst); test_transparent!(unit, ()); From 8cdd0bfd5a20ffeed8a057882df1f128ad63c191 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 6 Oct 2026 17:19:45 +0000 Subject: [PATCH 35/39] Do not include context span when source is unavailable to render ``` error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of ` as std::mem::SizedTypeProperties>::SIZE` failed here ``` --- .../rustc_errors/src/annotate_snippet_emitter_writer.rs | 6 +++++- tests/ui/coroutine/resume-arg-outlives-2.stderr | 1 - .../debuginfo/debuginfo-type-name-layout-ice-94961-1.stderr | 1 - .../debuginfo/debuginfo-type-name-layout-ice-94961-2.stderr | 1 - tests/ui/layout/invalid-unsized-in-always-sized-tail.stderr | 1 - tests/ui/layout/too-big-no-dce.stderr | 1 - tests/ui/limits/issue-17913.32bit.stderr | 1 - tests/ui/limits/issue-17913.64bit.stderr | 1 - tests/ui/limits/issue-55878.stderr | 1 - tests/ui/limits/issue-75158-64.stderr | 1 - tests/ui/limits/vtable-try-as-dyn.full-debuginfo.stderr | 1 - tests/ui/limits/vtable-try-as-dyn.no-debuginfo.stderr | 1 - tests/ui/nll/ice-106874.stderr | 2 -- tests/ui/pin-ergonomics/pinned-drop-check.stderr | 2 -- 14 files changed, 5 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs index bc1f2389cf55e..79c6336978d57 100644 --- a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs +++ b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs @@ -595,7 +595,11 @@ impl AnnotateSnippetEmitter { ) -> Group<'a> { let filename = sm.filename_for_diagnostics(file_name).to_string_lossy().to_string(); let mut line_tracker = vec![]; - for (i, a) in annotations.into_iter().enumerate() { + for (i, a) in annotations + .into_iter() + .filter(|a| !matches!(a.kind, AnnotationKind::Visible)) + .enumerate() + { let lo = sm.lookup_char_pos(a.span.lo()); let hi = sm.lookup_char_pos(a.span.hi()); if i == 0 || (a.label.is_some()) { diff --git a/tests/ui/coroutine/resume-arg-outlives-2.stderr b/tests/ui/coroutine/resume-arg-outlives-2.stderr index 49d3fee47fa9d..52a071821b638 100644 --- a/tests/ui/coroutine/resume-arg-outlives-2.stderr +++ b/tests/ui/coroutine/resume-arg-outlives-2.stderr @@ -18,7 +18,6 @@ LL | | }) | note: `'static` lifetime requirement from `spawn` introduced here --> $SRC_DIR/std/src/thread/functions.rs:LL:COL - ::: $SRC_DIR/std/src/thread/functions.rs:LL:COL | = note: lifetime requirement introduced here ::: $SRC_DIR/std/src/thread/functions.rs:LL:COL diff --git a/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-1.stderr b/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-1.stderr index 6e0de1071e721..73e1578242675 100644 --- a/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-1.stderr +++ b/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-1.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of ` as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-2.stderr b/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-2.stderr index 212320a60a1db..4ce1e2e407e9d 100644 --- a/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-2.stderr +++ b/tests/ui/debuginfo/debuginfo-type-name-layout-ice-94961-2.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of ` as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/layout/invalid-unsized-in-always-sized-tail.stderr b/tests/ui/layout/invalid-unsized-in-always-sized-tail.stderr index dbb861d4a3bed..b08e37dbd7472 100644 --- a/tests/ui/layout/invalid-unsized-in-always-sized-tail.stderr +++ b/tests/ui/layout/invalid-unsized-in-always-sized-tail.stderr @@ -20,7 +20,6 @@ LL | struct MySlice(T); error[E0080]: the type `MySlice<[bool]>` has an unknown layout --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `::ALIGN` failed here diff --git a/tests/ui/layout/too-big-no-dce.stderr b/tests/ui/layout/too-big-no-dce.stderr index 5533602d3f393..a4b01dda0a444 100644 --- a/tests/ui/layout/too-big-no-dce.stderr +++ b/tests/ui/layout/too-big-no-dce.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u32; NUMBER]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `<[u32; NUMBER] as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/issue-17913.32bit.stderr b/tests/ui/limits/issue-17913.32bit.stderr index 8b109ad703c75..6ddde4b891836 100644 --- a/tests/ui/limits/issue-17913.32bit.stderr +++ b/tests/ui/limits/issue-17913.32bit.stderr @@ -3,7 +3,6 @@ error: values of the type `[&usize; usize::MAX]` are too big for the target arch error[E0080]: values of the type `[&usize; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `<[&usize; usize::MAX] as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/issue-17913.64bit.stderr b/tests/ui/limits/issue-17913.64bit.stderr index 8ffa2c1966966..d35d697d5f3f3 100644 --- a/tests/ui/limits/issue-17913.64bit.stderr +++ b/tests/ui/limits/issue-17913.64bit.stderr @@ -3,7 +3,6 @@ error: values of the type `[&usize; usize::MAX]` are too big for the target arch error[E0080]: values of the type `[&usize; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `<[&usize; usize::MAX] as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/issue-55878.stderr b/tests/ui/limits/issue-55878.stderr index acae67709e6b1..994e43854f825 100644 --- a/tests/ui/limits/issue-55878.stderr +++ b/tests/ui/limits/issue-55878.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of `<[u8; usize::MAX] as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/issue-75158-64.stderr b/tests/ui/limits/issue-75158-64.stderr index 6832f04caaac4..bab0e1b777c28 100644 --- a/tests/ui/limits/issue-75158-64.stderr +++ b/tests/ui/limits/issue-75158-64.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/mem/mod.rs:LL:COL - ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | = note: evaluation of ` as std::mem::SizedTypeProperties>::SIZE` failed here diff --git a/tests/ui/limits/vtable-try-as-dyn.full-debuginfo.stderr b/tests/ui/limits/vtable-try-as-dyn.full-debuginfo.stderr index 16e4572c83e5b..c6a53d4face4f 100644 --- a/tests/ui/limits/vtable-try-as-dyn.full-debuginfo.stderr +++ b/tests/ui/limits/vtable-try-as-dyn.full-debuginfo.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/any.rs:LL:COL - ::: $SRC_DIR/core/src/any.rs:LL:COL | = note: evaluation of `std::any::try_as_dyn::<'_, [u8; usize::MAX], dyn Trait>::{constant#0}` failed inside this call note: inside `TypeId::trait_info_of::<'_, dyn Trait>` diff --git a/tests/ui/limits/vtable-try-as-dyn.no-debuginfo.stderr b/tests/ui/limits/vtable-try-as-dyn.no-debuginfo.stderr index 16e4572c83e5b..c6a53d4face4f 100644 --- a/tests/ui/limits/vtable-try-as-dyn.no-debuginfo.stderr +++ b/tests/ui/limits/vtable-try-as-dyn.no-debuginfo.stderr @@ -1,6 +1,5 @@ error[E0080]: values of the type `[u8; usize::MAX]` are too big for the target architecture --> $SRC_DIR/core/src/any.rs:LL:COL - ::: $SRC_DIR/core/src/any.rs:LL:COL | = note: evaluation of `std::any::try_as_dyn::<'_, [u8; usize::MAX], dyn Trait>::{constant#0}` failed inside this call note: inside `TypeId::trait_info_of::<'_, dyn Trait>` diff --git a/tests/ui/nll/ice-106874.stderr b/tests/ui/nll/ice-106874.stderr index 0b756a1795f8a..80381324b95bb 100644 --- a/tests/ui/nll/ice-106874.stderr +++ b/tests/ui/nll/ice-106874.stderr @@ -81,7 +81,6 @@ LL | A(B(C::new(D::new(move |st| f(st))))) | note: closure with signature `fn(&'2 mut V)` must implement `FnOnce<(&'1 mut V,)>`, for any lifetime `'1`... --> $SRC_DIR/alloc/src/rcs/rc.rs:LL:COL - ::: $SRC_DIR/alloc/src/rcs/rc.rs:LL:COL | = note: required by this bound in `Rc` = note: ...but it actually implements `FnOnce<(&'2 mut V,)>`, for some specific lifetime `'2` @@ -98,7 +97,6 @@ LL | A(B(C::new(D::new(move |st| f(st))))) | note: closure with signature `fn(&'2 mut V)` must implement `Fn<(&'1 mut V,)>`, for any lifetime `'1`... --> $SRC_DIR/alloc/src/rcs/rc.rs:LL:COL - ::: $SRC_DIR/alloc/src/rcs/rc.rs:LL:COL | = note: required by this bound in `Rc` = note: ...but it actually implements `Fn<(&'2 mut V,)>`, for some specific lifetime `'2` diff --git a/tests/ui/pin-ergonomics/pinned-drop-check.stderr b/tests/ui/pin-ergonomics/pinned-drop-check.stderr index 2a10ef06dcdbf..9fa39382abeca 100644 --- a/tests/ui/pin-ergonomics/pinned-drop-check.stderr +++ b/tests/ui/pin-ergonomics/pinned-drop-check.stderr @@ -8,7 +8,6 @@ LL | fn pin_drop(&pin mut self) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ duplicate definition | --> $SRC_DIR/core/src/ops/drop.rs:LL:COL - ::: $SRC_DIR/core/src/ops/drop.rs:LL:COL | = note: item in trait @@ -22,7 +21,6 @@ LL | fn pin_drop(&pin mut self) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ duplicate definition | --> $SRC_DIR/core/src/ops/drop.rs:LL:COL - ::: $SRC_DIR/core/src/ops/drop.rs:LL:COL | = note: item in trait From 053b6d4fca1cd02f51455856a0d1ab1f4517000b Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sun, 15 Nov 2026 13:27:26 -0800 Subject: [PATCH 36/39] Revert safety hygiene changes to `String::retain` This reverts commit 36860469bd38adc65e328b37d01b346d2342214e, reversing changes made to b222250994e8635a827e1a3338d4f976f5c06505. --- library/alloc/src/string.rs | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index c8336c4f43823..3f7cc3d64ec33 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -1730,18 +1730,9 @@ impl String { // Slow path: at least one character is going to be removed. let mut g = PanicGuard { s: self, write }; while read < len { - // SAFETY: Use `vec`: `String`'s deref includes `write..read`, - // which may be invalid UTF-8. The vector's length is still `len`; - // `read < len`, so `read..len` is in bounds and non-empty. - // At least one character was removed, so `write < read`. - // Copies end before the next `read`, preserving unread bytes. - // `read` starts after a `char_indices` character and advances by whole - // characters, so it stays on a char boundary. The original string was valid UTF-8, - // so the unchanged, non-empty tail is valid UTF-8 and `chars().next()` returns `Some`. - let ch = unsafe { - let tail = str::from_utf8_unchecked(g.s.vec.get_unchecked(read..len)); - tail.chars().next().unwrap_unchecked() - }; + // SAFETY: `read` is within bound because `read` < `len`, so taking + // a slice with `len` is safe. + let ch = unsafe { g.s.get_unchecked(read..len).chars().next().unwrap_unchecked() }; let ch_len = ch.len_utf8(); if f(ch) { // SAFETY: `read` is on a char boundary, as guaranteed above; `g.write` is From 3ff409501baefc883c16fb185bffadb2e01b2fd0 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Sun, 15 Nov 2026 13:28:57 -0800 Subject: [PATCH 37/39] Revert optimized implementation of `String::retain` This reverts commit 35df304c76838c5281ff911888aa0d9105aa113d, reversing changes made to e081d6616f3be5a96c6b42eecc6410f1a5378b7e. --- library/alloc/src/string.rs | 78 ++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 41 deletions(-) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 3f7cc3d64ec33..5015b4934c2ea 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -58,7 +58,7 @@ use core::ops::Add; use core::ops::AddAssign; use core::ops::{self, Range, RangeBounds}; use core::str::pattern::{Pattern, Utf8Pattern}; -use core::{fmt, hash, hint, ptr, slice}; +use core::{fmt, hash, ptr, slice}; #[cfg(not(no_global_oom_handling))] use crate::alloc::Allocator; @@ -1697,57 +1697,53 @@ impl String { where F: FnMut(char) -> bool, { - let len = self.len(); - if len == 0 { - // Explicit check results in better optimization - return; - } - - struct PanicGuard<'a> { + struct SetLenOnDrop<'a> { s: &'a mut String, - write: usize, + idx: usize, + del_bytes: usize, } - impl Drop for PanicGuard<'_> { + impl<'a> Drop for SetLenOnDrop<'a> { fn drop(&mut self) { - debug_assert!(self.write <= self.s.len()); - debug_assert!(str::from_utf8(&self.s.vec[..self.write]).is_ok()); - // SAFETY: Restore the string length to the number of bytes written so far. - unsafe { self.s.vec.set_len(self.write) } + let new_len = self.idx - self.del_bytes; + debug_assert!(new_len <= self.s.len()); + unsafe { self.s.vec.set_len(new_len) }; } } - // Fast path: find the first character that should be removed or return early. - let mut chars = self.char_indices(); - let (mut read, write) = loop { - let Some((idx, ch)) = chars.next() else { return }; - if hint::unlikely(!f(ch)) { - break (idx + ch.len_utf8(), idx); - } - }; - drop(chars); - - // Slow path: at least one character is going to be removed. - let mut g = PanicGuard { s: self, write }; - while read < len { - // SAFETY: `read` is within bound because `read` < `len`, so taking - // a slice with `len` is safe. - let ch = unsafe { g.s.get_unchecked(read..len).chars().next().unwrap_unchecked() }; + let len = self.len(); + let mut guard = SetLenOnDrop { s: self, idx: 0, del_bytes: 0 }; + + while guard.idx < len { + let ch = + // SAFETY: `guard.idx` is positive-or-zero and less that len so the `get_unchecked` + // is in bound. `self` is valid UTF-8 like string and the returned slice starts at + // a unicode code point so the `Chars` always return one character. + unsafe { guard.s.get_unchecked(guard.idx..len).chars().next().unwrap_unchecked() }; let ch_len = ch.len_utf8(); - if f(ch) { - // SAFETY: `read` is on a char boundary, as guaranteed above; `g.write` is - // within bounds because it is always behind `read`. - unsafe { - let ptr = g.s.vec.as_mut_ptr(); - ptr::copy(ptr.add(read), ptr.add(g.write), ch_len); - } - g.write += ch_len; + + if !f(ch) { + guard.del_bytes += ch_len; + } else if guard.del_bytes > 0 { + // SAFETY: `guard.idx` is in bound and `guard.del_bytes` represent the number of + // bytes that are erased from the string so the resulting `guard.idx - + // guard.del_bytes` always represent a valid unicode code point. + // + // `guard.del_bytes` >= `ch.len_utf8()`, so taking a slice with `ch.len_utf8()` len + // is safe. + ch.encode_utf8(unsafe { + crate::slice::from_raw_parts_mut( + guard.s.as_mut_ptr().add(guard.idx - guard.del_bytes), + ch.len_utf8(), + ) + }); } - read += ch_len; + + // Point idx to the next char + guard.idx += ch_len; } - // All bytes processed; commit the final length by dropping the guard. - drop(g); + drop(guard); } /// Inserts a character into this `String` at byte position `idx`. From 08e44b178063028f6561cc57aff8d338a070e908 Mon Sep 17 00:00:00 2001 From: Khashayar Fereidani Date: Sun, 15 Nov 2026 14:08:25 -0800 Subject: [PATCH 38/39] library: Reapply String::retain safety doc for tidy Co-authored-by: Jubilee Young --- library/alloc/src/string.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 5015b4934c2ea..4f59e88657b3f 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -1707,6 +1707,7 @@ impl String { fn drop(&mut self) { let new_len = self.idx - self.del_bytes; debug_assert!(new_len <= self.s.len()); + // SAFETY: Restore the string length to the number of bytes written so far. unsafe { self.s.vec.set_len(new_len) }; } } From 6a8e5c1fb4b173b73e6cfe5f5a3a422c057d7c72 Mon Sep 17 00:00:00 2001 From: TechnoPorg Date: Sun, 15 Nov 2026 09:26:50 -0500 Subject: [PATCH 39/39] Update TPDE submodule --- src/tpde | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tpde b/src/tpde index 9779acf4ada37..cce0616b638ac 160000 --- a/src/tpde +++ b/src/tpde @@ -1 +1 @@ -Subproject commit 9779acf4ada3736e779391da1e4b3369dba08024 +Subproject commit cce0616b638acee040e5d3c247c7c35c742f7169