rustc_codegen_ssa/back/
symbol_export.rs

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