]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/base.rs
Rollup merge of #92642 - avborhanian:master, r=Dylan-DPC
[rust.git] / compiler / rustc_codegen_llvm / src / base.rs
1 //! Codegen the MIR to the LLVM IR.
2 //!
3 //! Hopefully useful general knowledge about codegen:
4 //!
5 //! * There's no way to find out the [`Ty`] type of a [`Value`]. Doing so
6 //!   would be "trying to get the eggs out of an omelette" (credit:
7 //!   pcwalton). You can, instead, find out its [`llvm::Type`] by calling [`val_ty`],
8 //!   but one [`llvm::Type`] corresponds to many [`Ty`]s; for instance, `tup(int, int,
9 //!   int)` and `rec(x=int, y=int, z=int)` will have the same [`llvm::Type`].
10 //!
11 //! [`Ty`]: rustc_middle::ty::Ty
12 //! [`val_ty`]: crate::common::val_ty
13
14 use super::ModuleLlvm;
15
16 use crate::attributes;
17 use crate::builder::Builder;
18 use crate::context::CodegenCx;
19 use crate::llvm;
20 use crate::value::Value;
21
22 use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
23 use rustc_codegen_ssa::mono_item::MonoItemExt;
24 use rustc_codegen_ssa::traits::*;
25 use rustc_codegen_ssa::{ModuleCodegen, ModuleKind};
26 use rustc_data_structures::small_c_str::SmallCStr;
27 use rustc_middle::dep_graph;
28 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
29 use rustc_middle::mir::mono::{Linkage, Visibility};
30 use rustc_middle::ty::TyCtxt;
31 use rustc_session::config::DebugInfo;
32 use rustc_span::symbol::Symbol;
33 use rustc_target::spec::SanitizerSet;
34
35 use std::time::Instant;
36
37 pub struct ValueIter<'ll> {
38     cur: Option<&'ll Value>,
39     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
40 }
41
42 impl<'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
54 pub fn iter_globals(llmod: &llvm::Module) -> ValueIter<'_> {
55     unsafe { ValueIter { cur: llvm::LLVMGetFirstGlobal(llmod), step: llvm::LLVMGetNextGlobal } }
56 }
57
58 pub fn compile_codegen_unit(tcx: TyCtxt<'_>, cgu_name: Symbol) -> (ModuleCodegen<ModuleLlvm>, u64) {
59     let start_time = Instant::now();
60
61     let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
62     let (module, _) = tcx.dep_graph.with_task(
63         dep_node,
64         tcx,
65         cgu_name,
66         module_codegen,
67         Some(dep_graph::hash_result),
68     );
69     let time_to_codegen = start_time.elapsed();
70
71     // We assume that the cost to run LLVM on a CGU is proportional to
72     // the time we needed for codegenning it.
73     let cost = time_to_codegen.as_nanos() as u64;
74
75     fn module_codegen(tcx: TyCtxt<'_>, cgu_name: Symbol) -> ModuleCodegen<ModuleLlvm> {
76         let cgu = tcx.codegen_unit(cgu_name);
77         let _prof_timer = tcx.prof.generic_activity_with_args(
78             "codegen_module",
79             &[cgu_name.to_string(), cgu.size_estimate().to_string()],
80         );
81         // Instantiate monomorphizations without filling out definitions yet...
82         let llvm_module = ModuleLlvm::new(tcx, cgu_name.as_str());
83         {
84             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
85             let mono_items = cx.codegen_unit.items_in_deterministic_order(cx.tcx);
86             for &(mono_item, (linkage, visibility)) in &mono_items {
87                 mono_item.predefine::<Builder<'_, '_, '_>>(&cx, linkage, visibility);
88             }
89
90             // ... and now that we have everything pre-defined, fill out those definitions.
91             for &(mono_item, _) in &mono_items {
92                 mono_item.define::<Builder<'_, '_, '_>>(&cx);
93             }
94
95             // If this codegen unit contains the main function, also create the
96             // wrapper here
97             if let Some(entry) = maybe_create_entry_wrapper::<Builder<'_, '_, '_>>(&cx) {
98                 let attrs = attributes::sanitize_attrs(&cx, SanitizerSet::empty());
99                 attributes::apply_to_llfn(entry, llvm::AttributePlace::Function, &attrs);
100             }
101
102             // Run replace-all-uses-with for statics that need it
103             for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
104                 unsafe {
105                     let bitcast = llvm::LLVMConstPointerCast(new_g, cx.val_ty(old_g));
106                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
107                     llvm::LLVMDeleteGlobal(old_g);
108                 }
109             }
110
111             // Finalize code coverage by injecting the coverage map. Note, the coverage map will
112             // also be added to the `llvm.compiler.used` variable, created next.
113             if cx.sess().instrument_coverage() {
114                 cx.coverageinfo_finalize();
115             }
116
117             // Create the llvm.used and llvm.compiler.used variables.
118             if !cx.used_statics().borrow().is_empty() {
119                 cx.create_used_variable()
120             }
121             if !cx.compiler_used_statics().borrow().is_empty() {
122                 cx.create_compiler_used_variable()
123             }
124
125             // Finalize debuginfo
126             if cx.sess().opts.debuginfo != DebugInfo::None {
127                 cx.debuginfo_finalize();
128             }
129         }
130
131         ModuleCodegen {
132             name: cgu_name.to_string(),
133             module_llvm: llvm_module,
134             kind: ModuleKind::Regular,
135         }
136     }
137
138     (module, cost)
139 }
140
141 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
142     let Some(sect) = attrs.link_section else { return };
143     unsafe {
144         let buf = SmallCStr::new(sect.as_str());
145         llvm::LLVMSetSection(llval, buf.as_ptr());
146     }
147 }
148
149 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
150     match linkage {
151         Linkage::External => llvm::Linkage::ExternalLinkage,
152         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
153         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
154         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
155         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
156         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
157         Linkage::Appending => llvm::Linkage::AppendingLinkage,
158         Linkage::Internal => llvm::Linkage::InternalLinkage,
159         Linkage::Private => llvm::Linkage::PrivateLinkage,
160         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
161         Linkage::Common => llvm::Linkage::CommonLinkage,
162     }
163 }
164
165 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
166     match linkage {
167         Visibility::Default => llvm::Visibility::Default,
168         Visibility::Hidden => llvm::Visibility::Hidden,
169         Visibility::Protected => llvm::Visibility::Protected,
170     }
171 }