]> git.proxmox.com Git - rustc.git/blob - src/librustc_symbol_mangling/legacy.rs
New upstream version 1.44.1+dfsg1
[rustc.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 log::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 assert!(!substs.needs_subst());
120 substs.hash_stable(&mut hcx, &mut hasher);
121
122 if let Some(instantiating_crate) = instantiating_crate {
123 tcx.original_crate_name(instantiating_crate)
124 .as_str()
125 .hash_stable(&mut hcx, &mut hasher);
126 tcx.crate_disambiguator(instantiating_crate).hash_stable(&mut hcx, &mut hasher);
127 }
128
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(&mut hcx, &mut hasher);
133 });
134
135 // 64 bits should be enough to avoid collisions.
136 hasher.finish::<u64>()
137 }
138
139 // Follow C++ namespace-mangling style, see
140 // http://en.wikipedia.org/wiki/Name_mangling for more info.
141 //
142 // It turns out that on macOS you can actually have arbitrary symbols in
143 // function names (at least when given to LLVM), but this is not possible
144 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
145 // we won't need to do this name mangling. The problem with name mangling is
146 // that it seriously limits the available characters. For example we can't
147 // have things like &T in symbol names when one would theoretically
148 // want them for things like impls of traits on that type.
149 //
150 // To be able to work on all platforms and get *some* reasonable output, we
151 // use C++ name-mangling.
152 #[derive(Debug)]
153 struct SymbolPath {
154 result: String,
155 temp_buf: String,
156 }
157
158 impl SymbolPath {
159 fn new() -> Self {
160 let mut result =
161 SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) };
162 result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested
163 result
164 }
165
166 fn finalize_pending_component(&mut self) {
167 if !self.temp_buf.is_empty() {
168 let _ = write!(self.result, "{}{}", self.temp_buf.len(), self.temp_buf);
169 self.temp_buf.clear();
170 }
171 }
172
173 fn finish(mut self, hash: u64) -> String {
174 self.finalize_pending_component();
175 // E = end name-sequence
176 let _ = write!(self.result, "17h{:016x}E", hash);
177 self.result
178 }
179 }
180
181 struct SymbolPrinter<'tcx> {
182 tcx: TyCtxt<'tcx>,
183 path: SymbolPath,
184
185 // When `true`, `finalize_pending_component` isn't used.
186 // This is needed when recursing into `path_qualified`,
187 // or `path_generic_args`, as any nested paths are
188 // logically within one component.
189 keep_within_component: bool,
190 }
191
192 // HACK(eddyb) this relies on using the `fmt` interface to get
193 // `PrettyPrinter` aka pretty printing of e.g. types in paths,
194 // symbol names should have their own printing machinery.
195
196 impl Printer<'tcx> for SymbolPrinter<'tcx> {
197 type Error = fmt::Error;
198
199 type Path = Self;
200 type Region = Self;
201 type Type = Self;
202 type DynExistential = Self;
203 type Const = Self;
204
205 fn tcx(&self) -> TyCtxt<'tcx> {
206 self.tcx
207 }
208
209 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
210 Ok(self)
211 }
212
213 fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
214 match ty.kind {
215 // Print all nominal types as paths (unlike `pretty_print_type`).
216 ty::FnDef(def_id, substs)
217 | ty::Opaque(def_id, substs)
218 | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs })
219 | ty::UnnormalizedProjection(ty::ProjectionTy { item_def_id: def_id, substs })
220 | ty::Closure(def_id, substs)
221 | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs),
222 _ => self.pretty_print_type(ty),
223 }
224 }
225
226 fn print_dyn_existential(
227 mut self,
228 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
229 ) -> Result<Self::DynExistential, Self::Error> {
230 let mut first = true;
231 for p in predicates {
232 if !first {
233 write!(self, "+")?;
234 }
235 first = false;
236 self = p.print(self)?;
237 }
238 Ok(self)
239 }
240
241 fn print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
242 // only print integers
243 if let ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { .. })) = ct.val {
244 if ct.ty.is_integral() {
245 return self.pretty_print_const(ct, true);
246 }
247 }
248 self.write_str("_")?;
249 Ok(self)
250 }
251
252 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
253 self.write_str(&self.tcx.original_crate_name(cnum).as_str())?;
254 Ok(self)
255 }
256 fn path_qualified(
257 self,
258 self_ty: Ty<'tcx>,
259 trait_ref: Option<ty::TraitRef<'tcx>>,
260 ) -> Result<Self::Path, Self::Error> {
261 // Similar to `pretty_path_qualified`, but for the other
262 // types that are printed as paths (see `print_type` above).
263 match self_ty.kind {
264 ty::FnDef(..)
265 | ty::Opaque(..)
266 | ty::Projection(_)
267 | ty::UnnormalizedProjection(_)
268 | ty::Closure(..)
269 | ty::Generator(..)
270 if trait_ref.is_none() =>
271 {
272 self.print_type(self_ty)
273 }
274
275 _ => self.pretty_path_qualified(self_ty, trait_ref),
276 }
277 }
278
279 fn path_append_impl(
280 self,
281 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
282 _disambiguated_data: &DisambiguatedDefPathData,
283 self_ty: Ty<'tcx>,
284 trait_ref: Option<ty::TraitRef<'tcx>>,
285 ) -> Result<Self::Path, Self::Error> {
286 self.pretty_path_append_impl(
287 |mut cx| {
288 cx = print_prefix(cx)?;
289
290 if cx.keep_within_component {
291 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
292 cx.write_str("::")?;
293 } else {
294 cx.path.finalize_pending_component();
295 }
296
297 Ok(cx)
298 },
299 self_ty,
300 trait_ref,
301 )
302 }
303 fn path_append(
304 mut self,
305 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
306 disambiguated_data: &DisambiguatedDefPathData,
307 ) -> Result<Self::Path, Self::Error> {
308 self = print_prefix(self)?;
309
310 // Skip `::{{constructor}}` on tuple/unit structs.
311 if let DefPathData::Ctor = disambiguated_data.data {
312 return Ok(self);
313 }
314
315 if self.keep_within_component {
316 // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it.
317 self.write_str("::")?;
318 } else {
319 self.path.finalize_pending_component();
320 }
321
322 self.write_str(&disambiguated_data.data.as_symbol().as_str())?;
323 Ok(self)
324 }
325 fn path_generic_args(
326 mut self,
327 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
328 args: &[GenericArg<'tcx>],
329 ) -> Result<Self::Path, Self::Error> {
330 self = print_prefix(self)?;
331
332 let args = args.iter().cloned().filter(|arg| match arg.unpack() {
333 GenericArgKind::Lifetime(_) => false,
334 _ => true,
335 });
336
337 if args.clone().next().is_some() {
338 self.generic_delimiters(|cx| cx.comma_sep(args))
339 } else {
340 Ok(self)
341 }
342 }
343 }
344
345 impl PrettyPrinter<'tcx> for SymbolPrinter<'tcx> {
346 fn region_should_not_be_omitted(&self, _region: ty::Region<'_>) -> bool {
347 false
348 }
349 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
350 where
351 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
352 {
353 if let Some(first) = elems.next() {
354 self = first.print(self)?;
355 for elem in elems {
356 self.write_str(",")?;
357 self = elem.print(self)?;
358 }
359 }
360 Ok(self)
361 }
362
363 fn generic_delimiters(
364 mut self,
365 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
366 ) -> Result<Self, Self::Error> {
367 write!(self, "<")?;
368
369 let kept_within_component = mem::replace(&mut self.keep_within_component, true);
370 self = f(self)?;
371 self.keep_within_component = kept_within_component;
372
373 write!(self, ">")?;
374
375 Ok(self)
376 }
377 }
378
379 impl fmt::Write for SymbolPrinter<'_> {
380 fn write_str(&mut self, s: &str) -> fmt::Result {
381 // Name sanitation. LLVM will happily accept identifiers with weird names, but
382 // gas doesn't!
383 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
384 // NVPTX assembly has more strict naming rules than gas, so additionally, dots
385 // are replaced with '$' there.
386
387 for c in s.chars() {
388 if self.path.temp_buf.is_empty() {
389 match c {
390 'a'..='z' | 'A'..='Z' | '_' => {}
391 _ => {
392 // Underscore-qualify anything that didn't start as an ident.
393 self.path.temp_buf.push('_');
394 }
395 }
396 }
397 match c {
398 // Escape these with $ sequences
399 '@' => self.path.temp_buf.push_str("$SP$"),
400 '*' => self.path.temp_buf.push_str("$BP$"),
401 '&' => self.path.temp_buf.push_str("$RF$"),
402 '<' => self.path.temp_buf.push_str("$LT$"),
403 '>' => self.path.temp_buf.push_str("$GT$"),
404 '(' => self.path.temp_buf.push_str("$LP$"),
405 ')' => self.path.temp_buf.push_str("$RP$"),
406 ',' => self.path.temp_buf.push_str("$C$"),
407
408 '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => {
409 // NVPTX doesn't support these characters in symbol names.
410 self.path.temp_buf.push('$')
411 }
412
413 // '.' doesn't occur in types and functions, so reuse it
414 // for ':' and '-'
415 '-' | ':' => self.path.temp_buf.push('.'),
416
417 // Avoid crashing LLVM in certain (LTO-related) situations, see #60925.
418 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"),
419
420 // These are legal symbols
421 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),
422
423 _ => {
424 self.path.temp_buf.push('$');
425 for c in c.escape_unicode().skip(1) {
426 match c {
427 '{' => {}
428 '}' => self.path.temp_buf.push('$'),
429 c => self.path.temp_buf.push(c),
430 }
431 }
432 }
433 }
434 }
435
436 Ok(())
437 }
438 }