]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/base.rs
Auto merge of #79607 - DrMeepster:maybe_uninit_write_slice, r=m-ou-se
[rust.git] / compiler / rustc_codegen_llvm / src / base.rs
1 //! Codegen the completed AST to the LLVM IR.
2 //!
3 //! Some functions here, such as codegen_block and codegen_expr, return a value --
4 //! the result of the codegen to LLVM -- while others, such as codegen_fn
5 //! and mono_item, are called only for the side effect of adding a
6 //! particular definition to the LLVM IR output we're producing.
7 //!
8 //! Hopefully useful general knowledge about codegen:
9 //!
10 //! * There's no way to find out the `Ty` type of a Value. Doing so
11 //!   would be "trying to get the eggs out of an omelette" (credit:
12 //!   pcwalton). You can, instead, find out its `llvm::Type` by calling `val_ty`,
13 //!   but one `llvm::Type` corresponds to many `Ty`s; for instance, `tup(int, int,
14 //!   int)` and `rec(x=int, y=int, z=int)` will have the same `llvm::Type`.
15
16 use super::ModuleLlvm;
17
18 use crate::attributes;
19 use crate::builder::Builder;
20 use crate::common;
21 use crate::context::CodegenCx;
22 use crate::llvm;
23 use crate::metadata;
24 use crate::value::Value;
25
26 use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
27 use rustc_codegen_ssa::mono_item::MonoItemExt;
28 use rustc_codegen_ssa::traits::*;
29 use rustc_codegen_ssa::{ModuleCodegen, ModuleKind};
30 use rustc_data_structures::small_c_str::SmallCStr;
31 use rustc_middle::dep_graph;
32 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
33 use rustc_middle::middle::cstore::EncodedMetadata;
34 use rustc_middle::middle::exported_symbols;
35 use rustc_middle::mir::mono::{Linkage, Visibility};
36 use rustc_middle::ty::TyCtxt;
37 use rustc_session::config::{DebugInfo, SanitizerSet};
38 use rustc_span::symbol::Symbol;
39
40 use std::ffi::CString;
41 use std::time::Instant;
42
43 pub fn write_compressed_metadata<'tcx>(
44     tcx: TyCtxt<'tcx>,
45     metadata: &EncodedMetadata,
46     llvm_module: &mut ModuleLlvm,
47 ) {
48     use snap::write::FrameEncoder;
49     use std::io::Write;
50
51     let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
52     let mut compressed = tcx.metadata_encoding_version();
53     FrameEncoder::new(&mut compressed).write_all(&metadata.raw_data).unwrap();
54
55     let llmeta = common::bytes_in_context(metadata_llcx, &compressed);
56     let llconst = common::struct_in_context(metadata_llcx, &[llmeta], false);
57     let name = exported_symbols::metadata_symbol_name(tcx);
58     let buf = CString::new(name).unwrap();
59     let llglobal =
60         unsafe { llvm::LLVMAddGlobal(metadata_llmod, common::val_ty(llconst), buf.as_ptr()) };
61     unsafe {
62         llvm::LLVMSetInitializer(llglobal, llconst);
63         let section_name = metadata::metadata_section_name(&tcx.sess.target);
64         let name = SmallCStr::new(section_name);
65         llvm::LLVMSetSection(llglobal, name.as_ptr());
66
67         // Also generate a .section directive to force no
68         // flags, at least for ELF outputs, so that the
69         // metadata doesn't get loaded into memory.
70         let directive = format!(".section {}", section_name);
71         llvm::LLVMSetModuleInlineAsm2(metadata_llmod, directive.as_ptr().cast(), directive.len())
72     }
73 }
74
75 pub struct ValueIter<'ll> {
76     cur: Option<&'ll Value>,
77     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
78 }
79
80 impl Iterator for ValueIter<'ll> {
81     type Item = &'ll Value;
82
83     fn next(&mut self) -> Option<&'ll Value> {
84         let old = self.cur;
85         if let Some(old) = old {
86             self.cur = unsafe { (self.step)(old) };
87         }
88         old
89     }
90 }
91
92 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
93     unsafe { ValueIter { cur: llvm::LLVMGetFirstGlobal(llmod), step: llvm::LLVMGetNextGlobal } }
94 }
95
96 pub fn compile_codegen_unit(
97     tcx: TyCtxt<'tcx>,
98     cgu_name: Symbol,
99 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
100     let start_time = Instant::now();
101
102     let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
103     let (module, _) =
104         tcx.dep_graph.with_task(dep_node, tcx, cgu_name, module_codegen, dep_graph::hash_result);
105     let time_to_codegen = start_time.elapsed();
106
107     // We assume that the cost to run LLVM on a CGU is proportional to
108     // the time we needed for codegenning it.
109     let cost = time_to_codegen.as_nanos() as u64;
110
111     fn module_codegen(tcx: TyCtxt<'_>, cgu_name: Symbol) -> ModuleCodegen<ModuleLlvm> {
112         let cgu = tcx.codegen_unit(cgu_name);
113         let _prof_timer = tcx.prof.generic_activity_with_args(
114             "codegen_module",
115             &[cgu_name.to_string(), cgu.size_estimate().to_string()],
116         );
117         // Instantiate monomorphizations without filling out definitions yet...
118         let llvm_module = ModuleLlvm::new(tcx, &cgu_name.as_str());
119         {
120             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
121             let mono_items = cx.codegen_unit.items_in_deterministic_order(cx.tcx);
122             for &(mono_item, (linkage, visibility)) in &mono_items {
123                 mono_item.predefine::<Builder<'_, '_, '_>>(&cx, linkage, visibility);
124             }
125
126             // ... and now that we have everything pre-defined, fill out those definitions.
127             for &(mono_item, _) in &mono_items {
128                 mono_item.define::<Builder<'_, '_, '_>>(&cx);
129             }
130
131             // If this codegen unit contains the main function, also create the
132             // wrapper here
133             if let Some(entry) = maybe_create_entry_wrapper::<Builder<'_, '_, '_>>(&cx) {
134                 attributes::sanitize(&cx, SanitizerSet::empty(), entry);
135             }
136
137             // Run replace-all-uses-with for statics that need it
138             for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
139                 unsafe {
140                     let bitcast = llvm::LLVMConstPointerCast(new_g, cx.val_ty(old_g));
141                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
142                     llvm::LLVMDeleteGlobal(old_g);
143                 }
144             }
145
146             // Finalize code coverage by injecting the coverage map. Note, the coverage map will
147             // also be added to the `llvm.used` variable, created next.
148             if cx.sess().opts.debugging_opts.instrument_coverage {
149                 cx.coverageinfo_finalize();
150             }
151
152             // Create the llvm.used variable
153             // This variable has type [N x i8*] and is stored in the llvm.metadata section
154             if !cx.used_statics().borrow().is_empty() {
155                 cx.create_used_variable()
156             }
157
158             // Finalize debuginfo
159             if cx.sess().opts.debuginfo != DebugInfo::None {
160                 cx.debuginfo_finalize();
161             }
162         }
163
164         ModuleCodegen {
165             name: cgu_name.to_string(),
166             module_llvm: llvm_module,
167             kind: ModuleKind::Regular,
168         }
169     }
170
171     (module, cost)
172 }
173
174 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
175     let sect = match attrs.link_section {
176         Some(name) => name,
177         None => return,
178     };
179     unsafe {
180         let buf = SmallCStr::new(&sect.as_str());
181         llvm::LLVMSetSection(llval, buf.as_ptr());
182     }
183 }
184
185 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
186     match linkage {
187         Linkage::External => llvm::Linkage::ExternalLinkage,
188         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
189         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
190         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
191         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
192         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
193         Linkage::Appending => llvm::Linkage::AppendingLinkage,
194         Linkage::Internal => llvm::Linkage::InternalLinkage,
195         Linkage::Private => llvm::Linkage::PrivateLinkage,
196         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
197         Linkage::Common => llvm::Linkage::CommonLinkage,
198     }
199 }
200
201 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
202     match linkage {
203         Visibility::Default => llvm::Visibility::Default,
204         Visibility::Hidden => llvm::Visibility::Hidden,
205         Visibility::Protected => llvm::Visibility::Protected,
206     }
207 }