1 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
2 use rustc_hir::def_id::CrateNum;
3 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
4 use rustc_middle::mir::interpret::{ConstValue, Scalar};
5 use rustc_middle::ty::print::{PrettyPrinter, Print, Printer};
6 use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
7 use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable};
8 use rustc_middle::util::common::record_time;
9 use rustc_query_system::ich::NodeIdHashingMode;
13 use std::fmt::{self, Write};
14 use std::mem::{self, discriminant};
16 pub(super) fn mangle<'tcx>(
18 instance: Instance<'tcx>,
19 instantiating_crate: Option<CrateNum>,
21 let def_id = instance.def_id();
23 // We want to compute the "type" of this item. Unfortunately, some
24 // kinds of items (e.g., closures) don't have an entry in the
25 // item-type array. So walk back up the find the closest parent
26 // that DOES have an entry.
27 let mut ty_def_id = def_id;
30 let key = tcx.def_key(ty_def_id);
31 match key.disambiguated_data.data {
32 DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => {
33 instance_ty = tcx.type_of(ty_def_id);
37 // if we're making a symbol for something, there ought
38 // to be a value or type-def or something in there
40 ty_def_id.index = key.parent.unwrap_or_else(|| {
42 "finding type for {:?}, encountered def-id {:?} with no \
52 // Erase regions because they may not be deterministic when hashed
53 // and should not matter anyhow.
54 let instance_ty = tcx.erase_regions(instance_ty);
56 let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
58 let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false };
62 if let ty::InstanceDef::DropGlue(_, _) = instance.def {
63 // Add the name of the dropped type to the symbol name
71 if let ty::InstanceDef::VtableShim(..) = instance.def {
72 let _ = printer.write_str("{{vtable-shim}}");
75 if let ty::InstanceDef::ReifyShim(..) = instance.def {
76 let _ = printer.write_str("{{reify-shim}}");
79 printer.path.finish(hash)
82 fn get_symbol_hash<'tcx>(
85 // instance this name will be for
86 instance: Instance<'tcx>,
88 // type of the item, without any generic
89 // parameters substituted; this is
90 // included in the hash as a kind of
94 instantiating_crate: Option<CrateNum>,
96 let def_id = instance.def_id();
97 let substs = instance.substs;
98 debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs);
100 let mut hasher = StableHasher::new();
101 let mut hcx = tcx.create_stable_hashing_context();
103 record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
104 // the main symbol name is not necessarily unique; hash in the
105 // compiler's internal def-path, guaranteeing each symbol has a
107 tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
109 // Include the main item-type. Note that, in this case, the
110 // assertions about `definitely_needs_subst` may not hold, but this item-type
111 // ought to be the same for every reference anyway.
112 assert!(!item_type.has_erasable_regions(tcx));
113 hcx.while_hashing_spans(false, |hcx| {
114 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
115 item_type.hash_stable(hcx, &mut hasher);
119 // If this is a function, we hash the signature as well.
120 // This is not *strictly* needed, but it may help in some
121 // situations, see the `run-make/a-b-a-linker-guard` test.
122 if let ty::FnDef(..) = item_type.kind() {
123 item_type.fn_sig(tcx).hash_stable(&mut hcx, &mut hasher);
126 // also include any type parameters (for generic items)
127 substs.hash_stable(&mut hcx, &mut hasher);
129 if let Some(instantiating_crate) = instantiating_crate {
130 tcx.def_path_hash(instantiating_crate.as_def_id())
132 .hash_stable(&mut hcx, &mut hasher);
135 // We want to avoid accidental collision between different types of instances.
136 // Especially, `VtableShim`s and `ReifyShim`s may overlap with their original
137 // instances without this.
138 discriminant(&instance.def).hash_stable(&mut hcx, &mut hasher);
141 // 64 bits should be enough to avoid collisions.
142 hasher.finish::<u64>()
145 // Follow C++ namespace-mangling style, see
146 // https://en.wikipedia.org/wiki/Name_mangling for more info.
148 // It turns out that on macOS you can actually have arbitrary symbols in
149 // function names (at least when given to LLVM), but this is not possible
150 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
151 // we won't need to do this name mangling. The problem with name mangling is
152 // that it seriously limits the available characters. For example we can't
153 // have things like &T in symbol names when one would theoretically
154 // want them for things like impls of traits on that type.
156 // To be able to work on all platforms and get *some* reasonable output, we
157 // use C++ name-mangling.
167 SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
168 result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
172 fn finalize_pending_component(&mut self) {
173 if !self.temp_buf.is_empty() {
174 let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
175 self.temp_buf.clear();
179 fn finish(mut self, hash: u64) -> String {
180 self.finalize_pending_component();
181 // E = end name-sequence
182 let _ = write!(self.result, "17h{:016x}E", hash);
187 struct SymbolPrinter<'tcx> {
191 // When `true`, `finalize_pending_component` isn't used.
192 // This is needed when recursing into `path_qualified`,
193 // or `path_generic_args`, as any nested paths are
194 // logically within one component.
195 keep_within_component: bool,
198 // HACK(eddyb) this relies on using the `fmt` interface to get
199 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
200 // symbol names should have their own printing machinery.
202 impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> {
203 type Error = fmt::Error;
208 type DynExistential = Self;
211 fn tcx(&self) -> TyCtxt<'tcx> {
215 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
219 fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
221 // Print all nominal types as paths (unlike `pretty_print_type`).
222 ty::FnDef(def_id, substs)
223 | ty::Opaque(def_id, substs)
224 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
225 | ty::Closure(def_id, substs)
226 | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs),
227 _ => self.pretty_print_type(ty),
231 fn print_dyn_existential(
233 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
234 ) -> Result<Self::DynExistential, Self::Error> {
235 let mut first = true;
236 for p in predicates {
241 self = p.print(self)?;
246 fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
247 // only print integers
248 if let ty::ConstKind::Value(ConstValue::Scalar(Scalar::Int { .. })) = ct.val {
249 if ct.ty.is_integral() {
250 return self.pretty_print_const(ct, true);
253 self.write_str("_")?;
257 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
258 self.write_str(self.tcx.crate_name(cnum).as_str())?;
264 trait_ref: Option<ty::TraitRef<'tcx>>,
265 ) -> Result<Self::Path, Self::Error> {
266 // Similar to `pretty_path_qualified`, but for the other
267 // types that are printed as paths (see `print_type` above).
268 match self_ty.kind() {
274 if trait_ref.is_none() =>
276 self.print_type(self_ty)
279 _ => self.pretty_path_qualified(self_ty, trait_ref),
285 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
286 _disambiguated_data: &DisambiguatedDefPathData,
288 trait_ref: Option<ty::TraitRef<'tcx>>,
289 ) -> Result<Self::Path, Self::Error> {
290 self.pretty_path_append_impl(
292 cx = print_prefix(cx)?;
294 if cx.keep_within_component {
295 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
298 cx.path.finalize_pending_component();
309 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
310 disambiguated_data: &DisambiguatedDefPathData,
311 ) -> Result<Self::Path, Self::Error> {
312 self = print_prefix(self)?;
314 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
315 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
319 if self.keep_within_component {
320 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
321 self.write_str("::")?;
323 self.path.finalize_pending_component();
326 write!(self, "{}", disambiguated_data.data)?;
330 fn path_generic_args(
332 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
333 args: &[GenericArg<'tcx>],
334 ) -> Result<Self::Path, Self::Error> {
335 self = print_prefix(self)?;
338 args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
340 if args.clone().next().is_some() {
341 self.generic_delimiters(|cx| cx.comma_sep(args))
348 impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> {
349 fn region_should_not_be_omitted(&self, _region: ty::Region<'_>) -> bool {
352 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
354 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
356 if let Some(first) = elems.next() {
357 self = first.print(self)?;
359 self.write_str(",")?;
360 self = elem.print(self)?;
366 fn generic_delimiters(
368 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
369 ) -> Result<Self, Self::Error> {
372 let kept_within_component = mem::replace(&mut self.keep_within_component, true);
374 self.keep_within_component = kept_within_component;
382 impl fmt::Write for SymbolPrinter<'_> {
383 fn write_str(&mut self, s: &str) -> fmt::Result {
384 // Name sanitation. LLVM will happily accept identifiers with weird names, but
386 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
387 // NVPTX assembly has more strict naming rules than gas, so additionally, dots
388 // are replaced with '$' there.
391 if self.path.temp_buf.is_empty() {
393 'a'..='z' | 'A'..='Z' | '_' => {}
395 // Underscore-qualify anything that didn't start as an ident.
396 self.path.temp_buf.push('_');
401 // Escape these with $ sequences
402 '@' => self.path.temp_buf.push_str("$SP$"),
403 '*' => self.path.temp_buf.push_str("$BP$"),
404 '&' => self.path.temp_buf.push_str("$RF$"),
405 '<' => self.path.temp_buf.push_str("$LT$"),
406 '>' => self.path.temp_buf.push_str("$GT$"),
407 '(' => self.path.temp_buf.push_str("$LP$"),
408 ')' => self.path.temp_buf.push_str("$RP$"),
409 ',' => self.path.temp_buf.push_str("$C$"),
411 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
412 // NVPTX doesn't support these characters in symbol names.
413 self.path.temp_buf.push('$')
416 // '.' doesn't occur in types and functions, so reuse it
418 '-' | ':' => self.path.temp_buf.push('.'),
420 // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
421 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
423 // These are legal symbols
424 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
427 self.path.temp_buf.push('$');
428 for c in c.escape_unicode().skip(1) {
431 '}' => self.path.temp_buf.push('$'),
432 c => self.path.temp_buf.push(c),