]>
Commit | Line | Data |
---|---|---|
dc9dc135 | 1 | use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; |
dfeec247 | 2 | use rustc_hir::def_id::CrateNum; |
ba9703b0 | 3 | use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; |
ba9703b0 XL |
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; | |
dc9dc135 | 9 | |
3dfed10e | 10 | use tracing::debug; |
dc9dc135 XL |
11 | |
12 | use std::fmt::{self, Write}; | |
13 | use std::mem::{self, discriminant}; | |
14 | ||
a2a8927a | 15 | pub(super) fn mangle<'tcx>( |
dc9dc135 XL |
16 | tcx: TyCtxt<'tcx>, |
17 | instance: Instance<'tcx>, | |
18 | instantiating_crate: Option<CrateNum>, | |
19 | ) -> String { | |
20 | let def_id = instance.def_id(); | |
21 | ||
22 | // We want to compute the "type" of this item. Unfortunately, some | |
23 | // kinds of items (e.g., closures) don't have an entry in the | |
24 | // item-type array. So walk back up the find the closest parent | |
25 | // that DOES have an entry. | |
26 | let mut ty_def_id = def_id; | |
27 | let instance_ty; | |
28 | loop { | |
29 | let key = tcx.def_key(ty_def_id); | |
30 | match key.disambiguated_data.data { | |
31 | DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => { | |
32 | instance_ty = tcx.type_of(ty_def_id); | |
33 | break; | |
34 | } | |
35 | _ => { | |
36 | // if we're making a symbol for something, there ought | |
37 | // to be a value or type-def or something in there | |
38 | // *somewhere* | |
39 | ty_def_id.index = key.parent.unwrap_or_else(|| { | |
40 | bug!( | |
41 | "finding type for {:?}, encountered def-id {:?} with no \ | |
42 | parent", | |
43 | def_id, | |
44 | ty_def_id | |
45 | ); | |
46 | }); | |
47 | } | |
48 | } | |
49 | } | |
50 | ||
51 | // Erase regions because they may not be deterministic when hashed | |
52 | // and should not matter anyhow. | |
fc512014 | 53 | let instance_ty = tcx.erase_regions(instance_ty); |
dc9dc135 XL |
54 | |
55 | let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate); | |
56 | ||
94222f64 XL |
57 | let mut printer = SymbolPrinter { tcx, path: SymbolPath::new(), keep_within_component: false }; |
58 | printer | |
5869c6ff XL |
59 | .print_def_path( |
60 | def_id, | |
61 | if let ty::InstanceDef::DropGlue(_, _) = instance.def { | |
62 | // Add the name of the dropped type to the symbol name | |
63 | &*instance.substs | |
64 | } else { | |
65 | &[] | |
66 | }, | |
67 | ) | |
dfeec247 | 68 | .unwrap(); |
dc9dc135 | 69 | |
ba9703b0 | 70 | if let ty::InstanceDef::VtableShim(..) = instance.def { |
dc9dc135 XL |
71 | let _ = printer.write_str("{{vtable-shim}}"); |
72 | } | |
73 | ||
ba9703b0 XL |
74 | if let ty::InstanceDef::ReifyShim(..) = instance.def { |
75 | let _ = printer.write_str("{{reify-shim}}"); | |
76 | } | |
77 | ||
dc9dc135 XL |
78 | printer.path.finish(hash) |
79 | } | |
80 | ||
81 | fn get_symbol_hash<'tcx>( | |
82 | tcx: TyCtxt<'tcx>, | |
83 | ||
84 | // instance this name will be for | |
85 | instance: Instance<'tcx>, | |
86 | ||
87 | // type of the item, without any generic | |
88 | // parameters substituted; this is | |
89 | // included in the hash as a kind of | |
90 | // safeguard. | |
91 | item_type: Ty<'tcx>, | |
92 | ||
93 | instantiating_crate: Option<CrateNum>, | |
94 | ) -> u64 { | |
95 | let def_id = instance.def_id(); | |
96 | let substs = instance.substs; | |
dfeec247 | 97 | debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs); |
dc9dc135 | 98 | |
e74abb32 | 99 | let mut hasher = StableHasher::new(); |
dc9dc135 XL |
100 | let mut hcx = tcx.create_stable_hashing_context(); |
101 | ||
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 | |
105 | // truly unique path | |
106 | tcx.def_path_hash(def_id).hash_stable(&mut hcx, &mut hasher); | |
107 | ||
108 | // Include the main item-type. Note that, in this case, the | |
5099ac24 | 109 | // assertions about `needs_subst` may not hold, but this item-type |
dc9dc135 | 110 | // ought to be the same for every reference anyway. |
5099ac24 | 111 | assert!(!item_type.has_erasable_regions()); |
dc9dc135 | 112 | hcx.while_hashing_spans(false, |hcx| { |
5e7ed085 | 113 | item_type.hash_stable(hcx, &mut hasher); |
5099ac24 | 114 | |
5e7ed085 FG |
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); | |
120 | } | |
5099ac24 | 121 | |
5e7ed085 FG |
122 | // also include any type parameters (for generic items) |
123 | substs.hash_stable(hcx, &mut hasher); | |
124 | ||
125 | if let Some(instantiating_crate) = instantiating_crate { | |
126 | tcx.def_path_hash(instantiating_crate.as_def_id()) | |
127 | .stable_crate_id() | |
128 | .hash_stable(hcx, &mut hasher); | |
129 | } | |
5099ac24 | 130 | |
5e7ed085 FG |
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); | |
dc9dc135 | 135 | }); |
dc9dc135 XL |
136 | }); |
137 | ||
138 | // 64 bits should be enough to avoid collisions. | |
e74abb32 | 139 | hasher.finish::<u64>() |
dc9dc135 XL |
140 | } |
141 | ||
142 | // Follow C++ namespace-mangling style, see | |
3dfed10e | 143 | // https://en.wikipedia.org/wiki/Name_mangling for more info. |
dc9dc135 XL |
144 | // |
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. | |
152 | // | |
153 | // To be able to work on all platforms and get *some* reasonable output, we | |
154 | // use C++ name-mangling. | |
155 | #[derive(Debug)] | |
156 | struct SymbolPath { | |
157 | result: String, | |
158 | temp_buf: String, | |
159 | } | |
160 | ||
161 | impl SymbolPath { | |
162 | fn new() -> Self { | |
dfeec247 XL |
163 | let mut result = |
164 | SymbolPath { result: String::with_capacity(64), temp_buf: String::with_capacity(16) }; | |
dc9dc135 XL |
165 | result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested |
166 | result | |
167 | } | |
168 | ||
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(); | |
173 | } | |
174 | } | |
175 | ||
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); | |
180 | self.result | |
181 | } | |
182 | } | |
183 | ||
184 | struct SymbolPrinter<'tcx> { | |
185 | tcx: TyCtxt<'tcx>, | |
186 | path: SymbolPath, | |
187 | ||
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, | |
193 | } | |
194 | ||
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. | |
198 | ||
a2a8927a | 199 | impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { |
dc9dc135 XL |
200 | type Error = fmt::Error; |
201 | ||
202 | type Path = Self; | |
203 | type Region = Self; | |
204 | type Type = Self; | |
205 | type DynExistential = Self; | |
206 | type Const = Self; | |
207 | ||
208 | fn tcx(&self) -> TyCtxt<'tcx> { | |
209 | self.tcx | |
210 | } | |
211 | ||
dfeec247 | 212 | fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> { |
dc9dc135 XL |
213 | Ok(self) |
214 | } | |
215 | ||
5e7ed085 | 216 | fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> { |
1b1a35ee | 217 | match *ty.kind() { |
dc9dc135 | 218 | // Print all nominal types as paths (unlike `pretty_print_type`). |
dfeec247 XL |
219 | ty::FnDef(def_id, substs) |
220 | | ty::Opaque(def_id, substs) | |
221 | | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs }) | |
dfeec247 XL |
222 | | ty::Closure(def_id, substs) |
223 | | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs), | |
5e7ed085 FG |
224 | |
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.val().try_to_bits(self.tcx().data_layout.pointer_size) { | |
232 | write!(self, "{}", size)? | |
233 | } else if let ty::ConstKind::Param(param) = size.val() { | |
234 | self = param.print(self)? | |
235 | } else { | |
236 | self.write_str("_")? | |
237 | } | |
238 | self.write_str("]")?; | |
239 | Ok(self) | |
240 | } | |
241 | ||
dc9dc135 XL |
242 | _ => self.pretty_print_type(ty), |
243 | } | |
244 | } | |
245 | ||
246 | fn print_dyn_existential( | |
247 | mut self, | |
cdc7bbd5 | 248 | predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>, |
dc9dc135 XL |
249 | ) -> Result<Self::DynExistential, Self::Error> { |
250 | let mut first = true; | |
251 | for p in predicates { | |
252 | if !first { | |
253 | write!(self, "+")?; | |
254 | } | |
255 | first = false; | |
256 | self = p.print(self)?; | |
257 | } | |
258 | Ok(self) | |
259 | } | |
260 | ||
5099ac24 | 261 | fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> { |
dc9dc135 | 262 | // only print integers |
5e7ed085 FG |
263 | match (ct.val(), ct.ty().kind()) { |
264 | ( | |
265 | ty::ConstKind::Value(ConstValue::Scalar(Scalar::Int(scalar))), | |
266 | ty::Int(_) | ty::Uint(_), | |
267 | ) => { | |
268 | // The `pretty_print_const` formatting depends on -Zverbose | |
269 | // flag, so we cannot reuse it here. | |
270 | let signed = matches!(ct.ty().kind(), ty::Int(_)); | |
271 | write!( | |
272 | self, | |
273 | "{:#?}", | |
274 | ty::ConstInt::new(scalar, signed, ct.ty().is_ptr_sized_integral()) | |
275 | )?; | |
dc9dc135 | 276 | } |
5e7ed085 | 277 | _ => self.write_str("_")?, |
dc9dc135 | 278 | } |
dc9dc135 XL |
279 | Ok(self) |
280 | } | |
281 | ||
94222f64 | 282 | fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> { |
a2a8927a | 283 | self.write_str(self.tcx.crate_name(cnum).as_str())?; |
dc9dc135 XL |
284 | Ok(self) |
285 | } | |
286 | fn path_qualified( | |
287 | self, | |
288 | self_ty: Ty<'tcx>, | |
289 | trait_ref: Option<ty::TraitRef<'tcx>>, | |
290 | ) -> Result<Self::Path, Self::Error> { | |
291 | // Similar to `pretty_path_qualified`, but for the other | |
292 | // types that are printed as paths (see `print_type` above). | |
1b1a35ee | 293 | match self_ty.kind() { |
dfeec247 XL |
294 | ty::FnDef(..) |
295 | | ty::Opaque(..) | |
296 | | ty::Projection(_) | |
dfeec247 XL |
297 | | ty::Closure(..) |
298 | | ty::Generator(..) | |
dc9dc135 XL |
299 | if trait_ref.is_none() => |
300 | { | |
301 | self.print_type(self_ty) | |
302 | } | |
303 | ||
dfeec247 | 304 | _ => self.pretty_path_qualified(self_ty, trait_ref), |
dc9dc135 XL |
305 | } |
306 | } | |
307 | ||
308 | fn path_append_impl( | |
309 | self, | |
310 | print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>, | |
311 | _disambiguated_data: &DisambiguatedDefPathData, | |
312 | self_ty: Ty<'tcx>, | |
313 | trait_ref: Option<ty::TraitRef<'tcx>>, | |
314 | ) -> Result<Self::Path, Self::Error> { | |
315 | self.pretty_path_append_impl( | |
316 | |mut cx| { | |
317 | cx = print_prefix(cx)?; | |
318 | ||
319 | if cx.keep_within_component { | |
320 | // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it. | |
321 | cx.write_str("::")?; | |
322 | } else { | |
323 | cx.path.finalize_pending_component(); | |
324 | } | |
325 | ||
326 | Ok(cx) | |
327 | }, | |
328 | self_ty, | |
329 | trait_ref, | |
330 | ) | |
331 | } | |
332 | fn path_append( | |
333 | mut self, | |
334 | print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>, | |
335 | disambiguated_data: &DisambiguatedDefPathData, | |
336 | ) -> Result<Self::Path, Self::Error> { | |
337 | self = print_prefix(self)?; | |
338 | ||
a2a8927a XL |
339 | // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs. |
340 | if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data { | |
ba9703b0 | 341 | return Ok(self); |
dc9dc135 XL |
342 | } |
343 | ||
344 | if self.keep_within_component { | |
345 | // HACK(eddyb) print the path similarly to how `FmtPrinter` prints it. | |
346 | self.write_str("::")?; | |
347 | } else { | |
348 | self.path.finalize_pending_component(); | |
349 | } | |
350 | ||
1b1a35ee XL |
351 | write!(self, "{}", disambiguated_data.data)?; |
352 | ||
dc9dc135 XL |
353 | Ok(self) |
354 | } | |
355 | fn path_generic_args( | |
356 | mut self, | |
357 | print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>, | |
e74abb32 | 358 | args: &[GenericArg<'tcx>], |
dfeec247 | 359 | ) -> Result<Self::Path, Self::Error> { |
dc9dc135 XL |
360 | self = print_prefix(self)?; |
361 | ||
29967ef6 XL |
362 | let args = |
363 | args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_))); | |
dc9dc135 XL |
364 | |
365 | if args.clone().next().is_some() { | |
366 | self.generic_delimiters(|cx| cx.comma_sep(args)) | |
367 | } else { | |
368 | Ok(self) | |
369 | } | |
370 | } | |
371 | } | |
372 | ||
a2a8927a | 373 | impl<'tcx> PrettyPrinter<'tcx> for &mut SymbolPrinter<'tcx> { |
5e7ed085 | 374 | fn should_print_region(&self, _region: ty::Region<'_>) -> bool { |
dc9dc135 XL |
375 | false |
376 | } | |
377 | fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error> | |
378 | where | |
379 | T: Print<'tcx, Self, Output = Self, Error = Self::Error>, | |
380 | { | |
381 | if let Some(first) = elems.next() { | |
382 | self = first.print(self)?; | |
383 | for elem in elems { | |
384 | self.write_str(",")?; | |
385 | self = elem.print(self)?; | |
386 | } | |
387 | } | |
388 | Ok(self) | |
389 | } | |
390 | ||
391 | fn generic_delimiters( | |
392 | mut self, | |
393 | f: impl FnOnce(Self) -> Result<Self, Self::Error>, | |
394 | ) -> Result<Self, Self::Error> { | |
395 | write!(self, "<")?; | |
396 | ||
dfeec247 | 397 | let kept_within_component = mem::replace(&mut self.keep_within_component, true); |
dc9dc135 XL |
398 | self = f(self)?; |
399 | self.keep_within_component = kept_within_component; | |
400 | ||
401 | write!(self, ">")?; | |
402 | ||
403 | Ok(self) | |
404 | } | |
405 | } | |
406 | ||
407 | impl fmt::Write for SymbolPrinter<'_> { | |
408 | fn write_str(&mut self, s: &str) -> fmt::Result { | |
409 | // Name sanitation. LLVM will happily accept identifiers with weird names, but | |
410 | // gas doesn't! | |
411 | // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $ | |
412 | // NVPTX assembly has more strict naming rules than gas, so additionally, dots | |
413 | // are replaced with '$' there. | |
414 | ||
415 | for c in s.chars() { | |
416 | if self.path.temp_buf.is_empty() { | |
417 | match c { | |
418 | 'a'..='z' | 'A'..='Z' | '_' => {} | |
419 | _ => { | |
420 | // Underscore-qualify anything that didn't start as an ident. | |
421 | self.path.temp_buf.push('_'); | |
422 | } | |
423 | } | |
424 | } | |
425 | match c { | |
426 | // Escape these with $ sequences | |
427 | '@' => self.path.temp_buf.push_str("$SP$"), | |
428 | '*' => self.path.temp_buf.push_str("$BP$"), | |
429 | '&' => self.path.temp_buf.push_str("$RF$"), | |
430 | '<' => self.path.temp_buf.push_str("$LT$"), | |
431 | '>' => self.path.temp_buf.push_str("$GT$"), | |
432 | '(' => self.path.temp_buf.push_str("$LP$"), | |
433 | ')' => self.path.temp_buf.push_str("$RP$"), | |
434 | ',' => self.path.temp_buf.push_str("$C$"), | |
435 | ||
436 | '-' | ':' | '.' if self.tcx.has_strict_asm_symbol_naming() => { | |
437 | // NVPTX doesn't support these characters in symbol names. | |
438 | self.path.temp_buf.push('$') | |
439 | } | |
440 | ||
441 | // '.' doesn't occur in types and functions, so reuse it | |
442 | // for ':' and '-' | |
443 | '-' | ':' => self.path.temp_buf.push('.'), | |
444 | ||
445 | // Avoid crashing LLVM in certain (LTO-related) situations, see #60925. | |
446 | 'm' if self.path.temp_buf.ends_with(".llv") => self.path.temp_buf.push_str("$u6d$"), | |
447 | ||
448 | // These are legal symbols | |
449 | 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c), | |
450 | ||
451 | _ => { | |
452 | self.path.temp_buf.push('$'); | |
453 | for c in c.escape_unicode().skip(1) { | |
454 | match c { | |
455 | '{' => {} | |
456 | '}' => self.path.temp_buf.push('$'), | |
457 | c => self.path.temp_buf.push(c), | |
458 | } | |
459 | } | |
460 | } | |
461 | } | |
462 | } | |
463 | ||
464 | Ok(()) | |
465 | } | |
466 | } |