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