Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4905,6 +4905,7 @@ dependencies = [
"rustc_data_structures",
"rustc_hashes",
"rustc_hir",
"rustc_macros",
"rustc_middle",
"rustc_session",
"rustc_span",
Expand Down
36 changes: 26 additions & 10 deletions compiler/rustc_data_structures/src/stable_hash.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::hash::{BuildHasher, Hash, Hasher};
use std::marker::PhantomData;
use std::mem;
use std::num::NonZero;

use rustc_index::bit_set::{self, DenseBitSet};
Expand Down Expand Up @@ -533,10 +532,20 @@ where
{
#[inline]
fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
mem::discriminant(self).stable_hash(hcx, hasher);
#[derive(StableHash)]
enum Tag {
Ok,
Err,
}
match *self {
Ok(ref x) => x.stable_hash(hcx, hasher),
Err(ref x) => x.stable_hash(hcx, hasher),
Ok(ref x) => {
Tag::Ok.stable_hash(hcx, hasher);
x.stable_hash(hcx, hasher);
}
Err(ref x) => {
Tag::Err.stable_hash(hcx, hasher);
x.stable_hash(hcx, hasher);
}
}
}
}
Expand All @@ -551,12 +560,19 @@ where
}
}

impl<T> StableHash for ::std::mem::Discriminant<T> {
#[inline]
fn stable_hash<Hcx: StableHashCtxt>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
::std::hash::Hash::hash(self, hasher);
}
}
/// There is no way to stable-hash a `Discriminant` without leaking unstable
/// details of how the host compiler chooses and hashes discriminants.
///
/// That would be bad, because stable hashes must be consistent between
/// the stage1 compiler (built with the bootstrap compiler/stdlib)
/// and the stage2 compiler (built with the in-tree compiler/stdlib).
///
/// See <https://github.com/rust-lang/rust/issues/164734> for more context.
///
/// If you need to manually stable-hash a discriminant, instead derive `StableHash`
/// on a dedicated "tag" enum, and then hash the appropriate tag for each variant.
/// For an example, see the impl of `StableHash for Result`.
impl<T> !StableHash for std::mem::Discriminant<T> {}

impl<T> StableHash for ::std::range::RangeInclusive<T>
where
Expand Down
43 changes: 39 additions & 4 deletions compiler/rustc_macros/src/stable_hash.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use proc_macro2::Ident;
use quote::quote;
use quote::{ToTokens, quote};

struct Attributes {
ignore: bool,
Expand Down Expand Up @@ -96,9 +96,44 @@ fn stable_hash_derive_with_mode(

fn stable_hash_discriminant(s: &mut synstructure::Structure<'_>) -> proc_macro2::TokenStream {
match s.ast().data {
syn::Data::Enum(_) => quote! {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
},
syn::Data::Enum(_) => {
// For stable hashing, use a fake discriminant based on the syntactic
// ordering of enum variants, not the actual runtime discriminant.
// This helps to keep stable hashes consistent between stage1 and stage2.
let n_variants = s.variants().len();

// If this enum has no variants (and is therefore uninhabited),
// matching on `self` will cause the compiler to realise that all
// subsequent code is unreachable, triggering unhelpful warnings.
if n_variants == 0 {
return quote! {};
}

let mut match_arms = proc_macro2::TokenStream::new();

// Use a u8 discriminant, as it's measurably faster than usize.
// If support for larger enums is needed, take care to still use u8
// when possible, to avoid regressions.
assert!(
n_variants <= 256,
"deriving StableHash for an enum with more than 256 variants is unsupported \
(was: {n_variants})"
);
for (discriminant, variant) in (0u8..).zip(s.variants()) {

@oli-obk oli-obk Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will this actually cause the #discriminant in the quoted code to be a literal with a u8 postfix?

View changes since the review

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, when quote! interpolates an integer value it will add an explicit literal suffix of the corresponding type.

(I don’t know if this is explicitly documented anywhere, but the quote docs do mention that you have to wrap integer types if you want this suffixing to not happen.)

let pat = variant.pat();

quote! {
#pat => #discriminant.stable_hash(__hcx, __hasher),
}
.to_tokens(&mut match_arms);
}

quote! {
match *self {
#match_arms
}
}
}
syn::Data::Struct(_) => quote! {},
syn::Data::Union(_) => panic!("cannot derive on union"),
}
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_symbol_mangling/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ rustc_attr_ir = { path = "../rustc_attr_ir" }
rustc_data_structures = { path = "../rustc_data_structures" }
rustc_hashes = { path = "../rustc_hashes" }
rustc_hir = { path = "../rustc_hir" }
rustc_macros = { path = "../rustc_macros" }

@Zalathar Zalathar Oct 26, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rustc_symbol_mangling already depends on other crates that use rustc_macros, so adding it as a direct dependency should not affect build parallelism.

View changes since the review

rustc_middle = { path = "../rustc_middle" }
rustc_session = { path = "../rustc_session" }
rustc_span = { path = "../rustc_span" }
Expand Down
20 changes: 18 additions & 2 deletions compiler/rustc_symbol_mangling/src/legacy.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::fmt::{self, Write};
use std::mem::{self, discriminant};
use std::mem;

use rustc_data_structures::stable_hash::{StableHash, StableHasher};
use rustc_hashes::Hash64;
use rustc_hir::def_id::{CrateNum, DefId};
use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
use rustc_macros::StableHash;
use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer};
use rustc_middle::ty::{
self, GenericArg, GenericArgKind, Instance, ReifyReason, Ty, TyCtxt, TypeVisitableExt,
Expand Down Expand Up @@ -170,7 +171,22 @@ fn get_symbol_hash<'tcx>(
// We want to avoid accidental collision between different types of instances.
// Especially, `VTableShim`s and `ReifyShim`s may overlap with their original
// instances without this.
discriminant(&instance.def).stable_hash(hcx, &mut hasher);
#[derive(StableHash)]
enum Tag {
Item,
Intrinsic,
LlvmIntrinsic,
Virtual,
Shim,
}
match instance.def {
ty::InstanceKind::Item(_) => Tag::Item,
ty::InstanceKind::Intrinsic(_) => Tag::Intrinsic,
ty::InstanceKind::LlvmIntrinsic(_) => Tag::LlvmIntrinsic,
ty::InstanceKind::Virtual(_, _) => Tag::Virtual,
ty::InstanceKind::Shim(_) => Tag::Shim,
}
.stable_hash(hcx, &mut hasher);
});

// 64 bits should be enough to avoid collisions.
Expand Down
26 changes: 21 additions & 5 deletions compiler/rustc_type_ir/src/region_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use derive_where::derive_where;
#[cfg(feature = "nightly")]
use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
#[cfg(feature = "nightly")]
use rustc_macros::{Decodable_NoContext, Encodable_NoContext};
use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash};
use rustc_type_ir_macros::GenericTypeVisitable;

