Skip to main content

rustc_codegen_ssa/back/
symbol_export.rs

1use std::collections::hash_map::Entry::*;
2
3use rustc_abi::{CanonAbi, X86Call};
4use rustc_ast::expand::allocator::{AllocatorKind, NO_ALLOC_SHIM_IS_UNSTABLE, global_fn_name};
5use rustc_crate_store::CrateDepKind;
6use rustc_data_structures::fx::FxHashSet;
7use rustc_data_structures::unord::UnordMap;
8use rustc_hir as hir;
9use rustc_hir::def::DefKind;
10use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE, LocalDefId};
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::{
17    self, GenericArgKind, GenericArgsRef, Instance, ShimKind, SymbolName, Ty, TyCtxt,
18};
19use rustc_middle::util::Providers;
20use rustc_span::{Span, bug};
21use rustc_structures::CrateType;
22use rustc_symbol_mangling::{is_offload_kernel, mangle_internal_symbol};
23use rustc_target::spec::{Arch, Os, TlsModel};
24use tracing::debug;
25
26use crate::SymbolExport;
27use crate::back::symbol_export;
28use crate::base::allocator_shim_contents;
29
30fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
31    crates_export_threshold(tcx.crate_types())
32}
33
34fn crate_export_threshold(crate_type: CrateType) -> SymbolExportLevel {
35    match crate_type {
36        CrateType::Executable | CrateType::StaticLib | CrateType::ProcMacro | CrateType::Cdylib => {
37            SymbolExportLevel::C
38        }
39        CrateType::Rlib | CrateType::Dylib | CrateType::Sdylib => SymbolExportLevel::Rust,
40    }
41}
42
43pub fn crates_export_threshold(crate_types: &[CrateType]) -> SymbolExportLevel {
44    if crate_types
45        .iter()
46        .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
47    {
48        SymbolExportLevel::Rust
49    } else {
50        SymbolExportLevel::C
51    }
52}
53
54fn reachable_non_generics_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> DefIdMap<SymbolExportInfo> {
55    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
56        return Default::default();
57    }
58
59    reachable_non_generics_helper(tcx)
60}
61
62/// Exposed separately *without* the "should codegen" check so Miri can access it.
63pub fn reachable_non_generics_helper(tcx: TyCtxt<'_>) -> DefIdMap<SymbolExportInfo> {
64    let is_compiler_builtins = tcx.is_compiler_builtins(LOCAL_CRATE);
65
66    let mut reachable_non_generics: DefIdMap<_> = tcx
67        .reachable_set(())
68        .items()
69        .filter_map(|&def_id| {
70            // We want to ignore some FFI functions that are not exposed from
71            // this crate. Reachable FFI functions can be lumped into two
72            // categories:
73            //
74            // 1. Those that are included statically via a static library
75            // 2. Those included otherwise (e.g., dynamically or via a framework)
76            //
77            // Although our LLVM module is not literally emitting code for the
78            // statically included symbols, it's an export of our library which
79            // needs to be passed on to the linker and encoded in the metadata.
80            //
81            // As a result, if this id is an FFI item (foreign item) then we only
82            // let it through if it's included statically.
83            if let Some(parent_id) = tcx.opt_local_parent(def_id)
84                && let DefKind::ForeignMod = tcx.def_kind(parent_id)
85            {
86                let library = tcx.native_library(def_id)?;
87                return library.kind.is_statically_included().then_some(def_id);
88            }
89
90            // Only consider nodes that actually have exported symbols.
91            match tcx.def_kind(def_id) {
92                DefKind::Fn | DefKind::AssocFn
93                    if tcx.constness(def_id) == hir::Constness::Const { always: true } =>
94                {
95                    return None;
96                }
97                DefKind::Fn | DefKind::Static { .. } => {}
98                DefKind::AssocFn if tcx.impl_of_assoc(def_id.to_def_id()).is_some() => {}
99                _ => return None,
100            };
101
102            let generics = tcx.generics_of(def_id);
103            if generics.requires_monomorphization(tcx) {
104                return None;
105            }
106
107            if Instance::mono(tcx, def_id.into()).def.requires_inline(tcx) {
108                return None;
109            }
110
111            if tcx.cross_crate_inlinable(def_id) { None } else { Some(def_id) }
112        })
113        .map(|def_id| {
114            let export_level = if is_compiler_builtins {
115                // We don't want to export compiler-builtins symbols from any
116                // dylibs, even rust dylibs. Unlike all other crates it gets
117                // duplicated in every linker invocation and it may otherwise
118                // unintentionally override definitions of these symbols by
119                // libgcc or compiler-rt for C code.
120                SymbolExportLevel::Rust
121            } else {
122                symbol_export_level(tcx, def_id.to_def_id())
123            };
124            let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
125            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/back/symbol_export.rs:125",
                        "rustc_codegen_ssa::back::symbol_export",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/back/symbol_export.rs"),
                        ::tracing_core::__macro_support::Option::Some(125u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::symbol_export"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("EXPORTED SYMBOL (local): {0} ({1:?})",
                                                    tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
                                                    export_level) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
126                "EXPORTED SYMBOL (local): {} ({:?})",
127                tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
128                export_level
129            );
130            let info = SymbolExportInfo {
131                level: export_level,
132                kind: if tcx.is_static(def_id.to_def_id()) {
133                    if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
134                        SymbolExportKind::Tls
135                    } else {
136                        SymbolExportKind::Data
137                    }
138                } else {
139                    SymbolExportKind::Text
140                },
141                used: codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
142                    || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER),
143                rustc_std_internal_symbol: codegen_attrs
144                    .flags
145                    .contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
146                    || codegen_attrs
147                        .flags
148                        .contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM),
149            };
150            (def_id.to_def_id(), info)
151        })
152        .into();
153
154    if let Some(id) = tcx.proc_macro_decls_static(()) {
155        reachable_non_generics.insert(
156            id.to_def_id(),
157            SymbolExportInfo {
158                level: SymbolExportLevel::C,
159                kind: SymbolExportKind::Data,
160                used: false,
161                rustc_std_internal_symbol: false,
162            },
163        );
164    }
165
166    reachable_non_generics
167}
168
169fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
170    let export_threshold = threshold(tcx);
171
172    if let Some(&info) = tcx.reachable_non_generics(LOCAL_CRATE).get(&def_id.to_def_id()) {
173        info.level.is_below_threshold(export_threshold)
174    } else {
175        false
176    }
177}
178
179fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
180    tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
181}
182
183fn exported_non_generic_symbols_provider_local<'tcx>(
184    tcx: TyCtxt<'tcx>,
185    _: LocalCrate,
186) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
187    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
188        return &[];
189    }
190
191    exported_non_generic_symbols_helper(tcx)
192}
193
194/// Exposed separately *without* the "should codegen" check so Miri can access it.
195pub fn exported_non_generic_symbols_helper<'tcx>(
196    tcx: TyCtxt<'tcx>,
197) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
198    // FIXME: Sorting this is unnecessary since we are sorting later anyway.
199    //        Can we skip the later sorting?
200    let sorted = tcx.with_stable_hashing_context(|mut hcx| {
201        tcx.reachable_non_generics(LOCAL_CRATE).to_sorted(&mut hcx, true)
202    });
203
204    let mut symbols: Vec<_> =
205        sorted.iter().map(|&(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect();
206
207    // Export TLS shims
208    if !tcx.sess.target.dll_tls_export {
209        symbols.extend(sorted.iter().filter_map(|&(&def_id, &info)| {
210            tcx.needs_thread_local_shim(def_id).then(|| {
211                (
212                    ExportedSymbol::ThreadLocalShim(def_id),
213                    SymbolExportInfo {
214                        level: info.level,
215                        kind: SymbolExportKind::Text,
216                        used: info.used,
217                        rustc_std_internal_symbol: info.rustc_std_internal_symbol,
218                    },
219                )
220            })
221        }))
222    }
223
224    symbols.extend(sorted.iter().flat_map(|&(&def_id, &info)| {
225        tcx.codegen_fn_attrs(def_id).foreign_item_symbol_aliases.iter().map(
226            move |&(foreign_item, _linkage, _visibility)| {
227                (ExportedSymbol::NonGeneric(foreign_item), info)
228            },
229        )
230    }));
231
232    if tcx.entry_fn(()).is_some() {
233        let exported_symbol =
234            ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
235
236        symbols.push((
237            exported_symbol,
238            SymbolExportInfo {
239                level: SymbolExportLevel::C,
240                kind: SymbolExportKind::Text,
241                used: false,
242                rustc_std_internal_symbol: false,
243            },
244        ));
245    }
246
247    let is_device_offload = tcx
248        .sess
249        .opts
250        .unstable_opts
251        .offload
252        .iter()
253        .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    rustc_session::config::Offload::Device(_) => true,
    _ => false,
}matches!(o, rustc_session::config::Offload::Device(_)));
254    if is_device_offload {
255        let crate_items = tcx.hir_crate_items(());
256        let mut seen: rustc_data_structures::fx::FxHashSet<DefId> = symbols
257            .iter()
258            .filter_map(|(s, _)| match s {
259                ExportedSymbol::NonGeneric(d) => Some(*d),
260                _ => None,
261            })
262            .collect();
263
264        let mut try_emit_offload_kernel = |def_id: DefId, seen: &mut FxHashSet<DefId>| {
265            if !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
266                return;
267            }
268            if !tcx.generics_of(def_id).requires_monomorphization(tcx)
269                && is_offload_kernel(tcx.codegen_fn_attrs(def_id))
270                && seen.insert(def_id)
271            {
272                symbols.push((
273                    ExportedSymbol::NonGeneric(def_id),
274                    SymbolExportInfo {
275                        level: SymbolExportLevel::C,
276                        kind: SymbolExportKind::Text,
277                        used: false,
278                        rustc_std_internal_symbol: false,
279                    },
280                ));
281            }
282        };
283
284        for id in crate_items.free_items() {
285            try_emit_offload_kernel(id.owner_id.to_def_id(), &mut seen);
286        }
287        for id in crate_items.impl_items() {
288            try_emit_offload_kernel(id.owner_id.to_def_id(), &mut seen);
289        }
290    }
291
292    // Sort so we get a stable incr. comp. hash.
293    symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
294
295    tcx.arena.alloc_from_iter(symbols)
296}
297
298fn exported_generic_symbols_provider_local<'tcx>(
299    tcx: TyCtxt<'tcx>,
300    _: LocalCrate,
301) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
302    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
303        return &[];
304    }
305
306    let mut symbols: Vec<_> = ::alloc::vec::Vec::new()vec![];
307
308    let export_generics = tcx.local_crate_exports_generics();
309    let is_device_offload = tcx
310        .sess
311        .opts
312        .unstable_opts
313        .offload
314        .iter()
315        .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    rustc_session::config::Offload::Device(_) => true,
    _ => false,
}matches!(o, rustc_session::config::Offload::Device(_)));
316
317    if export_generics || is_device_offload {
318        use rustc_hir::attrs::Linkage;
319        use rustc_middle::mono::{MonoItem, Visibility};
320        use rustc_middle::ty::InstanceKind;
321
322        // Normally, we require that shared monomorphizations are not hidden,
323        // because if we want to re-use a monomorphization from a Rust dylib, it
324        // needs to be exported.
325        // However, on platforms that don't allow for Rust dylibs, having
326        // external linkage is enough for monomorphization to be linked to.
327        let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
328
329        let cgus = tcx.collect_and_partition_mono_items(()).codegen_units;
330
331        // Do not export symbols that cannot be instantiated by downstream crates.
332        let reachable_set = tcx.reachable_set(());
333        let is_local_to_current_crate = |ty: Ty<'_>| {
334            let no_refs = ty.peel_refs();
335            let root_def_id = match no_refs.kind() {
336                ty::Closure(closure, _) => *closure,
337                ty::FnDef(def_id, _) => *def_id,
338                ty::Coroutine(def_id, _) => *def_id,
339                ty::CoroutineClosure(def_id, _) => *def_id,
340                ty::CoroutineWitness(def_id, _) => *def_id,
341                _ => return false,
342            };
343            let Some(root_def_id) = root_def_id.as_local() else {
344                return false;
345            };
346
347            let is_local = !reachable_set.contains(&root_def_id);
348            is_local
349        };
350
351        let is_instantiable_downstream =
352            |did: Option<DefId>, generic_args: GenericArgsRef<'tcx>| {
353                generic_args
354                    .types()
355                    .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder()))
356                    .all(move |arg| {
357                        arg.walk().all(|ty| {
358                            ty.as_type().map_or(true, |ty| !is_local_to_current_crate(ty))
359                        })
360                    })
361            };
362
363        let is_offload_instance = |mono_item: &MonoItem<'tcx>| {
364            if let MonoItem::Fn(instance) = mono_item {
365                is_offload_kernel(tcx.codegen_fn_attrs(instance.def_id()))
366            } else {
367                false
368            }
369        };
370
371        // The symbols created in this loop are sorted below it
372        #[allow(rustc::potential_query_instability)]
373        for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
374            if data.linkage != Linkage::External {
375                // We can only re-use things with external linkage, otherwise
376                // we'll get a linker error
377                continue;
378            }
379
380            if need_visibility && data.visibility == Visibility::Hidden {
381                // If we potentially share things from Rust dylibs, they must
382                // not be hidden
383                continue;
384            }
385
386            let item_is_offload = is_offload_instance(mono_item);
387
388            if !item_is_offload && !tcx.sess.opts.share_generics() {
389                if tcx.codegen_fn_attrs(mono_item.def_id()).inline
390                    == rustc_hir::attrs::InlineAttr::Never
391                {
392                    // this is OK, we explicitly allow sharing inline(never) across crates even
393                    // without share-generics.
394                } else {
395                    continue;
396                }
397            }
398
399            // Note: These all set rustc_std_internal_symbol to false as generic functions must not
400            // be marked with this attribute and we are only handling generic functions here.
401            match *mono_item {
402                MonoItem::Fn(Instance { def: InstanceKind::Item(def), args }) => {
403                    let has_generics = args.non_erasable_generics().next().is_some();
404
405                    let should_export = if item_is_offload {
406                        has_generics
407                    } else {
408                        has_generics && is_instantiable_downstream(Some(def), &args)
409                    };
410
411                    if should_export {
412                        let symbol = ExportedSymbol::Generic(def, args);
413                        symbols.push((
414                            symbol,
415                            SymbolExportInfo {
416                                level: if item_is_offload {
417                                    SymbolExportLevel::C
418                                } else {
419                                    SymbolExportLevel::Rust
420                                },
421                                kind: SymbolExportKind::Text,
422                                used: false,
423                                rustc_std_internal_symbol: false,
424                            },
425                        ));
426                    }
427                }
428                MonoItem::Fn(Instance {
429                    def: InstanceKind::Shim(ShimKind::DropGlue(_, Some(ty))),
430                    args,
431                }) => {
432                    // A little sanity-check
433                    {
    match (&args.non_erasable_generics().next(),
            &Some(GenericArgKind::Type(ty))) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
434
435                    // 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).
436                    let should_export = match ty.kind() {
437                        ty::Adt(_, args) => is_instantiable_downstream(None, args),
438                        ty::Closure(_, args) => is_instantiable_downstream(None, args),
439                        _ => true,
440                    };
441
442                    if should_export {
443                        symbols.push((
444                            ExportedSymbol::DropGlue(ty),
445                            SymbolExportInfo {
446                                level: SymbolExportLevel::Rust,
447                                kind: SymbolExportKind::Text,
448                                used: false,
449                                rustc_std_internal_symbol: false,
450                            },
451                        ));
452                    }
453                }
454                MonoItem::Fn(Instance {
455                    def: InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(_, ty)),
456                    args,
457                }) => {
458                    // A little sanity-check
459                    {
    match (&args.non_erasable_generics().next(),
            &Some(GenericArgKind::Type(ty))) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
460                    symbols.push((
461                        ExportedSymbol::AsyncDropGlueCtorShim(ty),
462                        SymbolExportInfo {
463                            level: SymbolExportLevel::Rust,
464                            kind: SymbolExportKind::Text,
465                            used: false,
466                            rustc_std_internal_symbol: false,
467                        },
468                    ));
469                }
470                MonoItem::Fn(Instance {
471                    def: InstanceKind::Shim(ShimKind::AsyncDropGlue(def, ty)),
472                    args: _,
473                }) => {
474                    symbols.push((
475                        ExportedSymbol::AsyncDropGlue(def, ty),
476                        SymbolExportInfo {
477                            level: SymbolExportLevel::Rust,
478                            kind: SymbolExportKind::Text,
479                            used: false,
480                            rustc_std_internal_symbol: false,
481                        },
482                    ));
483                }
484                _ => {
485                    // Any other symbols don't qualify for sharing
486                }
487            }
488        }
489    }
490
491    // Sort so we get a stable incr. comp. hash.
492    symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
493
494    tcx.arena.alloc_from_iter(symbols)
495}
496
497fn upstream_monomorphizations_provider(
498    tcx: TyCtxt<'_>,
499    (): (),
500) -> DefIdMap<UnordMap<GenericArgsRef<'_>, CrateNum>> {
501    let cnums = tcx.crates(());
502
503    let mut instances: DefIdMap<UnordMap<_, _>> = Default::default();
504
505    let drop_glue_fn_def_id = tcx.lang_items().drop_glue_fn();
506    let async_drop_in_place_fn_def_id = tcx.lang_items().async_drop_in_place_fn();
507
508    for &cnum in cnums.iter() {
509        // It should be possible to compile to build a crate against a conditional dependency then
510        // later link that crate without the conditional dependency, so we cannot use exported
511        // generics from conditional dependencies.
512        // https://github.com/rust-lang/rust/issues/159682
513        if tcx.crate_dep_kind(cnum) == CrateDepKind::Conditional {
514            continue;
515        }
516
517        for (exported_symbol, _) in tcx.exported_generic_symbols(cnum).iter() {
518            let (def_id, args) = match *exported_symbol {
519                ExportedSymbol::Generic(def_id, args) => (def_id, args),
520                ExportedSymbol::DropGlue(ty) => {
521                    if let Some(drop_in_place_fn_def_id) = drop_glue_fn_def_id {
522                        (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
523                    } else {
524                        // `drop_glue` does not exist, don't try to use it.
525                        continue;
526                    }
527                }
528                ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
529                    if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
530                        (async_drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
531                    } else {
532                        continue;
533                    }
534                }
535                ExportedSymbol::AsyncDropGlue(def_id, ty) => (def_id, tcx.mk_args(&[ty.into()])),
536                ExportedSymbol::NonGeneric(..)
537                | ExportedSymbol::ThreadLocalShim(..)
538                | ExportedSymbol::NoDefId(..) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("{0:?}", exported_symbol)));
}unreachable!("{exported_symbol:?}"),
539            };
540
541            let args_map = instances.entry(def_id).or_default();
542
543            match args_map.entry(args) {
544                Occupied(mut e) => {
545                    // If there are multiple monomorphizations available,
546                    // we select one deterministically.
547                    let other_cnum = *e.get();
548                    if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
549                        e.insert(cnum);
550                    }
551                }
552                Vacant(e) => {
553                    e.insert(cnum);
554                }
555            }
556        }
557    }
558
559    instances
560}
561
562fn upstream_monomorphizations_for_provider(
563    tcx: TyCtxt<'_>,
564    def_id: DefId,
565) -> Option<&UnordMap<GenericArgsRef<'_>, CrateNum>> {
566    if !!def_id.is_local() {
    ::core::panicking::panic("assertion failed: !def_id.is_local()")
};assert!(!def_id.is_local());
567    tcx.upstream_monomorphizations(()).get(&def_id)
568}
569
570fn upstream_drop_glue_for_provider<'tcx>(
571    tcx: TyCtxt<'tcx>,
572    args: GenericArgsRef<'tcx>,
573) -> Option<CrateNum> {
574    let def_id = tcx.lang_items().drop_glue_fn()?;
575    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
576}
577
578fn upstream_async_drop_glue_for_provider<'tcx>(
579    tcx: TyCtxt<'tcx>,
580    args: GenericArgsRef<'tcx>,
581) -> Option<CrateNum> {
582    let def_id = tcx.lang_items().async_drop_in_place_fn()?;
583    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
584}
585
586fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
587    !tcx.reachable_set(()).contains(&def_id)
588}
589
590pub(crate) fn provide(providers: &mut Providers) {
591    providers.queries.reachable_non_generics = reachable_non_generics_provider;
592    providers.queries.is_reachable_non_generic = is_reachable_non_generic_provider_local;
593    providers.queries.exported_non_generic_symbols = exported_non_generic_symbols_provider_local;
594    providers.queries.exported_generic_symbols = exported_generic_symbols_provider_local;
595    providers.queries.upstream_monomorphizations = upstream_monomorphizations_provider;
596    providers.queries.is_unreachable_local_definition = is_unreachable_local_definition_provider;
597    providers.queries.upstream_drop_glue_for = upstream_drop_glue_for_provider;
598    providers.queries.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
599    providers.queries.wasm_import_module_map = wasm_import_module_map;
600    providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
601    providers.extern_queries.upstream_monomorphizations_for =
602        upstream_monomorphizations_for_provider;
603}
604
605pub(crate) fn allocator_shim_symbols(
606    tcx: TyCtxt<'_>,
607    kind: AllocatorKind,
608) -> impl Iterator<Item = (String, SymbolExportKind)> {
609    allocator_shim_contents(tcx, kind)
610        .into_iter()
611        .map(move |method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
612        .chain([mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE)])
613        .map(move |symbol_name| {
614            let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
615
616            (
617                symbol_export::exporting_symbol_name_for_instance_in_crate(
618                    tcx,
619                    exported_symbol,
620                    LOCAL_CRATE,
621                ),
622                SymbolExportKind::Text,
623            )
624        })
625}
626
627fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
628    // We export anything that's not mangled at the "C" layer as it probably has
629    // to do with ABI concerns. We do not, however, apply such treatment to
630    // special symbols in the standard library for various plumbing between
631    // core/std/allocators/etc. For example symbols used to hook up allocation
632    // are not considered for export
633    let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
634    let is_extern = codegen_fn_attrs.contains_extern_indicator();
635    let std_internal =
636        codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
637    let eii = codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
638
639    if is_extern && !std_internal && !eii {
640        let target = &tcx.sess.target.llvm_target;
641        // WebAssembly cannot export data symbols, so reduce their export level
642        // FIXME(jdonszelmann) don't do a substring match here.
643        if target.contains("emscripten") {
644            if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
645                return SymbolExportLevel::Rust;
646            }
647        }
648
649        SymbolExportLevel::C
650    } else {
651        SymbolExportLevel::Rust
652    }
653}
654
655/// This is the symbol name of the given instance instantiated in a specific crate.
656pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
657    tcx: TyCtxt<'tcx>,
658    symbol: ExportedSymbol<'tcx>,
659    instantiating_crate: CrateNum,
660) -> String {
661    // If this is something instantiated in the local crate then we might
662    // already have cached the name as a query result.
663    if instantiating_crate == LOCAL_CRATE {
664        return symbol.symbol_name_for_local_instance(tcx).to_string();
665    }
666
667    // This is something instantiated in an upstream crate, so we have to use
668    // the slower (because uncached) version of computing the symbol name.
669    match symbol {
670        ExportedSymbol::NonGeneric(def_id) => {
671            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
672                tcx,
673                Instance::mono(tcx, def_id),
674                instantiating_crate,
675            )
676        }
677        ExportedSymbol::Generic(def_id, args) => {
678            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
679                tcx,
680                Instance::new_raw(def_id, args),
681                instantiating_crate,
682            )
683        }
684        ExportedSymbol::ThreadLocalShim(def_id) => {
685            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
686                tcx,
687                ty::Instance {
688                    def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
689                    args: ty::GenericArgs::empty(),
690                },
691                instantiating_crate,
692            )
693        }
694        ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
695            tcx,
696            Instance::resolve_drop_glue(tcx, ty),
697            instantiating_crate,
698        ),
699        ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
700            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
701                tcx,
702                Instance::resolve_async_drop_in_place(tcx, ty),
703                instantiating_crate,
704            )
705        }
706        ExportedSymbol::AsyncDropGlue(def_id, ty) => {
707            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
708                tcx,
709                Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
710                instantiating_crate,
711            )
712        }
713        ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
714    }
715}
716
717fn calling_convention_for_symbol<'tcx>(
718    tcx: TyCtxt<'tcx>,
719    symbol: ExportedSymbol<'tcx>,
720) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
721    let instance = match symbol {
722        ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
723            if tcx.is_static(def_id) =>
724        {
725            None
726        }
727        ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
728        ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
729        // DropGlue always use the Rust calling convention and thus follow the target's default
730        // symbol decoration scheme.
731        ExportedSymbol::DropGlue(..) => None,
732        // AsyncDropGlueCtorShim always use the Rust calling convention and thus follow the
733        // target's default symbol decoration scheme.
734        ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
735        ExportedSymbol::AsyncDropGlue(..) => None,
736        // NoDefId always follow the target's default symbol decoration scheme.
737        ExportedSymbol::NoDefId(..) => None,
738        // ThreadLocalShim always follow the target's default symbol decoration scheme.
739        ExportedSymbol::ThreadLocalShim(..) => None,
740    };
741
742    instance
743        .map(|i| {
744            tcx.fn_abi_of_instance(
745                ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
746            )
747            .unwrap_or_else(|_| bug_impl(None, format_args!("fn_abi_of_instance({0:?}) failed", i),
    Location::caller())bug!("fn_abi_of_instance({i:?}) failed"))
748        })
749        .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
750        // FIXME(workingjubilee): why don't we know the convention here?
751        .unwrap_or((CanonAbi::Rust, &[]))
752}
753
754/// This is the symbol name of the given instance as seen by the linker.
755///
756/// On 32-bit Windows symbols are decorated according to their calling conventions.
757pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
758    tcx: TyCtxt<'tcx>,
759    symbol: ExportedSymbol<'tcx>,
760    export_kind: SymbolExportKind,
761    instantiating_crate: CrateNum,
762) -> String {
763    let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
764
765    // thread local will not be a function call,
766    // so it is safe to return before windows symbol decoration check.
767    if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
768        return name;
769    }
770
771    let target = &tcx.sess.target;
772    if !target.is_like_windows {
773        // Mach-O has a global "_" suffix and `object` crate will handle it.
774        // ELF does not have any symbol decorations.
775        return undecorated;
776    }
777
778    let prefix = match target.arch {
779        Arch::X86 => Some('_'),
780        Arch::X86_64 => None,
781        // Only functions are decorated for arm64ec.
782        Arch::Arm64EC if export_kind == SymbolExportKind::Text => Some('#'),
783        // Only x86/64 and arm64ec use symbol decorations.
784        _ => return undecorated,
785    };
786
787    let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
788
789    // Decorate symbols with prefixes, suffixes and total number of bytes of arguments.
790    // Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170
791    let (prefix, suffix) = match callconv {
792        CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
793        CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
794        CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
795        _ => {
796            if let Some(prefix) = prefix {
797                undecorated.insert(0, prefix);
798            }
799            return undecorated;
800        }
801    };
802
803    let args_in_bytes: u64 = args
804        .iter()
805        .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
806        .sum();
807    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}{3}", prefix, undecorated,
                suffix, args_in_bytes))
    })format!("{prefix}{undecorated}{suffix}{args_in_bytes}")
