1use std::collections::hash_map::Entry::*;
2
3use rustc_abi::{CanonAbi, X86Call};
4use rustc_ast::expand::allocator::{AllocatorKind, NO_ALLOC_SHIM_IS_UNSTABLE, global_fn_name};
5use rustc_data_structures::unord::UnordMap;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE, LocalDefId};
8use rustc_middle::bug;
9use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
10use rustc_middle::middle::exported_symbols::{
11 ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
12};
13use rustc_middle::query::LocalCrate;
14use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, Instance, SymbolName, Ty, TyCtxt};
15use rustc_middle::util::Providers;
16use rustc_session::config::CrateType;
17use rustc_span::Span;
18use rustc_symbol_mangling::mangle_internal_symbol;
19use rustc_target::spec::{Arch, Os, TlsModel};
20use tracing::debug;
21
22use crate::back::symbol_export;
23use crate::base::allocator_shim_contents;
24
25fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
26 crates_export_threshold(tcx.crate_types())
27}
28
29fn crate_export_threshold(crate_type: CrateType) -> SymbolExportLevel {
30 match crate_type {
31 CrateType::Executable | CrateType::StaticLib | CrateType::ProcMacro | CrateType::Cdylib => {
32 SymbolExportLevel::C
33 }
34 CrateType::Rlib | CrateType::Dylib | CrateType::Sdylib => SymbolExportLevel::Rust,
35 }
36}
37
38pub fn crates_export_threshold(crate_types: &[CrateType]) -> SymbolExportLevel {
39 if crate_types
40 .iter()
41 .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
42 {
43 SymbolExportLevel::Rust
44 } else {
45 SymbolExportLevel::C
46 }
47}
48
49fn reachable_non_generics_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> DefIdMap<SymbolExportInfo> {
50 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
51 return Default::default();
52 }
53
54 let is_compiler_builtins = tcx.is_compiler_builtins(LOCAL_CRATE);
55
56 let mut reachable_non_generics: DefIdMap<_> = tcx
57 .reachable_set(())
58 .items()
59 .filter_map(|&def_id| {
60 if let Some(parent_id) = tcx.opt_local_parent(def_id)
74 && let DefKind::ForeignMod = tcx.def_kind(parent_id)
75 {
76 let library = tcx.native_library(def_id)?;
77 return library.kind.is_statically_included().then_some(def_id);
78 }
79
80 match tcx.def_kind(def_id) {
82 DefKind::Fn | DefKind::Static { .. } => {}
83 DefKind::AssocFn if tcx.impl_of_assoc(def_id.to_def_id()).is_some() => {}
84 _ => return None,
85 };
86
87 let generics = tcx.generics_of(def_id);
88 if generics.requires_monomorphization(tcx) {
89 return None;
90 }
91
92 if Instance::mono(tcx, def_id.into()).def.requires_inline(tcx) {
93 return None;
94 }
95
96 if tcx.cross_crate_inlinable(def_id) { None } else { Some(def_id) }
97 })
98 .map(|def_id| {
99 let export_level = if is_compiler_builtins {
100 SymbolExportLevel::Rust
106 } else {
107 symbol_export_level(tcx, def_id.to_def_id())
108 };
109 let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
110 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/symbol_export.rs:110",
"rustc_codegen_ssa::back::symbol_export",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/symbol_export.rs"),
::tracing_core::__macro_support::Option::Some(110u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::symbol_export"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("EXPORTED SYMBOL (local): {0} ({1:?})",
tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
export_level) as &dyn Value))])
});
} else { ; }
};debug!(
111 "EXPORTED SYMBOL (local): {} ({:?})",
112 tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
113 export_level
114 );
115 let info = SymbolExportInfo {
116 level: export_level,
117 kind: if tcx.is_static(def_id.to_def_id()) {
118 if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
119 SymbolExportKind::Tls
120 } else {
121 SymbolExportKind::Data
122 }
123 } else {
124 SymbolExportKind::Text
125 },
126 used: codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
127 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER),
128 rustc_std_internal_symbol: codegen_attrs
129 .flags
130 .contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
131 || codegen_attrs
132 .flags
133 .contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM),
134 };
135 (def_id.to_def_id(), info)
136 })
137 .into();
138
139 if let Some(id) = tcx.proc_macro_decls_static(()) {
140 reachable_non_generics.insert(
141 id.to_def_id(),
142 SymbolExportInfo {
143 level: SymbolExportLevel::C,
144 kind: SymbolExportKind::Data,
145 used: false,
146 rustc_std_internal_symbol: false,
147 },
148 );
149 }
150
151 reachable_non_generics
152}
153
154fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
155 let export_threshold = threshold(tcx);
156
157 if let Some(&info) = tcx.reachable_non_generics(LOCAL_CRATE).get(&def_id.to_def_id()) {
158 info.level.is_below_threshold(export_threshold)
159 } else {
160 false
161 }
162}
163
164fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
165 tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
166}
167
168fn exported_non_generic_symbols_provider_local<'tcx>(
169 tcx: TyCtxt<'tcx>,
170 _: LocalCrate,
171) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
172 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
173 return &[];
174 }
175
176 let sorted = tcx.with_stable_hashing_context(|hcx| {
179 tcx.reachable_non_generics(LOCAL_CRATE).to_sorted(&hcx, true)
180 });
181
182 let mut symbols: Vec<_> =
183 sorted.iter().map(|&(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect();
184
185 if !tcx.sess.target.dll_tls_export {
187 symbols.extend(sorted.iter().filter_map(|&(&def_id, &info)| {
188 tcx.needs_thread_local_shim(def_id).then(|| {
189 (
190 ExportedSymbol::ThreadLocalShim(def_id),
191 SymbolExportInfo {
192 level: info.level,
193 kind: SymbolExportKind::Text,
194 used: info.used,
195 rustc_std_internal_symbol: info.rustc_std_internal_symbol,
196 },
197 )
198 })
199 }))
200 }
201
202 if tcx.entry_fn(()).is_some() {
203 let exported_symbol =
204 ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
205
206 symbols.push((
207 exported_symbol,
208 SymbolExportInfo {
209 level: SymbolExportLevel::C,
210 kind: SymbolExportKind::Text,
211 used: false,
212 rustc_std_internal_symbol: false,
213 },
214 ));
215 }
216
217 symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
219
220 tcx.arena.alloc_from_iter(symbols)
221}
222
223fn exported_generic_symbols_provider_local<'tcx>(
224 tcx: TyCtxt<'tcx>,
225 _: LocalCrate,
226) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
227 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
228 return &[];
229 }
230
231 let mut symbols: Vec<_> = ::alloc::vec::Vec::new()vec![];
232
233 if tcx.local_crate_exports_generics() {
234 use rustc_hir::attrs::Linkage;
235 use rustc_middle::mir::mono::{MonoItem, Visibility};
236 use rustc_middle::ty::InstanceKind;
237
238 let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
244
245 let cgus = tcx.collect_and_partition_mono_items(()).codegen_units;
246
247 let reachable_set = tcx.reachable_set(());
249 let is_local_to_current_crate = |ty: Ty<'_>| {
250 let no_refs = ty.peel_refs();
251 let root_def_id = match no_refs.kind() {
252 ty::Closure(closure, _) => *closure,
253 ty::FnDef(def_id, _) => *def_id,
254 ty::Coroutine(def_id, _) => *def_id,
255 ty::CoroutineClosure(def_id, _) => *def_id,
256 ty::CoroutineWitness(def_id, _) => *def_id,
257 _ => return false,
258 };
259 let Some(root_def_id) = root_def_id.as_local() else {
260 return false;
261 };
262
263 let is_local = !reachable_set.contains(&root_def_id);
264 is_local
265 };
266
267 let is_instantiable_downstream =
268 |did: Option<DefId>, generic_args: GenericArgsRef<'tcx>| {
269 generic_args
270 .types()
271 .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder()))
272 .all(move |arg| {
273 arg.walk().all(|ty| {
274 ty.as_type().map_or(true, |ty| !is_local_to_current_crate(ty))
275 })
276 })
277 };
278
279 #[allow(rustc::potential_query_instability)]
281 for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
282 if data.linkage != Linkage::External {
283 continue;
286 }
287
288 if need_visibility && data.visibility == Visibility::Hidden {
289 continue;
292 }
293
294 if !tcx.sess.opts.share_generics() {
295 if tcx.codegen_fn_attrs(mono_item.def_id()).inline
296 == rustc_hir::attrs::InlineAttr::Never
297 {
298 } else {
301 continue;
302 }
303 }
304
305 match *mono_item {
308 MonoItem::Fn(Instance { def: InstanceKind::Item(def), args }) => {
309 let has_generics = args.non_erasable_generics().next().is_some();
310
311 let should_export =
312 has_generics && is_instantiable_downstream(Some(def), &args);
313
314 if should_export {
315 let symbol = ExportedSymbol::Generic(def, args);
316 symbols.push((
317 symbol,
318 SymbolExportInfo {
319 level: SymbolExportLevel::Rust,
320 kind: SymbolExportKind::Text,
321 used: false,
322 rustc_std_internal_symbol: false,
323 },
324 ));
325 }
326 }
327 MonoItem::Fn(Instance { def: InstanceKind::DropGlue(_, Some(ty)), args }) => {
328 match (&args.non_erasable_generics().next(), &Some(GenericArgKind::Type(ty)))
{
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
330
331 let should_export = match ty.kind() {
333 ty::Adt(_, args) => is_instantiable_downstream(None, args),
334 ty::Closure(_, args) => is_instantiable_downstream(None, args),
335 _ => true,
336 };
337
338 if should_export {
339 symbols.push((
340 ExportedSymbol::DropGlue(ty),
341 SymbolExportInfo {
342 level: SymbolExportLevel::Rust,
343 kind: SymbolExportKind::Text,
344 used: false,
345 rustc_std_internal_symbol: false,
346 },
347 ));
348 }
349 }
350 MonoItem::Fn(Instance {
351 def: InstanceKind::AsyncDropGlueCtorShim(_, ty),
352 args,
353 }) => {
354 match (&args.non_erasable_generics().next(), &Some(GenericArgKind::Type(ty)))
{
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
356 symbols.push((
357 ExportedSymbol::AsyncDropGlueCtorShim(ty),
358 SymbolExportInfo {
359 level: SymbolExportLevel::Rust,
360 kind: SymbolExportKind::Text,
361 used: false,
362 rustc_std_internal_symbol: false,
363 },
364 ));
365 }
366 MonoItem::Fn(Instance { def: InstanceKind::AsyncDropGlue(def, ty), args: _ }) => {
367 symbols.push((
368 ExportedSymbol::AsyncDropGlue(def, ty),
369 SymbolExportInfo {
370 level: SymbolExportLevel::Rust,
371 kind: SymbolExportKind::Text,
372 used: false,
373 rustc_std_internal_symbol: false,
374 },
375 ));
376 }
377 _ => {
378 }
380 }
381 }
382 }
383
384 symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
386
387 tcx.arena.alloc_from_iter(symbols)
388}
389
390fn upstream_monomorphizations_provider(
391 tcx: TyCtxt<'_>,
392 (): (),
393) -> DefIdMap<UnordMap<GenericArgsRef<'_>, CrateNum>> {
394 let cnums = tcx.crates(());
395
396 let mut instances: DefIdMap<UnordMap<_, _>> = Default::default();
397
398 let drop_in_place_fn_def_id = tcx.lang_items().drop_in_place_fn();
399 let async_drop_in_place_fn_def_id = tcx.lang_items().async_drop_in_place_fn();
400
401 for &cnum in cnums.iter() {
402 for (exported_symbol, _) in tcx.exported_generic_symbols(cnum).iter() {
403 let (def_id, args) = match *exported_symbol {
404 ExportedSymbol::Generic(def_id, args) => (def_id, args),
405 ExportedSymbol::DropGlue(ty) => {
406 if let Some(drop_in_place_fn_def_id) = drop_in_place_fn_def_id {
407 (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
408 } else {
409 continue;
412 }
413 }
414 ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
415 if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
416 (async_drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
417 } else {
418 continue;
419 }
420 }
421 ExportedSymbol::AsyncDropGlue(def_id, ty) => (def_id, tcx.mk_args(&[ty.into()])),
422 ExportedSymbol::NonGeneric(..)
423 | ExportedSymbol::ThreadLocalShim(..)
424 | ExportedSymbol::NoDefId(..) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{0:?}", exported_symbol)));
}unreachable!("{exported_symbol:?}"),
425 };
426
427 let args_map = instances.entry(def_id).or_default();
428
429 match args_map.entry(args) {
430 Occupied(mut e) => {
431 let other_cnum = *e.get();
434 if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
435 e.insert(cnum);
436 }
437 }
438 Vacant(e) => {
439 e.insert(cnum);
440 }
441 }
442 }
443 }
444
445 instances
446}
447
448fn upstream_monomorphizations_for_provider(
449 tcx: TyCtxt<'_>,
450 def_id: DefId,
451) -> Option<&UnordMap<GenericArgsRef<'_>, CrateNum>> {
452 if !!def_id.is_local() {
::core::panicking::panic("assertion failed: !def_id.is_local()")
};assert!(!def_id.is_local());
453 tcx.upstream_monomorphizations(()).get(&def_id)
454}
455
456fn upstream_drop_glue_for_provider<'tcx>(
457 tcx: TyCtxt<'tcx>,
458 args: GenericArgsRef<'tcx>,
459) -> Option<CrateNum> {
460 let def_id = tcx.lang_items().drop_in_place_fn()?;
461 tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
462}
463
464fn upstream_async_drop_glue_for_provider<'tcx>(
465 tcx: TyCtxt<'tcx>,
466 args: GenericArgsRef<'tcx>,
467) -> Option<CrateNum> {
468 let def_id = tcx.lang_items().async_drop_in_place_fn()?;
469 tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
470}
471
472fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
473 !tcx.reachable_set(()).contains(&def_id)
474}
475
476pub(crate) fn provide(providers: &mut Providers) {
477 providers.queries.reachable_non_generics = reachable_non_generics_provider;
478 providers.queries.is_reachable_non_generic = is_reachable_non_generic_provider_local;
479 providers.queries.exported_non_generic_symbols = exported_non_generic_symbols_provider_local;
480 providers.queries.exported_generic_symbols = exported_generic_symbols_provider_local;
481 providers.queries.upstream_monomorphizations = upstream_monomorphizations_provider;
482 providers.queries.is_unreachable_local_definition = is_unreachable_local_definition_provider;
483 providers.queries.upstream_drop_glue_for = upstream_drop_glue_for_provider;
484 providers.queries.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
485 providers.queries.wasm_import_module_map = wasm_import_module_map;
486 providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
487 providers.extern_queries.upstream_monomorphizations_for =
488 upstream_monomorphizations_for_provider;
489}
490
491pub(crate) fn allocator_shim_symbols(
492 tcx: TyCtxt<'_>,
493 kind: AllocatorKind,
494) -> impl Iterator<Item = (String, SymbolExportKind)> {
495 allocator_shim_contents(tcx, kind)
496 .into_iter()
497 .map(move |method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
498 .chain([mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE)])
499 .map(move |symbol_name| {
500 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
501
502 (
503 symbol_export::exporting_symbol_name_for_instance_in_crate(
504 tcx,
505 exported_symbol,
506 LOCAL_CRATE,
507 ),
508 SymbolExportKind::Text,
509 )
510 })
511}
512
513fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
514 let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
520 let is_extern = codegen_fn_attrs.contains_extern_indicator();
521 let std_internal =
522 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
523 let eii = codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
524
525 if is_extern && !std_internal && !eii {
526 let target = &tcx.sess.target.llvm_target;
527 if target.contains("emscripten") {
530 if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
531 return SymbolExportLevel::Rust;
532 }
533 }
534
535 SymbolExportLevel::C
536 } else {
537 SymbolExportLevel::Rust
538 }
539}
540
541pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
543 tcx: TyCtxt<'tcx>,
544 symbol: ExportedSymbol<'tcx>,
545 instantiating_crate: CrateNum,
546) -> String {
547 if instantiating_crate == LOCAL_CRATE {
550 return symbol.symbol_name_for_local_instance(tcx).to_string();
551 }
552
553 match symbol {
556 ExportedSymbol::NonGeneric(def_id) => {
557 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
558 tcx,
559 Instance::mono(tcx, def_id),
560 instantiating_crate,
561 )
562 }
563 ExportedSymbol::Generic(def_id, args) => {
564 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
565 tcx,
566 Instance::new_raw(def_id, args),
567 instantiating_crate,
568 )
569 }
570 ExportedSymbol::ThreadLocalShim(def_id) => {
571 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
572 tcx,
573 ty::Instance {
574 def: ty::InstanceKind::ThreadLocalShim(def_id),
575 args: ty::GenericArgs::empty(),
576 },
577 instantiating_crate,
578 )
579 }
580 ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
581 tcx,
582 Instance::resolve_drop_in_place(tcx, ty),
583 instantiating_crate,
584 ),
585 ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
586 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
587 tcx,
588 Instance::resolve_async_drop_in_place(tcx, ty),
589 instantiating_crate,
590 )
591 }
592 ExportedSymbol::AsyncDropGlue(def_id, ty) => {
593 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
594 tcx,
595 Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
596 instantiating_crate,
597 )
598 }
599 ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
600 }
601}
602
603fn calling_convention_for_symbol<'tcx>(
604 tcx: TyCtxt<'tcx>,
605 symbol: ExportedSymbol<'tcx>,
606) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
607 let instance = match symbol {
608 ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
609 if tcx.is_static(def_id) =>
610 {
611 None
612 }
613 ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
614 ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
615 ExportedSymbol::DropGlue(..) => None,
618 ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
621 ExportedSymbol::AsyncDropGlue(..) => None,
622 ExportedSymbol::NoDefId(..) => None,
624 ExportedSymbol::ThreadLocalShim(..) => None,
626 };
627
628 instance
629 .map(|i| {
630 tcx.fn_abi_of_instance(
631 ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
632 )
633 .unwrap_or_else(|_| ::rustc_middle::util::bug::bug_fmt(format_args!("fn_abi_of_instance({0:?}) failed",
i))bug!("fn_abi_of_instance({i:?}) failed"))
634 })
635 .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
636 .unwrap_or((CanonAbi::Rust, &[]))
638}
639
640pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
644 tcx: TyCtxt<'tcx>,
645 symbol: ExportedSymbol<'tcx>,
646 export_kind: SymbolExportKind,
647 instantiating_crate: CrateNum,
648) -> String {
649 let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
650
651 if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
654 return name;
655 }
656
657 let target = &tcx.sess.target;
658 if !target.is_like_windows {
659 return undecorated;
662 }
663
664 let prefix = match target.arch {
665 Arch::X86 => Some('_'),
666 Arch::X86_64 => None,
667 Arch::Arm64EC if export_kind == SymbolExportKind::Text => Some('#'),
669 _ => return undecorated,
671 };
672
673 let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
674
675 let (prefix, suffix) = match callconv {
678 CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
679 CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
680 CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
681 _ => {
682 if let Some(prefix) = prefix {
683 undecorated.insert(0, prefix);
684 }
685 return undecorated;
686 }
687 };
688
689 let args_in_bytes: u64 = args
690 .iter()
691 .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
692 .sum();
693 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{2}{3}", prefix, undecorated,
suffix, args_in_bytes))
})format!("{prefix}{undecorated}{suffix}{args_in_bytes}")
694}
695
696pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
697 tcx: TyCtxt<'tcx>,
698 symbol: ExportedSymbol<'tcx>,
699 cnum: CrateNum,
700) -> String {
701 let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
702 maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
703}
704
705pub(crate) fn extend_exported_symbols<'tcx>(
709 symbols: &mut Vec<(String, SymbolExportKind)>,
710 tcx: TyCtxt<'tcx>,
711 symbol: ExportedSymbol<'tcx>,
712 instantiating_crate: CrateNum,
713) {
714 let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
715
716 if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != Os::AmdHsa {
717 return;
718 }
719
720 let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
721
722 symbols.push((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.kd", undecorated))
})format!("{undecorated}.kd"), SymbolExportKind::Data));
726}
727
728fn maybe_emutls_symbol_name<'tcx>(
729 tcx: TyCtxt<'tcx>,
730 symbol: ExportedSymbol<'tcx>,
731 undecorated: &str,
732) -> Option<String> {
733 if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.tls_model() {
TlsModel::Emulated => true,
_ => false,
}matches!(tcx.sess.tls_model(), TlsModel::Emulated)
734 && let ExportedSymbol::NonGeneric(def_id) = symbol
735 && tcx.is_thread_local_static(def_id)
736 {
737 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("__emutls_v.{0}", undecorated))
})format!("__emutls_v.{undecorated}"))
740 } else {
741 None
742 }
743}
744
745fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
746 let native_libs = tcx.native_libraries(cnum);
750
751 let def_id_to_native_lib = native_libs
752 .iter()
753 .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
754 .collect::<DefIdMap<_>>();
755
756 let mut ret = DefIdMap::default();
757 for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
758 let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
759 let Some(module) = module else { continue };
760 ret.extend(lib.foreign_items.iter().map(|id| {
761 match (&id.krate, &cnum) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(id.krate, cnum);
762 (*id, module.to_string())
763 }));
764 }
765
766 ret
767}
768
769pub fn escape_symbol_name(tcx: TyCtxt<'_>, symbol: &str, span: Span) -> String {
770 use rustc_target::spec::{Arch, BinaryFormat};
772 if !symbol.is_empty()
773 && symbol.chars().all(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
'0'..='9' | 'A'..='Z' | 'a'..='z' | '_' | '$' | '.' => true,
_ => false,
}matches!(c, '0'..='9' | 'A'..='Z' | 'a'..='z' | '_' | '$' | '.'))
774 {
775 return symbol.to_string();
776 }
777 if tcx.sess.target.binary_format == BinaryFormat::Xcoff {
778 tcx.sess.dcx().span_fatal(
779 span,
780 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("symbol escaping is not supported for the binary format {0}",
tcx.sess.target.binary_format))
})format!(
781 "symbol escaping is not supported for the binary format {}",
782 tcx.sess.target.binary_format
783 ),
784 );
785 }
786 if tcx.sess.target.arch == Arch::Nvptx64 {
787 tcx.sess.dcx().span_fatal(
788 span,
789 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("symbol escaping is not supported for the architecture {0}",
tcx.sess.target.arch))
})format!(
790 "symbol escaping is not supported for the architecture {}",
791 tcx.sess.target.arch
792 ),
793 );
794 }
795 let mut escaped_symbol = String::new();
796 escaped_symbol.push('\"');
797 for c in symbol.chars() {
798 match c {
799 '\n' => escaped_symbol.push_str("\\\n"),
800 '"' => escaped_symbol.push_str("\\\""),
801 '\\' => escaped_symbol.push_str("\\\\"),
802 c => escaped_symbol.push(c),
803 }
804 }
805 escaped_symbol.push('\"');
806 escaped_symbol
807}