rustc_codegen_ssa/back/
symbol_export.rs

1use std::collections::hash_map::Entry::*;
2
3use rustc_abi::{CanonAbi, X86Call};
4use rustc_ast::expand::allocator::{
5    ALLOC_ERROR_HANDLER, ALLOCATOR_METHODS, NO_ALLOC_SHIM_IS_UNSTABLE, global_fn_name,
6};
7use rustc_data_structures::unord::UnordMap;
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE, LocalDefId};
10use rustc_middle::bug;
11use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
12use rustc_middle::middle::exported_symbols::{
13    ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
14};
15use rustc_middle::query::LocalCrate;
16use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, Instance, SymbolName, Ty, TyCtxt};
17use rustc_middle::util::Providers;
18use rustc_session::config::{CrateType, OomStrategy};
19use rustc_symbol_mangling::mangle_internal_symbol;
20use rustc_target::spec::{Arch, Os, TlsModel};
21use tracing::debug;
22
23use crate::back::symbol_export;
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            // We want to ignore some FFI functions that are not exposed from
61            // this crate. Reachable FFI functions can be lumped into two
62            // categories:
63            //
64            // 1. Those that are included statically via a static library
65            // 2. Those included otherwise (e.g., dynamically or via a framework)
66            //
67            // Although our LLVM module is not literally emitting code for the
68            // statically included symbols, it's an export of our library which
69            // needs to be passed on to the linker and encoded in the metadata.
70            //
71            // As a result, if this id is an FFI item (foreign item) then we only
72            // let it through if it's included statically.
73            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            // Only consider nodes that actually have exported symbols.
81            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                // We don't want to export compiler-builtins symbols from any
101                // dylibs, even rust dylibs. Unlike all other crates it gets
102                // duplicated in every linker invocation and it may otherwise
103                // unintentionally override definitions of these symbols by
104                // libgcc or compiler-rt for C code.
105                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            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            };
132            (def_id.to_def_id(), info)
133        })
134        .into();
135
136    if let Some(id) = tcx.proc_macro_decls_static(()) {
137        reachable_non_generics.insert(
138            id.to_def_id(),
139            SymbolExportInfo {
140                level: SymbolExportLevel::C,
141                kind: SymbolExportKind::Data,
142                used: false,
143                rustc_std_internal_symbol: false,
144            },
145        );
146    }
147
148    reachable_non_generics
149}
150
151fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
152    let export_threshold = threshold(tcx);
153
154    if let Some(&info) = tcx.reachable_non_generics(LOCAL_CRATE).get(&def_id.to_def_id()) {
155        info.level.is_below_threshold(export_threshold)
156    } else {
157        false
158    }
159}
160
161fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
162    tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
163}
164
165fn exported_non_generic_symbols_provider_local<'tcx>(
166    tcx: TyCtxt<'tcx>,
167    _: LocalCrate,
168) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
169    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
170        return &[];
171    }
172
173    // FIXME: Sorting this is unnecessary since we are sorting later anyway.
174    //        Can we skip the later sorting?
175    let sorted = tcx.with_stable_hashing_context(|hcx| {
176        tcx.reachable_non_generics(LOCAL_CRATE).to_sorted(&hcx, true)
177    });
178
179    let mut symbols: Vec<_> =
180        sorted.iter().map(|&(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect();
181
182    // Export TLS shims
183    if !tcx.sess.target.dll_tls_export {
184        symbols.extend(sorted.iter().filter_map(|&(&def_id, &info)| {
185            tcx.needs_thread_local_shim(def_id).then(|| {
186                (
187                    ExportedSymbol::ThreadLocalShim(def_id),
188                    SymbolExportInfo {
189                        level: info.level,
190                        kind: SymbolExportKind::Text,
191                        used: info.used,
192                        rustc_std_internal_symbol: info.rustc_std_internal_symbol,
193                    },
194                )
195            })
196        }))
197    }
198
199    if tcx.entry_fn(()).is_some() {
200        let exported_symbol =
201            ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
202
203        symbols.push((
204            exported_symbol,
205            SymbolExportInfo {
206                level: SymbolExportLevel::C,
207                kind: SymbolExportKind::Text,
208                used: false,
209                rustc_std_internal_symbol: false,
210            },
211        ));
212    }
213
214    // Sort so we get a stable incr. comp. hash.
215    symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
216
217    tcx.arena.alloc_from_iter(symbols)
218}
219
220fn exported_generic_symbols_provider_local<'tcx>(
221    tcx: TyCtxt<'tcx>,
222    _: LocalCrate,
223) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
224    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
225        return &[];
226    }
227
228    let mut symbols: Vec<_> = vec![];
229
230    if tcx.local_crate_exports_generics() {
231        use rustc_hir::attrs::Linkage;
232        use rustc_middle::mir::mono::{MonoItem, Visibility};
233        use rustc_middle::ty::InstanceKind;
234
235        // Normally, we require that shared monomorphizations are not hidden,
236        // because if we want to re-use a monomorphization from a Rust dylib, it
237        // needs to be exported.
238        // However, on platforms that don't allow for Rust dylibs, having
239        // external linkage is enough for monomorphization to be linked to.
240        let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
241
242        let cgus = tcx.collect_and_partition_mono_items(()).codegen_units;
243
244        // Do not export symbols that cannot be instantiated by downstream crates.
245        let reachable_set = tcx.reachable_set(());
246        let is_local_to_current_crate = |ty: Ty<'_>| {
247            let no_refs = ty.peel_refs();
248            let root_def_id = match no_refs.kind() {
249                ty::Closure(closure, _) => *closure,
250                ty::FnDef(def_id, _) => *def_id,
251                ty::Coroutine(def_id, _) => *def_id,
252                ty::CoroutineClosure(def_id, _) => *def_id,
253                ty::CoroutineWitness(def_id, _) => *def_id,
254                _ => return false,
255            };
256            let Some(root_def_id) = root_def_id.as_local() else {
257                return false;
258            };
259
260            let is_local = !reachable_set.contains(&root_def_id);
261            is_local
262        };
263
264        let is_instantiable_downstream =
265            |did: Option<DefId>, generic_args: GenericArgsRef<'tcx>| {
266                generic_args
267                    .types()
268                    .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder()))
269                    .all(move |arg| {
270                        arg.walk().all(|ty| {
271                            ty.as_type().map_or(true, |ty| !is_local_to_current_crate(ty))
272                        })
273                    })
274            };
275
276        // The symbols created in this loop are sorted below it
277        #[allow(rustc::potential_query_instability)]
278        for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
279            if data.linkage != Linkage::External {
280                // We can only re-use things with external linkage, otherwise
281                // we'll get a linker error
282                continue;
283            }
284
285            if need_visibility && data.visibility == Visibility::Hidden {
286                // If we potentially share things from Rust dylibs, they must
287                // not be hidden
288                continue;
289            }
290
291            if !tcx.sess.opts.share_generics() {
292                if tcx.codegen_fn_attrs(mono_item.def_id()).inline
293                    == rustc_hir::attrs::InlineAttr::Never
294                {
295                    // this is OK, we explicitly allow sharing inline(never) across crates even
296                    // without share-generics.
297                } else {
298                    continue;
299                }
300            }
301
302            // Note: These all set rustc_std_internal_symbol to false as generic functions must not
303            // be marked with this attribute and we are only handling generic functions here.
304            match *mono_item {
305                MonoItem::Fn(Instance { def: InstanceKind::Item(def), args }) => {
306                    let has_generics = args.non_erasable_generics().next().is_some();
307
308                    let should_export =
309                        has_generics && is_instantiable_downstream(Some(def), &args);
310
311                    if should_export {
312                        let symbol = ExportedSymbol::Generic(def, args);
313                        symbols.push((
314                            symbol,
315                            SymbolExportInfo {
316                                level: SymbolExportLevel::Rust,
317                                kind: SymbolExportKind::Text,
318                                used: false,
319                                rustc_std_internal_symbol: false,
320                            },
321                        ));
322                    }
323                }
324                MonoItem::Fn(Instance { def: InstanceKind::DropGlue(_, Some(ty)), args }) => {
325                    // A little sanity-check
326                    assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
327
328                    // Drop glue did is always going to be non-local outside of libcore, thus we don't need to check it's locality (which includes invoking `type_of` query).
329                    let should_export = match ty.kind() {
330                        ty::Adt(_, args) => is_instantiable_downstream(None, args),
331                        ty::Closure(_, args) => is_instantiable_downstream(None, args),
332                        _ => true,
333                    };
334
335                    if should_export {
336                        symbols.push((
337                            ExportedSymbol::DropGlue(ty),
338                            SymbolExportInfo {
339                                level: SymbolExportLevel::Rust,
340                                kind: SymbolExportKind::Text,
341                                used: false,
342                                rustc_std_internal_symbol: false,
343                            },
344                        ));
345                    }
346                }
347                MonoItem::Fn(Instance {
348                    def: InstanceKind::AsyncDropGlueCtorShim(_, ty),
349                    args,
350                }) => {
351                    // A little sanity-check
352                    assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
353                    symbols.push((
354                        ExportedSymbol::AsyncDropGlueCtorShim(ty),
355                        SymbolExportInfo {
356                            level: SymbolExportLevel::Rust,
357                            kind: SymbolExportKind::Text,
358                            used: false,
359                            rustc_std_internal_symbol: false,
360                        },
361                    ));
362                }
363                MonoItem::Fn(Instance { def: InstanceKind::AsyncDropGlue(def, ty), args: _ }) => {
364                    symbols.push((
365                        ExportedSymbol::AsyncDropGlue(def, ty),
366                        SymbolExportInfo {
367                            level: SymbolExportLevel::Rust,
368                            kind: SymbolExportKind::Text,
369                            used: false,
370                            rustc_std_internal_symbol: false,
371                        },
372                    ));
373                }
374                _ => {
375                    // Any other symbols don't qualify for sharing
376                }
377            }
378        }
379    }
380
381    // Sort so we get a stable incr. comp. hash.
382    symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
383
384    tcx.arena.alloc_from_iter(symbols)
385}
386
387fn upstream_monomorphizations_provider(
388    tcx: TyCtxt<'_>,
389    (): (),
390) -> DefIdMap<UnordMap<GenericArgsRef<'_>, CrateNum>> {
391    let cnums = tcx.crates(());
392
393    let mut instances: DefIdMap<UnordMap<_, _>> = Default::default();
394
395    let drop_in_place_fn_def_id = tcx.lang_items().drop_in_place_fn();
396    let async_drop_in_place_fn_def_id = tcx.lang_items().async_drop_in_place_fn();
397
398    for &cnum in cnums.iter() {
399        for (exported_symbol, _) in tcx.exported_generic_symbols(cnum).iter() {
400            let (def_id, args) = match *exported_symbol {
401                ExportedSymbol::Generic(def_id, args) => (def_id, args),
402                ExportedSymbol::DropGlue(ty) => {
403                    if let Some(drop_in_place_fn_def_id) = drop_in_place_fn_def_id {
404                        (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
405                    } else {
406                        // `drop_in_place` in place does not exist, don't try
407                        // to use it.
408                        continue;
409                    }
410                }
411                ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
412                    if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
413                        (async_drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
414                    } else {
415                        continue;
416                    }
417                }
418                ExportedSymbol::AsyncDropGlue(def_id, ty) => (def_id, tcx.mk_args(&[ty.into()])),
419                ExportedSymbol::NonGeneric(..)
420                | ExportedSymbol::ThreadLocalShim(..)
421                | ExportedSymbol::NoDefId(..) => unreachable!("{exported_symbol:?}"),
422            };
423
424            let args_map = instances.entry(def_id).or_default();
425
426            match args_map.entry(args) {
427                Occupied(mut e) => {
428                    // If there are multiple monomorphizations available,
429                    // we select one deterministically.
430                    let other_cnum = *e.get();
431                    if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
432                        e.insert(cnum);
433                    }
434                }
435                Vacant(e) => {
436                    e.insert(cnum);
437                }
438            }
439        }
440    }
441
442    instances
443}
444
445fn upstream_monomorphizations_for_provider(
446    tcx: TyCtxt<'_>,
447    def_id: DefId,
448) -> Option<&UnordMap<GenericArgsRef<'_>, CrateNum>> {
449    assert!(!def_id.is_local());
450    tcx.upstream_monomorphizations(()).get(&def_id)
451}
452
453fn upstream_drop_glue_for_provider<'tcx>(
454    tcx: TyCtxt<'tcx>,
455    args: GenericArgsRef<'tcx>,
456) -> Option<CrateNum> {
457    let def_id = tcx.lang_items().drop_in_place_fn()?;
458    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
459}
460
461fn upstream_async_drop_glue_for_provider<'tcx>(
462    tcx: TyCtxt<'tcx>,
463    args: GenericArgsRef<'tcx>,
464) -> Option<CrateNum> {
465    let def_id = tcx.lang_items().async_drop_in_place_fn()?;
466    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
467}
468
469fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
470    !tcx.reachable_set(()).contains(&def_id)
471}
472
473pub(crate) fn provide(providers: &mut Providers) {
474    providers.reachable_non_generics = reachable_non_generics_provider;
475    providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
476    providers.exported_non_generic_symbols = exported_non_generic_symbols_provider_local;
477    providers.exported_generic_symbols = exported_generic_symbols_provider_local;
478    providers.upstream_monomorphizations = upstream_monomorphizations_provider;
479    providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
480    providers.upstream_drop_glue_for = upstream_drop_glue_for_provider;
481    providers.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
482    providers.wasm_import_module_map = wasm_import_module_map;
483    providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
484    providers.extern_queries.upstream_monomorphizations_for =
485        upstream_monomorphizations_for_provider;
486}
487
488pub(crate) fn allocator_shim_symbols(
489    tcx: TyCtxt<'_>,
490) -> impl Iterator<Item = (String, SymbolExportKind)> {
491    ALLOCATOR_METHODS
492        .iter()
493        .map(move |method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
494        .chain([
495            mangle_internal_symbol(tcx, global_fn_name(ALLOC_ERROR_HANDLER).as_str()),
496            mangle_internal_symbol(tcx, OomStrategy::SYMBOL),
497            mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE),
498        ])
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    // We export anything that's not mangled at the "C" layer as it probably has
515    // to do with ABI concerns. We do not, however, apply such treatment to
516    // special symbols in the standard library for various plumbing between
517    // core/std/allocators/etc. For example symbols used to hook up allocation
518    // are not considered for export
519    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
524    if is_extern && !std_internal {
525        let target = &tcx.sess.target.llvm_target;
526        // WebAssembly cannot export data symbols, so reduce their export level
527        if target.contains("emscripten") {
528            if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
529                return SymbolExportLevel::Rust;
530            }
531        }
532
533        SymbolExportLevel::C
534    } else {
535        SymbolExportLevel::Rust
536    }
537}
538
539/// This is the symbol name of the given instance instantiated in a specific crate.
540pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
541    tcx: TyCtxt<'tcx>,
542    symbol: ExportedSymbol<'tcx>,
543    instantiating_crate: CrateNum,
544) -> String {
545    // If this is something instantiated in the local crate then we might
546    // already have cached the name as a query result.
547    if instantiating_crate == LOCAL_CRATE {
548        return symbol.symbol_name_for_local_instance(tcx).to_string();
549    }
550
551    // This is something instantiated in an upstream crate, so we have to use
552    // the slower (because uncached) version of computing the symbol name.
553    match symbol {
554        ExportedSymbol::NonGeneric(def_id) => {
555            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
556                tcx,
557                Instance::mono(tcx, def_id),
558                instantiating_crate,
559            )
560        }
561        ExportedSymbol::Generic(def_id, args) => {
562            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
563                tcx,
564                Instance::new_raw(def_id, args),
565                instantiating_crate,
566            )
567        }
568        ExportedSymbol::ThreadLocalShim(def_id) => {
569            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
570                tcx,
571                ty::Instance {
572                    def: ty::InstanceKind::ThreadLocalShim(def_id),
573                    args: ty::GenericArgs::empty(),
574                },
575                instantiating_crate,
576            )
577        }
578        ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
579            tcx,
580            Instance::resolve_drop_in_place(tcx, ty),
581            instantiating_crate,
582        ),
583        ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
584            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
585                tcx,
586                Instance::resolve_async_drop_in_place(tcx, ty),
587                instantiating_crate,
588            )
589        }
590        ExportedSymbol::AsyncDropGlue(def_id, ty) => {
591            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
592                tcx,
593                Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
594                instantiating_crate,
595            )
596        }
597        ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
598    }
599}
600
601fn calling_convention_for_symbol<'tcx>(
602    tcx: TyCtxt<'tcx>,
603    symbol: ExportedSymbol<'tcx>,
604) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
605    let instance = match symbol {
606        ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
607            if tcx.is_static(def_id) =>
608        {
609            None
610        }
611        ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
612        ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
613        // DropGlue always use the Rust calling convention and thus follow the target's default
614        // symbol decoration scheme.
615        ExportedSymbol::DropGlue(..) => None,
616        // AsyncDropGlueCtorShim always use the Rust calling convention and thus follow the
617        // target's default symbol decoration scheme.
618        ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
619        ExportedSymbol::AsyncDropGlue(..) => None,
620        // NoDefId always follow the target's default symbol decoration scheme.
621        ExportedSymbol::NoDefId(..) => None,
622        // ThreadLocalShim always follow the target's default symbol decoration scheme.
623        ExportedSymbol::ThreadLocalShim(..) => None,
624    };
625
626    instance
627        .map(|i| {
628            tcx.fn_abi_of_instance(
629                ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
630            )
631            .unwrap_or_else(|_| bug!("fn_abi_of_instance({i:?}) failed"))
632        })
633        .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
634        // FIXME(workingjubilee): why don't we know the convention here?
635        .unwrap_or((CanonAbi::Rust, &[]))
636}
637
638/// This is the symbol name of the given instance as seen by the linker.
639///
640/// On 32-bit Windows symbols are decorated according to their calling conventions.
641pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
642    tcx: TyCtxt<'tcx>,
643    symbol: ExportedSymbol<'tcx>,
644    export_kind: SymbolExportKind,
645    instantiating_crate: CrateNum,
646) -> String {
647    let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
648
649    // thread local will not be a function call,
650    // so it is safe to return before windows symbol decoration check.
651    if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
652        return name;
653    }
654
655    let target = &tcx.sess.target;
656    if !target.is_like_windows {
657        // Mach-O has a global "_" suffix and `object` crate will handle it.
658        // ELF does not have any symbol decorations.
659        return undecorated;
660    }
661
662    let prefix = match target.arch {
663        Arch::X86 => Some('_'),
664        Arch::X86_64 => None,
665        // Only functions are decorated for arm64ec.
666        Arch::Arm64EC if export_kind == SymbolExportKind::Text => Some('#'),
667        // Only x86/64 and arm64ec use symbol decorations.
668        _ => return undecorated,
669    };
670
671    let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
672
673    // Decorate symbols with prefixes, suffixes and total number of bytes of arguments.
674    // Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170
675    let (prefix, suffix) = match callconv {
676        CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
677        CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
678        CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
679        _ => {
680            if let Some(prefix) = prefix {
681                undecorated.insert(0, prefix);
682            }
683            return undecorated;
684        }
685    };
686
687    let args_in_bytes: u64 = args
688        .iter()
689        .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
690        .sum();
691    format!("{prefix}{undecorated}{suffix}{args_in_bytes}")
692}
693
694pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
695    tcx: TyCtxt<'tcx>,
696    symbol: ExportedSymbol<'tcx>,
697    cnum: CrateNum,
698) -> String {
699    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
700    maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
701}
702
703/// On amdhsa, `gpu-kernel` functions have an associated metadata object with a `.kd` suffix.
704/// Add it to the symbols list for all kernel functions, so that it is exported in the linked
705/// object.
706pub(crate) fn extend_exported_symbols<'tcx>(
707    symbols: &mut Vec<(String, SymbolExportKind)>,
708    tcx: TyCtxt<'tcx>,
709    symbol: ExportedSymbol<'tcx>,
710    instantiating_crate: CrateNum,
711) {
712    let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
713
714    if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != Os::AmdHsa {
715        return;
716    }
717
718    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
719
720    // Add the symbol for the kernel descriptor (with .kd suffix)
721    // Per https://llvm.org/docs/AMDGPUUsage.html#symbols these will always be `STT_OBJECT` so
722    // export as data.
723    symbols.push((format!("{undecorated}.kd"), SymbolExportKind::Data));
724}
725
726fn maybe_emutls_symbol_name<'tcx>(
727    tcx: TyCtxt<'tcx>,
728    symbol: ExportedSymbol<'tcx>,
729    undecorated: &str,
730) -> Option<String> {
731    if matches!(tcx.sess.tls_model(), TlsModel::Emulated)
732        && let ExportedSymbol::NonGeneric(def_id) = symbol
733        && tcx.is_thread_local_static(def_id)
734    {
735        // When using emutls, LLVM will add the `__emutls_v.` prefix to thread local symbols,
736        // and exported symbol name need to match this.
737        Some(format!("__emutls_v.{undecorated}"))
738    } else {
739        None
740    }
741}
742
743fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
744    // Build up a map from DefId to a `NativeLib` structure, where
745    // `NativeLib` internally contains information about
746    // `#[link(wasm_import_module = "...")]` for example.
747    let native_libs = tcx.native_libraries(cnum);
748
749    let def_id_to_native_lib = native_libs
750        .iter()
751        .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
752        .collect::<DefIdMap<_>>();
753
754    let mut ret = DefIdMap::default();
755    for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
756        let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
757        let Some(module) = module else { continue };
758        ret.extend(lib.foreign_items.iter().map(|id| {
759            assert_eq!(id.krate, cnum);
760            (*id, module.to_string())
761        }));
762    }
763
764    ret
765}