]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/base.rs
Rollup merge of #90930 - Nilstrieb:fix-non-const-value-ice, r=estebank
[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`]: common::val_ty
13
14 use super::ModuleLlvm;
15
16 use crate::attributes;
17 use crate::builder::Builder;
18 use crate::common;
19 use crate::context::CodegenCx;
20 use crate::llvm;
21 use crate::value::Value;
22
23 use rustc_codegen_ssa::base::maybe_create_entry_wrapper;
24 use rustc_codegen_ssa::mono_item::MonoItemExt;
25 use rustc_codegen_ssa::traits::*;
26 use rustc_codegen_ssa::{ModuleCodegen, ModuleKind};
27 use rustc_data_structures::small_c_str::SmallCStr;
28 use rustc_metadata::EncodedMetadata;
29 use rustc_middle::dep_graph;
30 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
31 use rustc_middle::middle::exported_symbols;
32 use rustc_middle::mir::mono::{Linkage, Visibility};
33 use rustc_middle::ty::TyCtxt;
34 use rustc_session::config::DebugInfo;
35 use rustc_span::symbol::Symbol;
36 use rustc_target::spec::SanitizerSet;
37
38 use std::ffi::CString;
39 use std::time::Instant;
40
41 pub fn write_compressed_metadata<'tcx>(
42     tcx: TyCtxt<'tcx>,
43     metadata: &EncodedMetadata,
44     llvm_module: &mut ModuleLlvm,
45 ) {
46     use snap::write::FrameEncoder;
47     use std::io::Write;
48
49     // Historical note:
50     //
51     // When using link.exe it was seen that the section name `.note.rustc`
52     // was getting shortened to `.note.ru`, and according to the PE and COFF
53     // specification:
54     //
55     // > Executable images do not use a string table and do not support
56     // > section names longer than 8 characters
57     //
58     // https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
59     //
60     // As a result, we choose a slightly shorter name! As to why
61     // `.note.rustc` works on MinGW, see
62     // https://github.com/llvm/llvm-project/blob/llvmorg-12.0.0/lld/COFF/Writer.cpp#L1190-L1197
63     let section_name = if tcx.sess.target.is_like_osx { "__DATA,.rustc" } else { ".rustc" };
64
65     let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
66     let mut compressed = rustc_metadata::METADATA_HEADER.to_vec();
67     FrameEncoder::new(&mut compressed).write_all(metadata.raw_data()).unwrap();
68
69     let llmeta = common::bytes_in_context(metadata_llcx, &compressed);
70     let llconst = common::struct_in_context(metadata_llcx, &[llmeta], false);
71     let name = exported_symbols::metadata_symbol_name(tcx);
72     let buf = CString::new(name).unwrap();
73     let llglobal =
74         unsafe { llvm::LLVMAddGlobal(metadata_llmod, common::val_ty(llconst), buf.as_ptr()) };
75     unsafe {
76         llvm::LLVMSetInitializer(llglobal, llconst);
77         let name = SmallCStr::new(section_name);
78         llvm::LLVMSetSection(llglobal, name.as_ptr());
79
80         // Also generate a .section directive to force no
81         // flags, at least for ELF outputs, so that the
82         // metadata doesn't get loaded into memory.
83         let directive = format!(".section {}", section_name);
84         llvm::LLVMSetModuleInlineAsm2(metadata_llmod, directive.as_ptr().cast(), directive.len())
85     }
86 }
87
88 pub struct ValueIter<'ll> {
89     cur: Option<&'ll Value>,
90     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
91 }
92
93 impl Iterator for ValueIter<'ll> {
94     type Item = &'ll Value;
95
96     fn next(&mut self) -> Option<&'ll Value> {
97         let old = self.cur;
98         if let Some(old) = old {
99             self.cur = unsafe { (self.step)(old) };
100         }
101         old
102     }
103 }
104
105 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
106     unsafe { ValueIter { cur: llvm::LLVMGetFirstGlobal(llmod), step: llvm::LLVMGetNextGlobal } }
107 }
108
109 pub fn compile_codegen_unit(
110     tcx: TyCtxt<'tcx>,
111     cgu_name: Symbol,
112 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
113     let start_time = Instant::now();
114
115     let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
116     let (module, _) = tcx.dep_graph.with_task(
117         dep_node,
118         tcx,
119         cgu_name,
120         module_codegen,
121         Some(dep_graph::hash_result),
122     );
123     let time_to_codegen = start_time.elapsed();
124
125     // We assume that the cost to run LLVM on a CGU is proportional to
126     // the time we needed for codegenning it.
127     let cost = time_to_codegen.as_nanos() as u64;
128
129     fn module_codegen(tcx: TyCtxt<'_>, cgu_name: Symbol) -> ModuleCodegen<ModuleLlvm> {
130         let cgu = tcx.codegen_unit(cgu_name);
131         let _prof_timer = tcx.prof.generic_activity_with_args(
132             "codegen_module",
133             &[cgu_name.to_string(), cgu.size_estimate().to_string()],
134         );
135         // Instantiate monomorphizations without filling out definitions yet...
136         let llvm_module = ModuleLlvm::new(tcx, &cgu_name.as_str());
137         {
138             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
139             let mono_items = cx.codegen_unit.items_in_deterministic_order(cx.tcx);
140             for &(mono_item, (linkage, visibility)) in &mono_items {
141                 mono_item.predefine::<Builder<'_, '_, '_>>(&cx, linkage, visibility);
142             }
143
144             // ... and now that we have everything pre-defined, fill out those definitions.
145             for &(mono_item, _) in &mono_items {
146                 mono_item.define::<Builder<'_, '_, '_>>(&cx);
147             }
148
149             // If this codegen unit contains the main function, also create the
150             // wrapper here
151             if let Some(entry) = maybe_create_entry_wrapper::<Builder<'_, '_, '_>>(&cx) {
152                 attributes::sanitize(&cx, SanitizerSet::empty(), entry);
153             }
154
155             // Run replace-all-uses-with for statics that need it
156             for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
157                 unsafe {
158                     let bitcast = llvm::LLVMConstPointerCast(new_g, cx.val_ty(old_g));
159                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
160                     llvm::LLVMDeleteGlobal(old_g);
161                 }
162             }
163
164             // Finalize code coverage by injecting the coverage map. Note, the coverage map will
165             // also be added to the `llvm.compiler.used` variable, created next.
166             if cx.sess().instrument_coverage() {
167                 cx.coverageinfo_finalize();
168             }
169
170             // Create the llvm.used and llvm.compiler.used variables.
171             if !cx.used_statics().borrow().is_empty() {
172                 cx.create_used_variable()
173             }
174             if !cx.compiler_used_statics().borrow().is_empty() {
175                 cx.create_compiler_used_variable()
176             }
177
178             // Finalize debuginfo
179             if cx.sess().opts.debuginfo != DebugInfo::None {
180                 cx.debuginfo_finalize();
181             }
182         }
183
184         ModuleCodegen {
185             name: cgu_name.to_string(),
186             module_llvm: llvm_module,
187             kind: ModuleKind::Regular,
188         }
189     }
190
191     (module, cost)
192 }
193
194 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
195     let sect = match attrs.link_section {
196         Some(name) => name,
197         None => return,
198     };
199     unsafe {
200         let buf = SmallCStr::new(&sect.as_str());
201         llvm::LLVMSetSection(llval, buf.as_ptr());
202     }
203 }
204
205 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
206     match linkage {
207         Linkage::External => llvm::Linkage::ExternalLinkage,
208         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
209         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
210         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
211         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
212         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
213         Linkage::Appending => llvm::Linkage::AppendingLinkage,
214         Linkage::Internal => llvm::Linkage::InternalLinkage,
215         Linkage::Private => llvm::Linkage::PrivateLinkage,
216         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
217         Linkage::Common => llvm::Linkage::CommonLinkage,
218     }
219 }
220
221 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
222     match linkage {
223         Visibility::Default => llvm::Visibility::Default,
224         Visibility::Hidden => llvm::Visibility::Hidden,
225         Visibility::Protected => llvm::Visibility::Protected,
226     }
227 }