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