use self::RegionKind::*;
Expand Down Expand Up @@ -226,22 +226,38 @@ where
{
#[inline]
fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
std::mem::discriminant(self).stable_hash(hcx, hasher);
#[derive(StableHash)]
enum Tag {
ReErased,
ReStatic,
ReError,
ReBound,
ReEarlyParam,
ReLateParam,
RePlaceholder,
}

match self {
ReErased | ReStatic | ReError(_) => {
// No variant fields to hash for these ...
}
// No variant fields to hash for these ...
ReErased => Tag::ReErased.stable_hash(hcx, hasher),
ReStatic => Tag::ReStatic.stable_hash(hcx, hasher),
ReError(_) => Tag::ReError.stable_hash(hcx, hasher),

ReBound(d, r) => {
Tag::ReBound.stable_hash(hcx, hasher);
d.stable_hash(hcx, hasher);
r.stable_hash(hcx, hasher);
}
ReEarlyParam(r) => {
Tag::ReEarlyParam.stable_hash(hcx, hasher);
r.stable_hash(hcx, hasher);
}
ReLateParam(r) => {
Tag::ReLateParam.stable_hash(hcx, hasher);
r.stable_hash(hcx, hasher);
}
RePlaceholder(r) => {
Tag::RePlaceholder.stable_hash(hcx, hasher);
r.stable_hash(hcx, hasher);
}
ReVar(_) => {
Expand Down
25 changes: 22 additions & 3 deletions compiler/rustc_type_ir/src/ty_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use rustc_ast_ir::Mutability;
#[cfg(feature = "nightly")]
use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
#[cfg(feature = "nightly")]
use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash_NoContext};
use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash, StableHash_NoContext};
use rustc_type_ir::data_structures::{NoError, UnifyKey, UnifyValue};
use rustc_type_ir_macros::{
GenericTypeVisitable, Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic,
Expand Down Expand Up @@ -857,12 +857,31 @@ impl UnifyKey for FloatVid {
impl StableHash for InferTy {
fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
use InferTy::*;
std::mem::discriminant(self).stable_hash(hcx, hasher);

#[derive(StableHash)]
enum Tag {
FreshTy,
FreshIntTy,
FreshFloatTy,
}

match self {
TyVar(_) | IntVar(_) | FloatVar(_) => {
panic!("type variables should not be hashed: {self:?}")
}
FreshTy(v) | FreshIntTy(v) | FreshFloatTy(v) => v.stable_hash(hcx, hasher),

FreshTy(v) => {
Tag::FreshTy.stable_hash(hcx, hasher);
v.stable_hash(hcx, hasher);
}
FreshIntTy(v) => {
Tag::FreshIntTy.stable_hash(hcx, hasher);
v.stable_hash(hcx, hasher);
}
FreshFloatTy(v) => {
Tag::FreshFloatTy.stable_hash(hcx, hasher);
v.stable_hash(hcx, hasher);
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion tests/codegen-llvm/remap_path_prefix/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ mod aux_mod;
include!("aux_mod.rs");

// Here we check that the expansion of the file!() macro is mapped.
// CHECK: @alloc_5761061597a97f66e13ef2ff92712c4b = private unnamed_addr constant [34 x i8] c"/the/src/remap_path_prefix/main.rs"
// CHECK: @alloc_{{([0-9a-f]{32})}} = private unnamed_addr constant [34 x i8] c"/the/src/remap_path_prefix/main.rs"
pub static FILE_PATH: &'static str = file!();

fn main() {
Expand Down
2 changes: 1 addition & 1 deletion tests/debuginfo/function-names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
// Const generic parameter
//@ gdb-command:info functions -q function_names::const_generic_fn.*
//@ gdb-check:[...]static fn function_names::const_generic_fn_bool<false>();
//@ gdb-check:[...]static fn function_names::const_generic_fn_non_int<{CONST#68cf9e429c783d36}>();
//@ gdb-check:[...]static fn function_names::const_generic_fn_non_int<{CONST#[...]}>();
//@ gdb-check:[...]static fn function_names::const_generic_fn_signed_int<-7>();
//@ gdb-check:[...]static fn function_names::const_generic_fn_unsigned_int<14>();

Expand Down
Loading