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;
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                    || 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    // FIXME: Sorting this is unnecessary since we are sorting later anyway.
177    //        Can we skip the later sorting?
178    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    // Export TLS shims
186    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    // Sort so we get a stable incr. comp. hash.
218    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<_> = 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        // Normally, we require that shared monomorphizations are not hidden,
239        // because if we want to re-use a monomorphization from a Rust dylib, it
240        // needs to be exported.
241        // However, on platforms that don't allow for Rust dylibs, having
242        // external linkage is enough for monomorphization to be linked to.
243        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        // Do not export symbols that cannot be instantiated by downstream crates.
248        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        // The symbols created in this loop are sorted below it
280        #[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                // We can only re-use things with external linkage, otherwise
284                // we'll get a linker error
285                continue;
286            }
287
288            if need_visibility && data.visibility == Visibility::Hidden {
289                // If we potentially share things from Rust dylibs, they must
290                // not be hidden
291                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                    // this is OK, we explicitly allow sharing inline(never) across crates even
299                    // without share-generics.
300                } else {
301                    continue;
302                }
303            }
304
305            // Note: These all set rustc_std_internal_symbol to false as generic functions must not
306            // be marked with this attribute and we are only handling generic functions here.
307            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                    // A little sanity-check
329                    assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
330
331                    // 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).
332                    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                    // A little sanity-check
355                    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                    // Any other symbols don't qualify for sharing
379                }
380            }
381        }
382    }
383
384    // Sort so we get a stable incr. comp. hash.
385    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                        // `drop_in_place` in place does not exist, don't try
410                        // to use it.
411                        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(..) => 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                    // If there are multiple monomorphizations available,
432                    // we select one deterministically.
433                    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    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.reachable_non_generics = reachable_non_generics_provider;
478    providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
479    providers.exported_non_generic_symbols = exported_non_generic_symbols_provider_local;
480    providers.exported_generic_symbols = exported_generic_symbols_provider_local;
481    providers.upstream_monomorphizations = upstream_monomorphizations_provider;
482    providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
483    providers.upstream_drop_glue_for = upstream_drop_glue_for_provider;
484    providers.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
485    providers.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) -> impl Iterator<Item = (String, SymbolExportKind)> {
494    ALLOCATOR_METHODS
495        .iter()
496        .map(move |method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
497        .chain([
498            mangle_internal_symbol(tcx, global_fn_name(ALLOC_ERROR_HANDLER).as_str()),
499            mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE),
500        ])
501        .map(move |symbol_name| {
502            let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
503
504            (
505                symbol_export::exporting_symbol_name_for_instance_in_crate(
506                    tcx,
507                    exported_symbol,
508                    LOCAL_CRATE,
509                ),
510                SymbolExportKind::Text,
511            )
512        })
513}
514
515fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
516    // We export anything that's not mangled at the "C" layer as it probably has
517    // to do with ABI concerns. We do not, however, apply such treatment to
518    // special symbols in the standard library for various plumbing between
519    // core/std/allocators/etc. For example symbols used to hook up allocation
520    // are not considered for export
521    let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
522    let is_extern = codegen_fn_attrs.contains_extern_indicator();
523    let std_internal =
524        codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
525    let eii = codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
526
527    if is_extern && !std_internal && !eii {
528        let target = &tcx.sess.target.llvm_target;
529        // WebAssembly cannot export data symbols, so reduce their export level
530        // FIXME(jdonszelmann) don't do a substring match here.
531        if target.contains("emscripten") {
532            if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
533                return SymbolExportLevel::Rust;
534            }
535        }
536
537        SymbolExportLevel::C
538    } else {
539        SymbolExportLevel::Rust
540    }
541}
542
543/// This is the symbol name of the given instance instantiated in a specific crate.
544pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
545    tcx: TyCtxt<'tcx>,
546    symbol: ExportedSymbol<'tcx>,
547    instantiating_crate: CrateNum,
548) -> String {
549    // If this is something instantiated in the local crate then we might
550    // already have cached the name as a query result.
551    if instantiating_crate == LOCAL_CRATE {
552        return symbol.symbol_name_for_local_instance(tcx).to_string();
553    }
554
555    // This is something instantiated in an upstream crate, so we have to use
556    // the slower (because uncached) version of computing the symbol name.
557    match symbol {
558        ExportedSymbol::NonGeneric(def_id) => {
559            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
560                tcx,
561                Instance::mono(tcx, def_id),
562                instantiating_crate,
563            )
564        }
565        ExportedSymbol::Generic(def_id, args) => {
566            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
567                tcx,
568                Instance::new_raw(def_id, args),
569                instantiating_crate,
570            )
571        }
572        ExportedSymbol::ThreadLocalShim(def_id) => {
573            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
574                tcx,
575                ty::Instance {
576                    def: ty::InstanceKind::ThreadLocalShim(def_id),
577                    args: ty::GenericArgs::empty(),
578                },
579                instantiating_crate,
580            )
581        }
582        ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
583            tcx,
584            Instance::resolve_drop_in_place(tcx, ty),
585            instantiating_crate,
586        ),
587        ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
588            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
589                tcx,
590                Instance::resolve_async_drop_in_place(tcx, ty),
591                instantiating_crate,
592            )
593        }
594        ExportedSymbol::AsyncDropGlue(def_id, ty) => {
595            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
596                tcx,
597                Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
598                instantiating_crate,
599            )
600        }
601        ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
602    }
603}
604
605fn calling_convention_for_symbol<'tcx>(
606    tcx: TyCtxt<'tcx>,
607    symbol: ExportedSymbol<'tcx>,
608) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
609    let instance = match symbol {
610        ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
611            if tcx.is_static(def_id) =>
612        {
613            None
614        }
615        ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
616        ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
617        // DropGlue always use the Rust calling convention and thus follow the target's default
618        // symbol decoration scheme.
619        ExportedSymbol::DropGlue(..) => None,
620        // AsyncDropGlueCtorShim always use the Rust calling convention and thus follow the
621        // target's default symbol decoration scheme.
622        ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
623        ExportedSymbol::AsyncDropGlue(..) => None,
624        // NoDefId always follow the target's default symbol decoration scheme.
625        ExportedSymbol::NoDefId(..) => None,
626        // ThreadLocalShim always follow the target's default symbol decoration scheme.
627        ExportedSymbol::ThreadLocalShim(..) => None,
628    };
629
630    instance
631        .map(|i| {
632            tcx.fn_abi_of_instance(
633                ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
634            )
635            .unwrap_or_else(|_| bug!("fn_abi_of_instance({i:?}) failed"))
636        })
637        .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
638        // FIXME(workingjubilee): why don't we know the convention here?
639        .unwrap_or((CanonAbi::Rust, &[]))
640}
641
642/// This is the symbol name of the given instance as seen by the linker.
643///
644/// On 32-bit Windows symbols are decorated according to their calling conventions.
645pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
646    tcx: TyCtxt<'tcx>,
647    symbol: ExportedSymbol<'tcx>,
648    export_kind: SymbolExportKind,
649    instantiating_crate: CrateNum,
650) -> String {
651    let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
652
653    // thread local will not be a function call,
654    // so it is safe to return before windows symbol decoration check.
655    if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
656        return name;
657    }
658
659    let target = &tcx.sess.target;
660    if !target.is_like_windows {
661        // Mach-O has a global "_" suffix and `object` crate will handle it.
662        // ELF does not have any symbol decorations.
663        return undecorated;
664    }
665
666    let prefix = match target.arch {
667        Arch::X86 => Some('_'),
668        Arch::X86_64 => None,
669        // Only functions are decorated for arm64ec.
670        Arch::Arm64EC if export_kind == SymbolExportKind::Text => Some('#'),
671        // Only x86/64 and arm64ec use symbol decorations.
672        _ => return undecorated,
673    };
674
675    let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
676
677    // Decorate symbols with prefixes, suffixes and total number of bytes of arguments.
678    // Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170
679    let (prefix, suffix) = match callconv {
680        CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
681        CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
682        CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
683        _ => {
684            if let Some(prefix) = prefix {
685                undecorated.insert(0, prefix);
686            }
687            return undecorated;
688        }
689    };
690
691    let args_in_bytes: u64 = args
692        .iter()
693        .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
694        .sum();
695    format!("{prefix}{undecorated}{suffix}{args_in_bytes}")
696}
697
698pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
699    tcx: TyCtxt<'tcx>,
700    symbol: ExportedSymbol<'tcx>,
701    cnum: CrateNum,
702) -> String {
703    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
704    maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
705}
706
707/// On amdhsa, `gpu-kernel` functions have an associated metadata object with a `.kd` suffix.
708/// Add it to the symbols list for all kernel functions, so that it is exported in the linked
709/// object.
710pub(crate) fn extend_exported_symbols<'tcx>(
711    symbols: &mut Vec<(String, SymbolExportKind)>,
712    tcx: TyCtxt<'tcx>,
713    symbol: ExportedSymbol<'tcx>,
714    instantiating_crate: CrateNum,
715) {
716    let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
717
718    if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != Os::AmdHsa {
719        return;
720    }
721
722    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
723
724    // Add the symbol for the kernel descriptor (with .kd suffix)
725    // Per https://llvm.org/docs/AMDGPUUsage.html#symbols these will always be `STT_OBJECT` so
726    // export as data.
727    symbols.push((format!("{undecorated}.kd"), SymbolExportKind::Data));
728}
729
730fn maybe_emutls_symbol_name<'tcx>(
731    tcx: TyCtxt<'tcx>,
732    symbol: ExportedSymbol<'tcx>,
733    undecorated: &str,
734) -> Option<String> {
735    if matches!(tcx.sess.tls_model(), TlsModel::Emulated)
736        && let ExportedSymbol::NonGeneric(def_id) = symbol
737        && tcx.is_thread_local_static(def_id)
738    {
739        // When using emutls, LLVM will add the `__emutls_v.` prefix to thread local symbols,
740        // and exported symbol name need to match this.
741        Some(format!("__emutls_v.{undecorated}"))
742    } else {
743        None
744    }
745}
746
747fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
748    // Build up a map from DefId to a `NativeLib` structure, where
749    // `NativeLib` internally contains information about
750    // `#[link(wasm_import_module = "...")]` for example.
751    let native_libs = tcx.native_libraries(cnum);
752
753    let def_id_to_native_lib = native_libs
754        .iter()
755        .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
756        .collect::<DefIdMap<_>>();
757
758    let mut ret = DefIdMap::default();
759    for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
760        let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
761        let Some(module) = module else { continue };
762        ret.extend(lib.foreign_items.iter().map(|id| {
763            assert_eq!(id.krate, cnum);
764            (*id, module.to_string())
765        }));
766    }
767
768    ret
769}