rustc_codegen_llvm/
mono_item.rs

1use rustc_codegen_ssa::traits::*;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::{DefId, LOCAL_CRATE};
4use rustc_middle::bug;
5use rustc_middle::mir::mono::{Linkage, Visibility};
6use rustc_middle::ty::layout::{FnAbiOf, HasTypingEnv, LayoutOf};
7use rustc_middle::ty::{self, Instance, TypeVisitableExt};
8use rustc_session::config::CrateType;
9use rustc_target::spec::RelocModel;
10use tracing::debug;
11
12use crate::context::CodegenCx;
13use crate::errors::SymbolAlreadyDefined;
14use crate::type_of::LayoutLlvmExt;
15use crate::{base, llvm};
16
17impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
18    fn predefine_static(
19        &self,
20        def_id: DefId,
21        linkage: Linkage,
22        visibility: Visibility,
23        symbol_name: &str,
24    ) {
25        let instance = Instance::mono(self.tcx, def_id);
26        let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
27        // Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
28        // out the llvm type from the actual evaluated initializer.
29        let ty =
30            if nested { self.tcx.types.unit } else { instance.ty(self.tcx, self.typing_env()) };
31        let llty = self.layout_of(ty).llvm_type(self);
32
33        let g = self.define_global(symbol_name, llty).unwrap_or_else(|| {
34            self.sess()
35                .dcx()
36                .emit_fatal(SymbolAlreadyDefined { span: self.tcx.def_span(def_id), symbol_name })
37        });
38
39        llvm::set_linkage(g, base::linkage_to_llvm(linkage));
40        llvm::set_visibility(g, base::visibility_to_llvm(visibility));
41        self.assume_dso_local(g, false);
42
43        self.instances.borrow_mut().insert(instance, g);
44    }
45
46    fn predefine_fn(
47        &self,
48        instance: Instance<'tcx>,
49        linkage: Linkage,
50        visibility: Visibility,
51        symbol_name: &str,
52    ) {
53        assert!(!instance.args.has_infer());
54
55        let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty());
56        let lldecl = self.declare_fn(symbol_name, fn_abi, Some(instance));
57        llvm::set_linkage(lldecl, base::linkage_to_llvm(linkage));
58        let attrs = self.tcx.codegen_fn_attrs(instance.def_id());
59        base::set_link_section(lldecl, attrs);
60        if (linkage == Linkage::LinkOnceODR || linkage == Linkage::WeakODR)
61            && self.tcx.sess.target.supports_comdat()
62        {
63            llvm::SetUniqueComdat(self.llmod, lldecl);
64        }
65
66        // If we're compiling the compiler-builtins crate, e.g., the equivalent of
67        // compiler-rt, then we want to implicitly compile everything with hidden
68        // visibility as we're going to link this object all over the place but
69        // don't want the symbols to get exported.
70        if linkage != Linkage::Internal && self.tcx.is_compiler_builtins(LOCAL_CRATE) {
71            llvm::set_visibility(lldecl, llvm::Visibility::Hidden);
72        } else {
73            llvm::set_visibility(lldecl, base::visibility_to_llvm(visibility));
74        }
75
76        debug!("predefine_fn: instance = {:?}", instance);
77
78        self.assume_dso_local(lldecl, false);
79
80        self.instances.borrow_mut().insert(instance, lldecl);
81    }
82}
83
84impl CodegenCx<'_, '_> {
85    /// Whether a definition or declaration can be assumed to be local to a group of
86    /// libraries that form a single DSO or executable.
87    /// Marks the local as DSO if so.
88    pub(crate) fn assume_dso_local(&self, llval: &llvm::Value, is_declaration: bool) -> bool {
89        let assume = self.should_assume_dso_local(llval, is_declaration);
90        if assume {
91            llvm::set_dso_local(llval);
92        }
93        assume
94    }
95
96    fn should_assume_dso_local(&self, llval: &llvm::Value, is_declaration: bool) -> bool {
97        let linkage = llvm::get_linkage(llval);
98        let visibility = llvm::get_visibility(llval);
99
100        if matches!(linkage, llvm::Linkage::InternalLinkage | llvm::Linkage::PrivateLinkage) {
101            return true;
102        }
103
104        if visibility != llvm::Visibility::Default && linkage != llvm::Linkage::ExternalWeakLinkage
105        {
106            return true;
107        }
108
109        // Symbols from executables can't really be imported any further.
110        let all_exe = self.tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable);
111        let is_declaration_for_linker =
112            is_declaration || linkage == llvm::Linkage::AvailableExternallyLinkage;
113        if all_exe && !is_declaration_for_linker {
114            return true;
115        }
116
117        // PowerPC64 prefers TOC indirection to avoid copy relocations.
118        if matches!(&*self.tcx.sess.target.arch, "powerpc64" | "powerpc64le") {
119            return false;
120        }
121
122        // Match clang by only supporting COFF and ELF for now.
123        if self.tcx.sess.target.is_like_osx {
124            return false;
125        }
126
127        // With pie relocation model calls of functions defined in the translation
128        // unit can use copy relocations.
129        if self.tcx.sess.relocation_model() == RelocModel::Pie && !is_declaration {
130            return true;
131        }
132
133        // Thread-local variables generally don't support copy relocations.
134        let is_thread_local_var = unsafe { llvm::LLVMIsAGlobalVariable(llval) }
135            .is_some_and(|v| unsafe { llvm::LLVMIsThreadLocal(v) } == llvm::True);
136        if is_thread_local_var {
137            return false;
138        }
139
140        // Respect the direct-access-external-data to override default behavior if present.
141        if let Some(direct) = self.tcx.sess.direct_access_external_data() {
142            return direct;
143        }
144
145        // Static relocation model should force copy relocations everywhere.
146        self.tcx.sess.relocation_model() == RelocModel::Static
147    }
148}