808}
809
810pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
811    tcx: TyCtxt<'tcx>,
812    symbol: ExportedSymbol<'tcx>,
813    cnum: CrateNum,
814) -> String {
815    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
816    maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
817}
818
819/// On amdhsa, `gpu-kernel` functions have an associated metadata object with a `.kd` suffix.
820/// Add it to the symbols list for all kernel functions, so that it is exported in the linked
821/// object.
822pub(crate) fn extend_exported_symbols<'tcx>(
823    symbols: &mut Vec<SymbolExport>,
824    tcx: TyCtxt<'tcx>,
825    symbol: ExportedSymbol<'tcx>,
826    instantiating_crate: CrateNum,
827) {
828    let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
829
830    if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != Os::AmdHsa {
831        return;
832    }
833
834    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
835
836    // Add the symbol for the kernel descriptor (with .kd suffix)
837    // Per https://llvm.org/docs/AMDGPUUsage.html#symbols these will always be `STT_OBJECT` so
838    // export as data.
839    symbols.push(SymbolExport::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.kd", undecorated))
    })format!("{undecorated}.kd"), SymbolExportKind::Data));
840}
841
842fn maybe_emutls_symbol_name<'tcx>(
843    tcx: TyCtxt<'tcx>,
844    symbol: ExportedSymbol<'tcx>,
845    undecorated: &str,
846) -> Option<String> {
847    if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.tls_model() {
    TlsModel::Emulated => true,
    _ => false,
}matches!(tcx.sess.tls_model(), TlsModel::Emulated)
848        && let ExportedSymbol::NonGeneric(def_id) = symbol
849        && tcx.is_thread_local_static(def_id)
850    {
851        // When using emutls, LLVM will add the `__emutls_v.` prefix to thread local symbols,
852        // and exported symbol name need to match this.
853        Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__emutls_v.{0}", undecorated))
    })format!("__emutls_v.{undecorated}"))
