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