]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/lib.rs
Rollup merge of #103047 - GuillaumeGomez:update-browser-ui-test, r=notriddle
[rust.git] / compiler / rustc_codegen_llvm / src / lib.rs
1 //! The Rust compiler.
2 //!
3 //! # Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(hash_raw_entry)]
9 #![feature(let_chains)]
10 #![feature(extern_types)]
11 #![feature(once_cell)]
12 #![feature(iter_intersperse)]
13 #![recursion_limit = "256"]
14 #![allow(rustc::potential_query_instability)]
15
16 #[macro_use]
17 extern crate rustc_macros;
18 #[macro_use]
19 extern crate tracing;
20
21 use back::write::{create_informational_target_machine, create_target_machine};
22
23 pub use llvm_util::target_features;
24 use rustc_ast::expand::allocator::AllocatorKind;
25 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
26 use rustc_codegen_ssa::back::write::{
27     CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
28 };
29 use rustc_codegen_ssa::traits::*;
30 use rustc_codegen_ssa::ModuleCodegen;
31 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
32 use rustc_data_structures::fx::FxHashMap;
33 use rustc_errors::{ErrorGuaranteed, FatalError, Handler};
34 use rustc_metadata::EncodedMetadata;
35 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
36 use rustc_middle::ty::query::Providers;
37 use rustc_middle::ty::TyCtxt;
38 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
39 use rustc_session::Session;
40 use rustc_span::symbol::Symbol;
41
42 use std::any::Any;
43 use std::ffi::CStr;
44
45 mod back {
46     pub mod archive;
47     pub mod lto;
48     mod profiling;
49     pub mod write;
50 }
51
52 mod abi;
53 mod allocator;
54 mod asm;
55 mod attributes;
56 mod base;
57 mod builder;
58 mod callee;
59 mod common;
60 mod consts;
61 mod context;
62 mod coverageinfo;
63 mod debuginfo;
64 mod declare;
65 mod intrinsic;
66
67 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
68 #[path = "llvm/mod.rs"]
69 mod llvm_;
70 pub mod llvm {
71     pub use super::llvm_::*;
72 }
73
74 mod llvm_util;
75 mod mono_item;
76 mod type_;
77 mod type_of;
78 mod va_arg;
79 mod value;
80
81 #[derive(Clone)]
82 pub struct LlvmCodegenBackend(());
83
84 struct TimeTraceProfiler {
85     enabled: bool,
86 }
87
88 impl TimeTraceProfiler {
89     fn new(enabled: bool) -> Self {
90         if enabled {
91             unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
92         }
93         TimeTraceProfiler { enabled }
94     }
95 }
96
97 impl Drop for TimeTraceProfiler {
98     fn drop(&mut self) {
99         if self.enabled {
100             unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
101         }
102     }
103 }
104
105 impl ExtraBackendMethods for LlvmCodegenBackend {
106     fn codegen_allocator<'tcx>(
107         &self,
108         tcx: TyCtxt<'tcx>,
109         module_name: &str,
110         kind: AllocatorKind,
111         has_alloc_error_handler: bool,
112     ) -> ModuleLlvm {
113         let mut module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
114         unsafe {
115             allocator::codegen(tcx, &mut module_llvm, module_name, kind, has_alloc_error_handler);
116         }
117         module_llvm
118     }
119     fn compile_codegen_unit(
120         &self,
121         tcx: TyCtxt<'_>,
122         cgu_name: Symbol,
123     ) -> (ModuleCodegen<ModuleLlvm>, u64) {
124         base::compile_codegen_unit(tcx, cgu_name)
125     }
126     fn target_machine_factory(
127         &self,
128         sess: &Session,
129         optlvl: OptLevel,
130         target_features: &[String],
131     ) -> TargetMachineFactoryFn<Self> {
132         back::write::target_machine_factory(sess, optlvl, target_features)
133     }
134
135     fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
136     where
137         F: FnOnce() -> T,
138         F: Send + 'static,
139         T: Send + 'static,
140     {
141         std::thread::spawn(move || {
142             let _profiler = TimeTraceProfiler::new(time_trace);
143             f()
144         })
145     }
146
147     fn spawn_named_thread<F, T>(
148         time_trace: bool,
149         name: String,
150         f: F,
151     ) -> std::io::Result<std::thread::JoinHandle<T>>
152     where
153         F: FnOnce() -> T,
154         F: Send + 'static,
155         T: Send + 'static,
156     {
157         std::thread::Builder::new().name(name).spawn(move || {
158             let _profiler = TimeTraceProfiler::new(time_trace);
159             f()
160         })
161     }
162 }
163
164 impl WriteBackendMethods for LlvmCodegenBackend {
165     type Module = ModuleLlvm;
166     type ModuleBuffer = back::lto::ModuleBuffer;
167     type TargetMachine = &'static mut llvm::TargetMachine;
168     type ThinData = back::lto::ThinData;
169     type ThinBuffer = back::lto::ThinBuffer;
170     fn print_pass_timings(&self) {
171         unsafe {
172             llvm::LLVMRustPrintPassTimings();
173         }
174     }
175     fn run_link(
176         cgcx: &CodegenContext<Self>,
177         diag_handler: &Handler,
178         modules: Vec<ModuleCodegen<Self::Module>>,
179     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
180         back::write::link(cgcx, diag_handler, modules)
181     }
182     fn run_fat_lto(
183         cgcx: &CodegenContext<Self>,
184         modules: Vec<FatLTOInput<Self>>,
185         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
186     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
187         back::lto::run_fat(cgcx, modules, cached_modules)
188     }
189     fn run_thin_lto(
190         cgcx: &CodegenContext<Self>,
191         modules: Vec<(String, Self::ThinBuffer)>,
192         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
193     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
194         back::lto::run_thin(cgcx, modules, cached_modules)
195     }
196     unsafe fn optimize(
197         cgcx: &CodegenContext<Self>,
198         diag_handler: &Handler,
199         module: &ModuleCodegen<Self::Module>,
200         config: &ModuleConfig,
201     ) -> Result<(), FatalError> {
202         back::write::optimize(cgcx, diag_handler, module, config)
203     }
204     fn optimize_fat(
205         cgcx: &CodegenContext<Self>,
206         module: &mut ModuleCodegen<Self::Module>,
207     ) -> Result<(), FatalError> {
208         let diag_handler = cgcx.create_diag_handler();
209         back::lto::run_pass_manager(cgcx, &diag_handler, module, false)
210     }
211     unsafe fn optimize_thin(
212         cgcx: &CodegenContext<Self>,
213         thin: ThinModule<Self>,
214     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
215         back::lto::optimize_thin_module(thin, cgcx)
216     }
217     unsafe fn codegen(
218         cgcx: &CodegenContext<Self>,
219         diag_handler: &Handler,
220         module: ModuleCodegen<Self::Module>,
221         config: &ModuleConfig,
222     ) -> Result<CompiledModule, FatalError> {
223         back::write::codegen(cgcx, diag_handler, module, config)
224     }
225     fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
226         back::lto::prepare_thin(module)
227     }
228     fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
229         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
230     }
231 }
232
233 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
234 unsafe impl Sync for LlvmCodegenBackend {}
235
236 impl LlvmCodegenBackend {
237     pub fn new() -> Box<dyn CodegenBackend> {
238         Box::new(LlvmCodegenBackend(()))
239     }
240 }
241
242 impl CodegenBackend for LlvmCodegenBackend {
243     fn init(&self, sess: &Session) {
244         llvm_util::init(sess); // Make sure llvm is inited
245     }
246
247     fn provide(&self, providers: &mut Providers) {
248         providers.global_backend_features =
249             |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
250     }
251
252     fn print(&self, req: PrintRequest, sess: &Session) {
253         match req {
254             PrintRequest::RelocationModels => {
255                 println!("Available relocation models:");
256                 for name in &[
257                     "static",
258                     "pic",
259                     "pie",
260                     "dynamic-no-pic",
261                     "ropi",
262                     "rwpi",
263                     "ropi-rwpi",
264                     "default",
265                 ] {
266                     println!("    {}", name);
267                 }
268                 println!();
269             }
270             PrintRequest::CodeModels => {
271                 println!("Available code models:");
272                 for name in &["tiny", "small", "kernel", "medium", "large"] {
273                     println!("    {}", name);
274                 }
275                 println!();
276             }
277             PrintRequest::TlsModels => {
278                 println!("Available TLS models:");
279                 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
280                     println!("    {}", name);
281                 }
282                 println!();
283             }
284             PrintRequest::StackProtectorStrategies => {
285                 println!(
286                     r#"Available stack protector strategies:
287     all
288         Generate stack canaries in all functions.
289
290     strong
291         Generate stack canaries in a function if it either:
292         - has a local variable of `[T; N]` type, regardless of `T` and `N`
293         - takes the address of a local variable.
294
295           (Note that a local variable being borrowed is not equivalent to its
296           address being taken: e.g. some borrows may be removed by optimization,
297           while by-value argument passing may be implemented with reference to a
298           local stack variable in the ABI.)
299
300     basic
301         Generate stack canaries in functions with local variables of `[T; N]`
302         type, where `T` is byte-sized and `N` >= 8.
303
304     none
305         Do not generate stack canaries.
306 "#
307                 );
308             }
309             req => llvm_util::print(req, sess),
310         }
311     }
312
313     fn print_passes(&self) {
314         llvm_util::print_passes();
315     }
316
317     fn print_version(&self) {
318         llvm_util::print_version();
319     }
320
321     fn target_features(&self, sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
322         target_features(sess, allow_unstable)
323     }
324
325     fn codegen_crate<'tcx>(
326         &self,
327         tcx: TyCtxt<'tcx>,
328         metadata: EncodedMetadata,
329         need_metadata_module: bool,
330     ) -> Box<dyn Any> {
331         Box::new(rustc_codegen_ssa::base::codegen_crate(
332             LlvmCodegenBackend(()),
333             tcx,
334             crate::llvm_util::target_cpu(tcx.sess).to_string(),
335             metadata,
336             need_metadata_module,
337         ))
338     }
339
340     fn join_codegen(
341         &self,
342         ongoing_codegen: Box<dyn Any>,
343         sess: &Session,
344         outputs: &OutputFilenames,
345     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
346         let (codegen_results, work_products) = ongoing_codegen
347             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
348             .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
349             .join(sess);
350
351         sess.time("llvm_dump_timing_file", || {
352             if sess.opts.unstable_opts.llvm_time_trace {
353                 let file_name = outputs.with_extension("llvm_timings.json");
354                 llvm_util::time_trace_profiler_finish(&file_name);
355             }
356         });
357
358         Ok((codegen_results, work_products))
359     }
360
361     fn link(
362         &self,
363         sess: &Session,
364         codegen_results: CodegenResults,
365         outputs: &OutputFilenames,
366     ) -> Result<(), ErrorGuaranteed> {
367         use crate::back::archive::LlvmArchiveBuilderBuilder;
368         use rustc_codegen_ssa::back::link::link_binary;
369
370         // Run the linker on any artifacts that resulted from the LLVM run.
371         // This should produce either a finished executable or library.
372         link_binary(sess, &LlvmArchiveBuilderBuilder, &codegen_results, outputs)
373     }
374 }
375
376 pub struct ModuleLlvm {
377     llcx: &'static mut llvm::Context,
378     llmod_raw: *const llvm::Module,
379     tm: &'static mut llvm::TargetMachine,
380 }
381
382 unsafe impl Send for ModuleLlvm {}
383 unsafe impl Sync for ModuleLlvm {}
384
385 impl ModuleLlvm {
386     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
387         unsafe {
388             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
389             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
390             ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
391         }
392     }
393
394     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
395         unsafe {
396             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
397             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
398             ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
399         }
400     }
401
402     fn parse(
403         cgcx: &CodegenContext<LlvmCodegenBackend>,
404         name: &CStr,
405         buffer: &[u8],
406         handler: &Handler,
407     ) -> Result<Self, FatalError> {
408         unsafe {
409             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
410             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
411             let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
412             let tm = match (cgcx.tm_factory)(tm_factory_config) {
413                 Ok(m) => m,
414                 Err(e) => {
415                     handler.struct_err(&e).emit();
416                     return Err(FatalError);
417                 }
418             };
419
420             Ok(ModuleLlvm { llmod_raw, llcx, tm })
421         }
422     }
423
424     fn llmod(&self) -> &llvm::Module {
425         unsafe { &*self.llmod_raw }
426     }
427 }
428
429 impl Drop for ModuleLlvm {
430     fn drop(&mut self) {
431         unsafe {
432             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
433             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
434         }
435     }
436 }