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::ty::print::{PrettyPrinter, Print, Printer};
5 use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
6 use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable};
7 use rustc_middle::util::common::record_time;
11 use std::fmt::{self, Write};
12 use std::mem::{self, discriminant};
14 pub(super) fn mangle<'tcx>(
16 instance: Instance<'tcx>,
17 instantiating_crate: Option<CrateNum>,
19 let def_id = instance.def_id();
21 // We want to compute the "type" of this item. Unfortunately, some
22 // kinds of items (e.g., closures) don't have an entry in the
23 // item-type array. So walk back up the find the closest parent
24 // that DOES have an entry.
25 let mut ty_def_id = def_id;
28 let key = tcx.def_key(ty_def_id);
29 match key.disambiguated_data.data {
30 DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => {
31 instance_ty = tcx.type_of(ty_def_id);
36 // if we're making a symbol for something, there ought
37 // to be a value or type-def or something in there
39 ty_def_id.index = key.parent.unwrap_or_else(|| {
41 "finding type for {:?}, encountered def-id {:?} with no \
51 // Erase regions because they may not be deterministic when hashed
52 // and should not matter anyhow.
53 let instance_ty = tcx.erase_regions(instance_ty);
55 let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
57 let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false };
61 if let ty::InstanceDef::DropGlue(_, _) = instance.def {
62 // Add the name of the dropped type to the symbol name
70 if let ty::InstanceDef::VtableShim(..) = instance.def {
71 let _ = printer.write_str("{{vtable-shim}}");
74 if let ty::InstanceDef::ReifyShim(..) = instance.def {
75 let _ = printer.write_str("{{reify-shim}}");
78 printer.path.finish(hash)
81 fn get_symbol_hash<'tcx>(
84 // instance this name will be for
85 instance: Instance<'tcx>,
87 // type of the item, without any generic
88 // parameters substituted; this is
89 // included in the hash as a kind of
93 instantiating_crate: Option<CrateNum>,
95 let def_id = instance.def_id();
96 let substs = instance.substs;
97 debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs);
99 let mut hasher = StableHasher::new();
100 let mut hcx = tcx.create_stable_hashing_context();
102 record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
103 // the main symbol name is not necessarily unique; hash in the
104 // compiler's internal def-path, guaranteeing each symbol has a
106 tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
108 // Include the main item-type. Note that, in this case, the
109 // assertions about `needs_subst` may not hold, but this item-type
110 // ought to be the same for every reference anyway.
111 assert!(!item_type.has_erasable_regions());
112 hcx.while_hashing_spans(false, |hcx| {
113 item_type.hash_stable(hcx, &mut hasher);
115 // If this is a function, we hash the signature as well.
116 // This is not *strictly* needed, but it may help in some
117 // situations, see the `run-make/a-b-a-linker-guard` test.
118 if let ty::FnDef(..) = item_type.kind() {
119 item_type.fn_sig(tcx).hash_stable(hcx, &mut hasher);
122 // also include any type parameters (for generic items)
123 substs.hash_stable(hcx, &mut hasher);
125 if let Some(instantiating_crate) = instantiating_crate {
126 tcx.def_path_hash(instantiating_crate.as_def_id())
128 .hash_stable(hcx, &mut hasher);
131 // We want to avoid accidental collision between different types of instances.
132 // Especially, `VtableShim`s and `ReifyShim`s may overlap with their original
133 // instances without this.
134 discriminant(&instance.def).hash_stable(hcx, &mut hasher);
138 // 64 bits should be enough to avoid collisions.
139 hasher.finish::<u64>()
142 // Follow C++ namespace-mangling style, see
143 // https://en.wikipedia.org/wiki/Name_mangling for more info.
145 // It turns out that on macOS you can actually have arbitrary symbols in
146 // function names (at least when given to LLVM), but this is not possible
147 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
148 // we won't need to do this name mangling. The problem with name mangling is
149 // that it seriously limits the available characters. For example we can't
150 // have things like &T in symbol names when one would theoretically
151 // want them for things like impls of traits on that type.
153 // To be able to work on all platforms and get *some* reasonable output, we
154 // use C++ name-mangling.
164 SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
165 result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
169 fn finalize_pending_component(&mut self) {
170 if !self.temp_buf.is_empty() {
171 let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
172 self.temp_buf.clear();
176 fn finish(mut self, hash: u64) -> String {
177 self.finalize_pending_component();
178 // E = end name-sequence
179 let _ = write!(self.result, "17h{:016x}E", hash);
184 struct SymbolPrinter<'tcx> {
188 // When `true`, `finalize_pending_component` isn't used.
189 // This is needed when recursing into `path_qualified`,
190 // or `path_generic_args`, as any nested paths are
191 // logically within one component.
192 keep_within_component: bool,
195 // HACK(eddyb) this relies on using the `fmt` interface to get
196 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
197 // symbol names should have their own printing machinery.
199 impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> {
200 type Error = fmt::Error;
205 type DynExistential = Self;
208 fn tcx(&self) -> TyCtxt<'tcx> {
212 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
216 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
218 // Print all nominal types as paths (unlike `pretty_print_type`).
219 ty::FnDef(def_id, substs)
220 | ty::Opaque(def_id, substs)
221 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
222 | ty::Closure(def_id, substs)
223 | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs),
225 // The `pretty_print_type` formatting of array size depends on
226 // -Zverbose flag, so we cannot reuse it here.
227 ty::Array(ty, size) => {
228 self.write_str("[")?;
229 self = self.print_type(ty)?;
230 self.write_str("; ")?;
231 if let Some(size) = size.kind().try_to_bits(self.tcx().data_layout.pointer_size) {
232 write!(self, "{}", size)?
233 } else if let ty::ConstKind::Param(param) = size.kind() {
234 self = param.print(self)?
238 self.write_str("]")?;
242 _ => self.pretty_print_type(ty),
246 fn print_dyn_existential(
248 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
249 ) -> Result<Self::DynExistential, Self::Error> {
250 let mut first = true;
251 for p in predicates {
256 self = p.print(self)?;
261 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
262 // only print integers
263 match (ct.kind(), ct.ty().kind()) {
264 (ty::ConstKind::Value(ty::ValTree::Leaf(scalar)), ty::Int(_) | ty::Uint(_)) => {
265 // The `pretty_print_const` formatting depends on -Zverbose
266 // flag, so we cannot reuse it here.
267 let signed = matches!(ct.ty().kind(), ty::Int(_));
271 ty::ConstInt::new(scalar, signed, ct.ty().is_ptr_sized_integral())
274 _ => self.write_str("_")?,
279 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
280 self.write_str(self.tcx.crate_name(cnum).as_str())?;
286 trait_ref: Option<ty::TraitRef<'tcx>>,
287 ) -> Result<Self::Path, Self::Error> {
288 // Similar to `pretty_path_qualified`, but for the other
289 // types that are printed as paths (see `print_type` above).
290 match self_ty.kind() {
296 if trait_ref.is_none() =>
298 self.print_type(self_ty)
301 _ => self.pretty_path_qualified(self_ty, trait_ref),
307 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
308 _disambiguated_data: &DisambiguatedDefPathData,
310 trait_ref: Option<ty::TraitRef<'tcx>>,
311 ) -> Result<Self::Path, Self::Error> {
312 self.pretty_path_append_impl(
314 cx = print_prefix(cx)?;
316 if cx.keep_within_component {
317 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
320 cx.path.finalize_pending_component();
331 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
332 disambiguated_data: &DisambiguatedDefPathData,
333 ) -> Result<Self::Path, Self::Error> {
334 self = print_prefix(self)?;
336 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
337 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
341 if self.keep_within_component {
342 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
343 self.write_str("::")?;
345 self.path.finalize_pending_component();
348 write!(self, "{}", disambiguated_data.data)?;
352 fn path_generic_args(
354 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
355 args: &[GenericArg<'tcx>],
356 ) -> Result<Self::Path, Self::Error> {
357 self = print_prefix(self)?;
360 args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
362 if args.clone().next().is_some() {
363 self.generic_delimiters(|cx| cx.comma_sep(args))
370 impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> {
371 fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
374 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
376 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
378 if let Some(first) = elems.next() {
379 self = first.print(self)?;
381 self.write_str(",")?;
382 self = elem.print(self)?;
388 fn generic_delimiters(
390 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
391 ) -> Result<Self, Self::Error> {
394 let kept_within_component = mem::replace(&mut self.keep_within_component, true);
396 self.keep_within_component = kept_within_component;
404 impl fmt::Write for SymbolPrinter<'_> {
405 fn write_str(&mut self, s: &str) -> fmt::Result {
406 // Name sanitation. LLVM will happily accept identifiers with weird names, but
408 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
409 // NVPTX assembly has more strict naming rules than gas, so additionally, dots
410 // are replaced with '$' there.
413 if self.path.temp_buf.is_empty() {
415 'a'..='z' | 'A'..='Z' | '_' => {}
417 // Underscore-qualify anything that didn't start as an ident.
418 self.path.temp_buf.push('_');
423 // Escape these with $ sequences
424 '@' => self.path.temp_buf.push_str("$SP$"),
425 '*' => self.path.temp_buf.push_str("$BP$"),
426 '&' => self.path.temp_buf.push_str("$RF$"),
427 '<' => self.path.temp_buf.push_str("$LT$"),
428 '>' => self.path.temp_buf.push_str("$GT$"),
429 '(' => self.path.temp_buf.push_str("$LP$"),
430 ')' => self.path.temp_buf.push_str("$RP$"),
431 ',' => self.path.temp_buf.push_str("$C$"),
433 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
434 // NVPTX doesn't support these characters in symbol names.
435 self.path.temp_buf.push('$')
438 // '.' doesn't occur in types and functions, so reuse it
440 '-' | ':' => self.path.temp_buf.push('.'),
442 // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
443 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
445 // These are legal symbols
446 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
449 self.path.temp_buf.push('$');
450 for c in c.escape_unicode().skip(1) {
453 '}' => self.path.temp_buf.push('$'),
454 c => self.path.temp_buf.push(c),