Skip to main content

rustc_codegen_llvm/
mono_item.rs

1use std::ffi::CString;
2
3use rustc_abi::AddressSpace;
4use rustc_codegen_ssa::traits::*;
5use rustc_hir::attrs::Linkage;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE};
8use rustc_middle::bug;
9use rustc_middle::mir::mono::Visibility;
10use rustc_middle::ty::layout::{FnAbiOf, HasTypingEnv, LayoutOf};
11use rustc_middle::ty::{self, Instance, TypeVisitableExt};
12use rustc_session::config::CrateType;
13use rustc_target::spec::{Arch, RelocModel};
14use tracing::debug;
15
16use crate::context::CodegenCx;
17use crate::errors::SymbolAlreadyDefined;
18use crate::type_of::LayoutLlvmExt;
19use crate::{base, llvm};
20
21impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
22    fn predefine_static(
23        &mut self,
24        def_id: DefId,
25        linkage: Linkage,
26        visibility: Visibility,
27        symbol_name: &str,
28    ) {
29        let instance = Instance::mono(self.tcx, def_id);
30        let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
31        // Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
32        // out the llvm type from the actual evaluated initializer.
33        let ty =
34            if nested { self.tcx.types.unit } else { instance.ty(self.tcx, self.typing_env()) };
35        let llty = self.layout_of(ty).llvm_type(self);
36
37        let g = self.define_global(symbol_name, llty).unwrap_or_else(|| {
38            self.sess()
39                .dcx()
40                .emit_fatal(SymbolAlreadyDefined { span: self.tcx.def_span(def_id), symbol_name })
41        });
42
43        llvm::set_linkage(g, base::linkage_to_llvm(linkage));
44        self.set_visibility(g, linkage, visibility);
45
46        self.assume_dso_local(g, false);
47
48        let attrs = self.tcx.codegen_instance_attrs(instance.def);
49        self.add_aliases(g, &attrs.foreign_item_symbol_aliases);
50
51        self.instances.borrow_mut().insert(instance, g);
52    }
53
54    fn predefine_fn(
55        &mut self,
56        instance: Instance<'tcx>,
57        linkage: Linkage,
58        visibility: Visibility,
59        symbol_name: &str,
60    ) {
61        if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
62
63        let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty());
64        let lldecl = self.declare_fn(symbol_name, fn_abi, Some(instance));
65        llvm::set_linkage(lldecl, base::linkage_to_llvm(linkage));
66        let attrs = self.tcx.codegen_instance_attrs(instance.def);
67        base::set_link_section(lldecl, &attrs);
68        if (linkage == Linkage::LinkOnceODR || linkage == Linkage::WeakODR)
69            && self.tcx.sess.target.supports_comdat()
70        {
71            llvm::SetUniqueComdat(self.llmod, lldecl);
72        }
73        self.set_visibility(lldecl, linkage, visibility);
74
75        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/mono_item.rs:75",
                        "rustc_codegen_llvm::mono_item", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/mono_item.rs"),
                        ::tracing_core::__macro_support::Option::Some(75u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::mono_item"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("predefine_fn: instance = {0:?}",
                                                    instance) as &dyn Value))])
            });
    } else { ; }
};debug!("predefine_fn: instance = {:?}", instance);
76
77        self.assume_dso_local(lldecl, false);
78
79        self.add_aliases(lldecl, &attrs.foreign_item_symbol_aliases);
80
81        self.instances.borrow_mut().insert(instance, lldecl);
82    }
83}
84
85impl CodegenCx<'_, '_> {
86    fn add_aliases(&self, aliasee: &llvm::Value, aliases: &[(DefId, Linkage, Visibility)]) {
87        let ty = self.get_type_of_global(aliasee);
88
89        for (alias, linkage, visibility) in aliases {
90            let symbol_name = self.tcx.symbol_name(Instance::mono(self.tcx, *alias));
91
92            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/mono_item.rs:92",
                        "rustc_codegen_llvm::mono_item", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/mono_item.rs"),
                        ::tracing_core::__macro_support::Option::Some(92u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::mono_item"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("ALIAS: {0:?} {1:?} {2:?}",
                                                    alias, linkage, visibility) as &dyn Value))])
            });
    } else { ; }
};tracing::debug!("ALIAS: {alias:?} {linkage:?} {visibility:?}");
93            let lldecl = llvm::add_alias(
94                self.llmod,
95                ty,
96                AddressSpace::ZERO,
97                aliasee,
98                &CString::new(symbol_name.name).unwrap(),
99            );
100
101            llvm::set_visibility(lldecl, base::visibility_to_llvm(*visibility));
102            llvm::set_linkage(lldecl, base::linkage_to_llvm(*linkage));
103        }
104    }
105
106    /// A definition or declaration can be assumed to be local to a group of
107    /// libraries that form a single DSO or executable.
108    /// Marks the local as DSO if so.
109    pub(crate) fn assume_dso_local(&self, llval: &llvm::Value, is_declaration: bool) -> bool {
110        let assume = self.should_assume_dso_local(llval, is_declaration);
111        if assume {
112            llvm::set_dso_local(llval);
113        }
114        assume
115    }
116
117    fn set_visibility(&self, lldecl: &llvm::Value, linkage: Linkage, visibility: Visibility) {
118        // If we're compiling the compiler-builtins crate, i.e., the equivalent of
119        // compiler-rt, then we want to implicitly compile everything with hidden
120        // visibility as we're going to link this object all over the place but
121        // don't want the symbols to get exported.
122        if linkage != Linkage::Internal && self.tcx.is_compiler_builtins(LOCAL_CRATE) {
123            llvm::set_visibility(lldecl, llvm::Visibility::Hidden);
124        } else {
125            llvm::set_visibility(lldecl, base::visibility_to_llvm(visibility));
126        }
127    }
128
129    fn should_assume_dso_local(&self, llval: &llvm::Value, is_declaration: bool) -> bool {
130        let linkage = llvm::get_linkage(llval);
131        let visibility = llvm::get_visibility(llval);
132
133        if #[allow(non_exhaustive_omitted_patterns)] match linkage {
    llvm::Linkage::InternalLinkage | llvm::Linkage::PrivateLinkage => true,
    _ => false,
}matches!(linkage, llvm::Linkage::InternalLinkage | llvm::Linkage::PrivateLinkage) {
134            return true;
135        }
136
137        if visibility != llvm::Visibility::Default && linkage != llvm::Linkage::ExternalWeakLinkage
138        {
139            return true;
140        }
141
142        // Symbols from executables can't really be imported any further.
143        let all_exe = self.tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable);
144        let is_declaration_for_linker =
145            is_declaration || linkage == llvm::Linkage::AvailableExternallyLinkage;
146        if all_exe && !is_declaration_for_linker {
147            return true;
148        }
149
150        // PowerPC64 prefers TOC indirection to avoid copy relocations.
151        if self.tcx.sess.target.arch == Arch::PowerPC64 {
152            return false;
153        }
154
155        // Match clang by only supporting COFF and ELF for now.
156        if self.tcx.sess.target.is_like_darwin {
157            return false;
158        }
159
160        // With pie relocation model, calls of functions defined in the translation
161        // unit can use copy relocations.
162        if self.tcx.sess.relocation_model() == RelocModel::Pie && !is_declaration {
163            return true;
164        }
165
166        // Thread-local variables generally don't support copy relocations.
167        let is_thread_local_var = llvm::LLVMIsAGlobalVariable(llval)
168            .is_some_and(|v| llvm::LLVMIsThreadLocal(v).is_true());
169        if is_thread_local_var {
170            return false;
171        }
172
173        // Respect the direct-access-external-data to override default behavior if present.
174        if let Some(direct) = self.tcx.sess.direct_access_external_data() {
175            return direct;
176        }
177
178        // Static relocation model should force copy relocations everywhere.
179        self.tcx.sess.relocation_model() == RelocModel::Static
180    }
181}