rustc_codegen_llvm/
base.rs1use std::time::Instant;
15
16use rustc_codegen_ssa::ModuleCodegen;
17use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
18use rustc_codegen_ssa::mono_item::MonoItemExt;
19use rustc_codegen_ssa::traits::*;
20use rustc_data_structures::small_c_str::SmallCStr;
21use rustc_hir::attrs::Linkage;
22use rustc_middle::dep_graph;
23use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrs, SanitizerFnAttrs};
24use rustc_middle::mono::Visibility;
25use rustc_middle::ty::TyCtxt;
26use rustc_session::config::{DebugInfo, Offload};
27use rustc_span::Symbol;
28use rustc_target::spec::SanitizerSet;
29
30use super::ModuleLlvm;
31use crate::attributes;
32use crate::builder::Builder;
33use crate::builder::gpu_offload::OffloadGlobals;
34use crate::context::CodegenCx;
35use crate::llvm::{self, Value};
36
37pub(crate) struct ValueIter<'ll> {
38 cur: Option<&'ll Value>,
39 step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
40}
41
42impl<'ll> Iterator for ValueIter<'ll> {
43 type Item = &'ll Value;
44
45 fn next(&mut self) -> Option<&'ll Value> {
46 let old = self.cur;
47 if let Some(old) = old {
48 self.cur = unsafe { (self.step)(old) };
49 }
50 old
51 }
52}
53
54pub(crate) fn iter_globals(llmod: &llvm::Module) -> ValueIter<'_> {
55 unsafe { ValueIter { cur: llvm::LLVMGetFirstGlobal(llmod), step: llvm::LLVMGetNextGlobal } }
56}
57
58pub(crate) fn iter_global_aliases(llmod: &llvm::Module) -> ValueIter<'_> {
59 unsafe {
60 ValueIter { cur: llvm::LLVMGetFirstGlobalAlias(llmod), step: llvm::LLVMGetNextGlobalAlias }
61 }
62}
63
64pub(crate) fn compile_codegen_unit(
65 tcx: TyCtxt<'_>,
66 cgu_name: Symbol,
67) -> (ModuleCodegen<ModuleLlvm>, u64) {
68 let start_time = Instant::now();
69
70 let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
71 let (module, _) = tcx.dep_graph.with_task(
72 dep_node,
73 tcx,
74 || module_codegen(tcx, cgu_name),
75 Some(dep_graph::hash_result),
76 );
77 let time_to_codegen = start_time.elapsed();
78
79 let cost = time_to_codegen.as_nanos() as u64;
82
83 fn module_codegen(tcx: TyCtxt<'_>, cgu_name: Symbol) -> ModuleCodegen<ModuleLlvm> {
84 let cgu = tcx.codegen_unit(cgu_name);
85 let _prof_timer =
86 tcx.prof.generic_activity_with_arg_recorder("codegen_module", |recorder| {
87 recorder.record_arg(cgu_name.to_string());
88 recorder.record_arg(cgu.size_estimate().to_string());
89 });
90 let llvm_module = ModuleLlvm::new(tcx, cgu_name.as_str());
92 {
93 let mut cx = CodegenCx::new(tcx, cgu, &llvm_module);
94
95 let has_host_offload = cx
102 .sess()
103 .opts
104 .unstable_opts
105 .offload
106 .iter()
107 .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
Offload::Host(_) | Offload::Test => true,
_ => false,
}matches!(o, Offload::Host(_) | Offload::Test));
108 if has_host_offload && !cx.sess().target.is_like_gpu {
109 cx.offload_globals.replace(Some(OffloadGlobals::declare(&cx)));
110 }
111
112 let mono_items = cx.codegen_unit.items_in_deterministic_order(cx.tcx);
113 for &(mono_item, data) in &mono_items {
114 mono_item.predefine::<Builder<'_, '_, '_>>(
115 &mut cx,
116 cgu_name.as_str(),
117 data.linkage,
118 data.visibility,
119 );
120 }
121
122 for &(mono_item, item_data) in &mono_items {
124 mono_item.define::<Builder<'_, '_, '_>>(&mut cx, cgu_name.as_str(), item_data);
125 }
126
127 if let Some(entry) =
130 maybe_create_entry_wrapper::<Builder<'_, '_, '_>>(&cx, cx.codegen_unit)
131 {
132 let mut attrs = attributes::sanitize_attrs(&cx, tcx, SanitizerFnAttrs::default());
133 if cx.sess().pointer_authentication() {
140 let cfg = cx.sess().pointer_auth_config.as_ref().unwrap();
141 for ptrauth_attr in cfg.fn_attrs() {
142 attrs.push(llvm::CreateAttrString(cx.llcx, ptrauth_attr));
143 }
144 }
145 attributes::apply_to_llfn(entry, llvm::AttributePlace::Function, &attrs);
146 }
147
148 if !cx.objc_classrefs.borrow().is_empty() || !cx.objc_selrefs.borrow().is_empty() {
155 if cx.objc_abi_version() == 1 {
156 cx.define_objc_module_info();
157 }
158 cx.add_objc_module_flags();
159 }
160
161 if cx.sess().pointer_authentication() {
162 let cfg = cx.sess().pointer_auth_config.as_ref().unwrap();
163
164 let aarch64_elf_pauthabi_version =
165 cfg.calculate_pauth_abi_version(&cx.sess().target);
166 if aarch64_elf_pauthabi_version != 0 {
167 cx.add_ptrauth_pauthabi_version_and_platform_flags(
168 aarch64_elf_pauthabi_version,
169 );
170 }
171 if cfg.elf_got {
172 cx.add_ptrauth_elf_got_flag();
173 }
174 if cx.sess().pointer_authentication_functions().is_some() {
175 cx.add_ptrauth_sign_personality_flag();
176 }
177 }
178
179 if cx.sess().instrument_coverage() {
182 cx.coverageinfo_finalize();
183 }
184
185 if !cx.used_statics.is_empty() {
187 cx.create_used_variable_impl(c"llvm.used", &cx.used_statics);
188 }
189
190 {
192 let compiler_used_statics = cx.compiler_used_statics.borrow();
193 if !compiler_used_statics.is_empty() {
194 cx.create_used_variable_impl(c"llvm.compiler.used", &compiler_used_statics);
195 }
196 }
197
198 for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
201 unsafe {
202 llvm::LLVMReplaceAllUsesWith(old_g, new_g);
203 llvm::LLVMDeleteGlobal(old_g);
204 }
205 }
206
207 if cx.sess().opts.debuginfo != DebugInfo::None {
209 cx.debuginfo_finalize();
210 }
211 }
212
213 ModuleCodegen::new_regular(cgu_name.to_string(), llvm_module)
214 }
215
216 (module, cost)
217}
218
219pub(crate) fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
220 let Some(sect) = attrs.link_section else { return };
221 let buf = SmallCStr::new(sect.as_str());
222 llvm::set_section(llval, &buf);
223}
224
225pub(crate) fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
226 match linkage {
227 Linkage::External => llvm::Linkage::ExternalLinkage,
228 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
229 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
230 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
231 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
232 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
233 Linkage::Internal => llvm::Linkage::InternalLinkage,
234 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
235 Linkage::Common => llvm::Linkage::CommonLinkage,
236 }
237}
238
239pub(crate) fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
240 match linkage {
241 Visibility::Default => llvm::Visibility::Default,
242 Visibility::Hidden => llvm::Visibility::Hidden,
243 Visibility::Protected => llvm::Visibility::Protected,
244 }
245}
246
247pub(crate) fn set_variable_sanitizer_attrs(llval: &Value, attrs: &CodegenFnAttrs) {
248 if attrs.sanitizers.disabled.contains(SanitizerSet::ADDRESS)
249 || attrs.sanitizers.disabled.contains(SanitizerSet::KERNELADDRESS)
250 {
251 unsafe { llvm::LLVMRustSetNoSanitizeAddress(llval) };
252 }
253 if attrs.sanitizers.disabled.contains(SanitizerSet::HWADDRESS)
254 || attrs.sanitizers.disabled.contains(SanitizerSet::KERNELHWADDRESS)
255 {
256 unsafe { llvm::LLVMRustSetNoSanitizeHWAddress(llval) };
257 }
258}