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, TypeVisitable};
7 use rustc_middle::util::common::record_time;
9 use std::fmt::{self, Write};
10 use std::mem::{self, discriminant};
12 pub(super) fn mangle<'tcx>(
14 instance: Instance<'tcx>,
15 instantiating_crate: Option<CrateNum>,
17 let def_id = instance.def_id();
19 // We want to compute the "type" of this item. Unfortunately, some
20 // kinds of items (e.g., closures) don't have an entry in the
21 // item-type array. So walk back up the find the closest parent
22 // that DOES have an entry.
23 let mut ty_def_id = def_id;
26 let key = tcx.def_key(ty_def_id);
27 match key.disambiguated_data.data {
28 DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => {
29 instance_ty = tcx.type_of(ty_def_id);
34 // if we're making a symbol for something, there ought
35 // to be a value or type-def or something in there
37 ty_def_id.index = key.parent.unwrap_or_else(|| {
39 "finding type for {:?}, encountered def-id {:?} with no \
49 // Erase regions because they may not be deterministic when hashed
50 // and should not matter anyhow.
51 let instance_ty = tcx.erase_regions(instance_ty);
53 let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
55 let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false };
59 if let ty::InstanceDef::DropGlue(_, _) = instance.def {
60 // Add the name of the dropped type to the symbol name
68 if let ty::InstanceDef::VTableShim(..) = instance.def {
69 let _ = printer.write_str("{{vtable-shim}}");
72 if let ty::InstanceDef::ReifyShim(..) = instance.def {
73 let _ = printer.write_str("{{reify-shim}}");
76 printer.path.finish(hash)
79 fn get_symbol_hash<'tcx>(
82 // instance this name will be for
83 instance: Instance<'tcx>,
85 // type of the item, without any generic
86 // parameters substituted; this is
87 // included in the hash as a kind of
91 instantiating_crate: Option<CrateNum>,
93 let def_id = instance.def_id();
94 let substs = instance.substs;
95 debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs);
97 tcx.with_stable_hashing_context(|mut hcx| {
98 let mut hasher = StableHasher::new();
100 record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
101 // the main symbol name is not necessarily unique; hash in the
102 // compiler's internal def-path, guaranteeing each symbol has a
104 tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
106 // Include the main item-type. Note that, in this case, the
107 // assertions about `needs_subst` may not hold, but this item-type
108 // ought to be the same for every reference anyway.
109 assert!(!item_type.has_erasable_regions());
110 hcx.while_hashing_spans(false, |hcx| {
111 item_type.hash_stable(hcx, &mut hasher);
113 // If this is a function, we hash the signature as well.
114 // This is not *strictly* needed, but it may help in some
115 // situations, see the `run-make/a-b-a-linker-guard` test.
116 if let ty::FnDef(..) = item_type.kind() {
117 item_type.fn_sig(tcx).hash_stable(hcx, &mut hasher);
120 // also include any type parameters (for generic items)
121 substs.hash_stable(hcx, &mut hasher);
123 if let Some(instantiating_crate) = instantiating_crate {
124 tcx.def_path_hash(instantiating_crate.as_def_id())
126 .hash_stable(hcx, &mut hasher);
129 // We want to avoid accidental collision between different types of instances.
130 // Especially, `VTableShim`s and `ReifyShim`s may overlap with their original
131 // instances without this.
132 discriminant(&instance.def).hash_stable(hcx, &mut hasher);
136 // 64 bits should be enough to avoid collisions.
137 hasher.finish::<u64>()
141 // Follow C++ namespace-mangling style, see
142 // https://en.wikipedia.org/wiki/Name_mangling for more info.
144 // It turns out that on macOS you can actually have arbitrary symbols in
145 // function names (at least when given to LLVM), but this is not possible
146 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
147 // we won't need to do this name mangling. The problem with name mangling is
148 // that it seriously limits the available characters. For example we can't
149 // have things like &T in symbol names when one would theoretically
150 // want them for things like impls of traits on that type.
152 // To be able to work on all platforms and get *some* reasonable output, we
153 // use C++ name-mangling.
163 SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
164 result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
168 fn finalize_pending_component(&mut self) {
169 if !self.temp_buf.is_empty() {
170 let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
171 self.temp_buf.clear();
175 fn finish(mut self, hash: u64) -> String {
176 self.finalize_pending_component();
177 // E = end name-sequence
178 let _ = write!(self.result, "17h{:016x}E", hash);
183 struct SymbolPrinter<'tcx> {
187 // When `true`, `finalize_pending_component` isn't used.
188 // This is needed when recursing into `path_qualified`,
189 // or `path_generic_args`, as any nested paths are
190 // logically within one component.
191 keep_within_component: bool,
194 // HACK(eddyb) this relies on using the `fmt` interface to get
195 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
196 // symbol names should have their own printing machinery.
198 impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> {
199 type Error = fmt::Error;
204 type DynExistential = Self;
207 fn tcx(&self) -> TyCtxt<'tcx> {
211 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
215 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
217 // Print all nominal types as paths (unlike `pretty_print_type`).
218 ty::FnDef(def_id, substs)
219 | ty::Opaque(def_id, substs)
220 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
221 | ty::Closure(def_id, substs)
222 | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs),
224 // The `pretty_print_type` formatting of array size depends on
225 // -Zverbose flag, so we cannot reuse it here.
226 ty::Array(ty, size) => {
227 self.write_str("[")?;
228 self = self.print_type(ty)?;
229 self.write_str("; ")?;
230 if let Some(size) = size.kind().try_to_bits(self.tcx().data_layout.pointer_size) {
231 write!(self, "{}", size)?
232 } else if let ty::ConstKind::Param(param) = size.kind() {
233 self = param.print(self)?
237 self.write_str("]")?;
241 _ => self.pretty_print_type(ty),
245 fn print_dyn_existential(
247 predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
248 ) -> Result<Self::DynExistential, Self::Error> {
249 let mut first = true;
250 for p in predicates {
255 self = p.print(self)?;
260 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
261 // only print integers
262 match (ct.kind(), ct.ty().kind()) {
263 (ty::ConstKind::Value(ty::ValTree::Leaf(scalar)), ty::Int(_) | ty::Uint(_)) => {
264 // The `pretty_print_const` formatting depends on -Zverbose
265 // flag, so we cannot reuse it here.
266 let signed = matches!(ct.ty().kind(), ty::Int(_));
270 ty::ConstInt::new(scalar, signed, ct.ty().is_ptr_sized_integral())
273 _ => self.write_str("_")?,
278 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
279 self.write_str(self.tcx.crate_name(cnum).as_str())?;
285 trait_ref: Option<ty::TraitRef<'tcx>>,
286 ) -> Result<Self::Path, Self::Error> {
287 // Similar to `pretty_path_qualified`, but for the other
288 // types that are printed as paths (see `print_type` above).
289 match self_ty.kind() {
295 if trait_ref.is_none() =>
297 self.print_type(self_ty)
300 _ => self.pretty_path_qualified(self_ty, trait_ref),
306 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
307 _disambiguated_data: &DisambiguatedDefPathData,
309 trait_ref: Option<ty::TraitRef<'tcx>>,
310 ) -> Result<Self::Path, Self::Error> {
311 self.pretty_path_append_impl(
313 cx = print_prefix(cx)?;
315 if cx.keep_within_component {
316 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
319 cx.path.finalize_pending_component();
330 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
331 disambiguated_data: &DisambiguatedDefPathData,
332 ) -> Result<Self::Path, Self::Error> {
333 self = print_prefix(self)?;
335 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
336 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
340 if self.keep_within_component {
341 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
342 self.write_str("::")?;
344 self.path.finalize_pending_component();
347 write!(self, "{}", disambiguated_data.data)?;
351 fn path_generic_args(
353 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
354 args: &[GenericArg<'tcx>],
355 ) -> Result<Self::Path, Self::Error> {
356 self = print_prefix(self)?;
359 args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
361 if args.clone().next().is_some() {
362 self.generic_delimiters(|cx| cx.comma_sep(args))
369 impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> {
370 fn should_print_region(&self, _region: ty::Region<'_>) -> bool {
373 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
375 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
377 if let Some(first) = elems.next() {
378 self = first.print(self)?;
380 self.write_str(",")?;
381 self = elem.print(self)?;
387 fn generic_delimiters(
389 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
390 ) -> Result<Self, Self::Error> {
393 let kept_within_component = mem::replace(&mut self.keep_within_component, true);
395 self.keep_within_component = kept_within_component;
403 impl fmt::Write for SymbolPrinter<'_> {
404 fn write_str(&mut self, s: &str) -> fmt::Result {
405 // Name sanitation. LLVM will happily accept identifiers with weird names, but
407 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
408 // NVPTX assembly has more strict naming rules than gas, so additionally, dots
409 // are replaced with '$' there.
412 if self.path.temp_buf.is_empty() {
414 'a'..='z' | 'A'..='Z' | '_' => {}
416 // Underscore-qualify anything that didn't start as an ident.
417 self.path.temp_buf.push('_');
422 // Escape these with $ sequences
423 '@' => self.path.temp_buf.push_str("$SP$"),
424 '*' => self.path.temp_buf.push_str("$BP$"),
425 '&' => self.path.temp_buf.push_str("$RF$"),
426 '<' => self.path.temp_buf.push_str("$LT$"),
427 '>' => self.path.temp_buf.push_str("$GT$"),
428 '(' => self.path.temp_buf.push_str("$LP$"),
429 ')' => self.path.temp_buf.push_str("$RP$"),
430 ',' => self.path.temp_buf.push_str("$C$"),
432 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
433 // NVPTX doesn't support these characters in symbol names.
434 self.path.temp_buf.push('$')
437 // '.' doesn't occur in types and functions, so reuse it
439 '-' | ':' => self.path.temp_buf.push('.'),
441 // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
442 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
444 // These are legal symbols
445 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
448 self.path.temp_buf.push('$');
449 for c in c.escape_unicode().skip(1) {
452 '}' => self.path.temp_buf.push('$'),
453 c => self.path.temp_buf.push(c),