854    } else {
855        None
856    }
857}
858
859fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
860    // Build up a map from DefId to a `NativeLib` structure, where
861    // `NativeLib` internally contains information about
862    // `#[link(wasm_import_module = "...")]` for example.
863    let native_libs = tcx.native_libraries(cnum);
864
865    let def_id_to_native_lib = native_libs
866        .iter()
867        .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
868        .collect::<DefIdMap<_>>();
869
870    let mut ret = DefIdMap::default();
871    for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
872        let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
873        let Some(module) = module else { continue };
874        ret.extend(lib.foreign_items.iter().map(|id| {
875            {
    match (&id.krate, &cnum) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(id.krate, cnum);
876            (*id, module.to_string())
877        }));
878    }
879
880    ret
881}
882
883pub fn escape_symbol_name(tcx: TyCtxt<'_>, symbol: &str, span: Span) -> String {
884    // https://github.com/llvm/llvm-project/blob/a55fbab0cffc9b4af497b9e4f187b61143743e06/llvm/lib/MC/MCSymbol.cpp
885    use rustc_target::spec::{Arch, BinaryFormat};
886    if !symbol.is_empty()
887        && symbol.chars().all(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
    '0'..='9' | 'A'..='Z' | 'a'..='z' | '_' | '$' | '.' => true,
    _ => false,
}matches!(c, '0'..='9' | 'A'..='Z' | 'a'..='z' | '_' | '$' | '.'))
888    {
889        return symbol.to_string();
890    }
891    if tcx.sess.target.binary_format == BinaryFormat::Xcoff {
892        tcx.sess.dcx().span_fatal(
893            span,
894            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("symbol escaping is not supported for the binary format {0}",
                tcx.sess.target.binary_format))
    })format!(
895                "symbol escaping is not supported for the binary format {}",
896                tcx.sess.target.binary_format
897            ),
898        );
899    }
900    if tcx.sess.target.arch == Arch::Nvptx64 {
901        tcx.sess.dcx().span_fatal(
902            span,
903            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("symbol escaping is not supported for the architecture {0}",
                tcx.sess.target.arch))
    })format!(
904                "symbol escaping is not supported for the architecture {}",
905                tcx.sess.target.arch
906            ),
907        );
908    }
909    let mut escaped_symbol = String::new();
910    escaped_symbol.push('\"');
911    for c in symbol.chars() {
912        match c {
913            '\n' => escaped_symbol.push_str("\\\n"),
914            '"' => escaped_symbol.push_str("\\\""),
915            '\\' => escaped_symbol.push_str("\\\\"),
916            c => escaped_symbol.push(c),
917        }
918    }
919    escaped_symbol.push('\"');
920    escaped_symbol
921}