]> git.lizzy.rs Git - rust.git/blob - src/librustc_symbol_mangling/legacy.rs
Rollup merge of #75485 - RalfJung:pin, r=nagisa
[rust.git] / src / librustc_symbol_mangling / legacy.rs
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::ich::NodeIdHashingMode;
5 use rustc_middle::mir::interpret::{ConstValue, Scalar};
6 use rustc_middle::ty::print::{PrettyPrinter, Print, Printer};
7 use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
8 use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable};
9 use rustc_middle::util::common::record_time;
10
11 use tracing::debug;
12
13 use std::fmt::{self, Write};
14 use std::mem::{self, discriminant};
15
16 pub(super) fn mangle(
17     tcx: TyCtxt<'tcx>,
18     instance: Instance<'tcx>,
19     instantiating_crate: Option<CrateNum>,
20 ) -> String {
21     let def_id = instance.def_id();
22
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;
28     let instance_ty;
29     loop {
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);
34                 break;
35             }
36             _ => {
37                 // if we're making a symbol for something, there ought
38                 // to be a value or type-def or something in there
39                 // *somewhere*
40                 ty_def_id.index = key.parent.unwrap_or_else(|| {
41                     bug!(
42                         "finding type for {:?}, encountered def-id {:?} with no \
43                          parent",
44                         def_id,
45                         ty_def_id
46                     );
47                 });
48             }
49         }
50     }
51
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);
55
56     let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate);
57
58     let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false }
59         .print_def_path(def_id, &[])
60         .unwrap();
61
62     if let ty::InstanceDef::VtableShim(..) = instance.def {
63         let _ = printer.write_str("{{vtable-shim}}");
64     }
65
66     if let ty::InstanceDef::ReifyShim(..) = instance.def {
67         let _ = printer.write_str("{{reify-shim}}");
68     }
69
70     printer.path.finish(hash)
71 }
72
73 fn get_symbol_hash<'tcx>(
74     tcx: TyCtxt<'tcx>,
75
76     // instance this name will be for
77     instance: Instance<'tcx>,
78
79     // type of the item, without any generic
80     // parameters substituted; this is
81     // included in the hash as a kind of
82     // safeguard.
83     item_type: Ty<'tcx>,
84
85     instantiating_crate: Option<CrateNum>,
86 ) -> u64 {
87     let def_id = instance.def_id();
88     let substs = instance.substs;
89     debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs);
90
91     let mut hasher = StableHasher::new();
92     let mut hcx = tcx.create_stable_hashing_context();
93
94     record_time(&tcx.sess.perf_stats.symbol_hash_time, || {
95         // the main symbol name is not necessarily unique; hash in the
96         // compiler's internal def-path, guaranteeing each symbol has a
97         // truly unique path
98         tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher);
99
100         // Include the main item-type. Note that, in this case, the
101         // assertions about `needs_subst` may not hold, but this item-type
102         // ought to be the same for every reference anyway.
103         assert!(!item_type.has_erasable_regions());
104         hcx.while_hashing_spans(false, |hcx| {
105             hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
106                 item_type.hash_stable(hcx, &mut hasher);
107             });
108         });
109
110         // If this is a function, we hash the signature as well.
111         // This is not *strictly* needed, but it may help in some
112         // situations, see the `run-make/a-b-a-linker-guard` test.
113         if let ty::FnDef(..) = item_type.kind {
114             item_type.fn_sig(tcx).hash_stable(&mut hcx, &mut hasher);
115         }
116
117         // also include any type parameters (for generic items)
118         assert!(!substs.has_erasable_regions());
119         substs.hash_stable(&mut hcx, &mut hasher);
120
121         if let Some(instantiating_crate) = instantiating_crate {
122             tcx.original_crate_name(instantiating_crate)
123                 .as_str()
124                 .hash_stable(&mut hcx, &mut hasher);
125             tcx.crate_disambiguator(instantiating_crate).hash_stable(&mut hcx, &mut hasher);
126         }
127
128         // We want to avoid accidental collision between different types of instances.
129         // Especially, `VtableShim`s and `ReifyShim`s may overlap with their original
130         // instances without this.
131         discriminant(&instance.def).hash_stable(&mut hcx, &mut hasher);
132     });
133
134     // 64 bits should be enough to avoid collisions.
135     hasher.finish::<u64>()
136 }
137
138 // Follow C++ namespace-mangling style, see
139 // http://en.wikipedia.org/wiki/Name_mangling for more info.
140 //
141 // It turns out that on macOS you can actually have arbitrary symbols in
142 // function names (at least when given to LLVM), but this is not possible
143 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
144 // we won't need to do this name mangling. The problem with name mangling is
145 // that it seriously limits the available characters. For example we can't
146 // have things like &T in symbol names when one would theoretically
147 // want them for things like impls of traits on that type.
148 //
149 // To be able to work on all platforms and get *some* reasonable output, we
150 // use C++ name-mangling.
151 #[derive(Debug)]
152 struct SymbolPath {
153     result: String,
154     temp_buf: String,
155 }
156
157 impl SymbolPath {
158     fn new() -> Self {
159         let mut result =
160             SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
161         result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
162         result
163     }
164
165     fn finalize_pending_component(&mut self) {
166         if !self.temp_buf.is_empty() {
167             let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
168             self.temp_buf.clear();
169         }
170     }
171
172     fn finish(mut self, hash: u64) -> String {
173         self.finalize_pending_component();
174         // E = end name-sequence
175         let _ = write!(self.result, "17h{:016x}E", hash);
176         self.result
177     }
178 }
179
180 struct SymbolPrinter<'tcx> {
181     tcx: TyCtxt<'tcx>,
182     path: SymbolPath,
183
184     // When `true`, `finalize_pending_component` isn't used.
185     // This is needed when recursing into `path_qualified`,
186     // or `path_generic_args`, as any nested paths are
187     // logically within one component.
188     keep_within_component: bool,
189 }
190
191 // HACK(eddyb) this relies on using the `fmt` interface to get
192 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
193 // symbol names should have their own printing machinery.
194
195 impl Printer<'tcx> for SymbolPrinter<'tcx> {
196     type Error = fmt::Error;
197
198     type Path = Self;
199     type Region = Self;
200     type Type = Self;
201     type DynExistential = Self;
202     type Const = Self;
203
204     fn tcx(&self) -> TyCtxt<'tcx> {
205         self.tcx
206     }
207
208     fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
209         Ok(self)
210     }
211
212     fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
213         match ty.kind {
214             // Print all nominal types as paths (unlike `pretty_print_type`).
215             ty::FnDef(def_id, substs)
216             | ty::Opaque(def_id, substs)
217             | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
218             | ty::Closure(def_id, substs)
219             | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs),
220             _ => self.pretty_print_type(ty),
221         }
222     }
223
224     fn print_dyn_existential(
225         mut self,
226         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
227     ) -> Result<Self::DynExistential, Self::Error> {
228         let mut first = true;
229         for p in predicates {
230             if !first {
231                 write!(self, "+")?;
232             }
233             first = false;
234             self = p.print(self)?;
235         }
236         Ok(self)
237     }
238
239     fn print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
240         // only print integers
241         if let ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { .. })) = ct.val {
242             if ct.ty.is_integral() {
243                 return self.pretty_print_const(ct, true);
244             }
245         }
246         self.write_str("_")?;
247         Ok(self)
248     }
249
250     fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
251         self.write_str(&self.tcx.original_crate_name(cnum).as_str())?;
252         Ok(self)
253     }
254     fn path_qualified(
255         self,
256         self_ty: Ty<'tcx>,
257         trait_ref: Option<ty::TraitRef<'tcx>>,
258     ) -> Result<Self::Path, Self::Error> {
259         // Similar to `pretty_path_qualified`, but for the other
260         // types that are printed as paths (see `print_type` above).
261         match self_ty.kind {
262             ty::FnDef(..)
263             | ty::Opaque(..)
264             | ty::Projection(_)
265             | ty::Closure(..)
266             | ty::Generator(..)
267                 if trait_ref.is_none() =>
268             {
269                 self.print_type(self_ty)
270             }
271
272             _ => self.pretty_path_qualified(self_ty, trait_ref),
273         }
274     }
275
276     fn path_append_impl(
277         self,
278         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
279         _disambiguated_data: &DisambiguatedDefPathData,
280         self_ty: Ty<'tcx>,
281         trait_ref: Option<ty::TraitRef<'tcx>>,
282     ) -> Result<Self::Path, Self::Error> {
283         self.pretty_path_append_impl(
284             |mut cx| {
285                 cx = print_prefix(cx)?;
286
287                 if cx.keep_within_component {
288                     // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
289                     cx.write_str("::")?;
290                 } else {
291                     cx.path.finalize_pending_component();
292                 }
293
294                 Ok(cx)
295             },
296             self_ty,
297             trait_ref,
298         )
299     }
300     fn path_append(
301         mut self,
302         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
303         disambiguated_data: &DisambiguatedDefPathData,
304     ) -> Result<Self::Path, Self::Error> {
305         self = print_prefix(self)?;
306
307         // Skip `::{{constructor}}` on tuple/unit structs.
308         if let DefPathData::Ctor = disambiguated_data.data {
309             return Ok(self);
310         }
311
312         if self.keep_within_component {
313             // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
314             self.write_str("::")?;
315         } else {
316             self.path.finalize_pending_component();
317         }
318
319         self.write_str(&disambiguated_data.data.as_symbol().as_str())?;
320         Ok(self)
321     }
322     fn path_generic_args(
323         mut self,
324         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
325         args: &[GenericArg<'tcx>],
326     ) -> Result<Self::Path, Self::Error> {
327         self = print_prefix(self)?;
328
329         let args = args.iter().cloned().filter(|arg| match arg.unpack() {
330             GenericArgKind::Lifetime(_) => false,
331             _ => true,
332         });
333
334         if args.clone().next().is_some() {
335             self.generic_delimiters(|cx| cx.comma_sep(args))
336         } else {
337             Ok(self)
338         }
339     }
340 }
341
342 impl PrettyPrinter<'tcx> for SymbolPrinter<'tcx> {
343     fn region_should_not_be_omitted(&self, _region: ty::Region<'_>) -> bool {
344         false
345     }
346     fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
347     where
348         T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
349     {
350         if let Some(first) = elems.next() {
351             self = first.print(self)?;
352             for elem in elems {
353                 self.write_str(",")?;
354                 self = elem.print(self)?;
355             }
356         }
357         Ok(self)
358     }
359
360     fn generic_delimiters(
361         mut self,
362         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
363     ) -> Result<Self, Self::Error> {
364         write!(self, "<")?;
365
366         let kept_within_component = mem::replace(&mut self.keep_within_component, true);
367         self = f(self)?;
368         self.keep_within_component = kept_within_component;
369
370         write!(self, ">")?;
371
372         Ok(self)
373     }
374 }
375
376 impl fmt::Write for SymbolPrinter<'_> {
377     fn write_str(&mut self, s: &str) -> fmt::Result {
378         // Name sanitation. LLVM will happily accept identifiers with weird names, but
379         // gas doesn't!
380         // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
381         // NVPTX assembly has more strict naming rules than gas, so additionally, dots
382         // are replaced with '$' there.
383
384         for c in s.chars() {
385             if self.path.temp_buf.is_empty() {
386                 match c {
387                     'a'..='z' | 'A'..='Z' | '_' => {}
388                     _ => {
389                         // Underscore-qualify anything that didn't start as an ident.
390                         self.path.temp_buf.push('_');
391                     }
392                 }
393             }
394             match c {
395                 // Escape these with $ sequences
396                 '@' => self.path.temp_buf.push_str("$SP$"),
397                 '*' => self.path.temp_buf.push_str("$BP$"),
398                 '&' => self.path.temp_buf.push_str("$RF$"),
399                 '<' => self.path.temp_buf.push_str("$LT$"),
400                 '>' => self.path.temp_buf.push_str("$GT$"),
401                 '(' => self.path.temp_buf.push_str("$LP$"),
402                 ')' => self.path.temp_buf.push_str("$RP$"),
403                 ',' => self.path.temp_buf.push_str("$C$"),
404
405                 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
406                     // NVPTX doesn't support these characters in symbol names.
407                     self.path.temp_buf.push('$')
408                 }
409
410                 // '.' doesn't occur in types and functions, so reuse it
411                 // for ':' and '-'
412                 '-' | ':' => self.path.temp_buf.push('.'),
413
414                 // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
415                 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
416
417                 // These are legal symbols
418                 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
419
420                 _ => {
421                     self.path.temp_buf.push('$');
422                     for c in c.escape_unicode().skip(1) {
423                         match c {
424                             '{' => {}
425                             '}' => self.path.temp_buf.push('$'),
426                             c => self.path.temp_buf.push(c),
427                         }
428                     }
429                 }
430             }
431         }
432
433         Ok(())
434     }
435 }