]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/lib.rs
Rollup merge of #102313 - anirudh24seven:update_sleep_ms_doc, r=Mark-Simulacrum
[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     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
135         llvm_util::target_cpu(sess)
136     }
137     fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
138         llvm_util::tune_cpu(sess)
139     }
140
141     fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
142     where
143         F: FnOnce() -> T,
144         F: Send + 'static,
145         T: Send + 'static,
146     {
147         std::thread::spawn(move || {
148             let _profiler = TimeTraceProfiler::new(time_trace);
149             f()
150         })
151     }
152
153     fn spawn_named_thread<F, T>(
154         time_trace: bool,
155         name: String,
156         f: F,
157     ) -> std::io::Result<std::thread::JoinHandle<T>>
158     where
159         F: FnOnce() -> T,
160         F: Send + 'static,
161         T: Send + 'static,
162     {
163         std::thread::Builder::new().name(name).spawn(move || {
164             let _profiler = TimeTraceProfiler::new(time_trace);
165             f()
166         })
167     }
168 }
169
170 impl WriteBackendMethods for LlvmCodegenBackend {
171     type Module = ModuleLlvm;
172     type ModuleBuffer = back::lto::ModuleBuffer;
173     type Context = llvm::Context;
174     type TargetMachine = &'static mut llvm::TargetMachine;
175     type ThinData = back::lto::ThinData;
176     type ThinBuffer = back::lto::ThinBuffer;
177     fn print_pass_timings(&self) {
178         unsafe {
179             llvm::LLVMRustPrintPassTimings();
180         }
181     }
182     fn run_link(
183         cgcx: &CodegenContext<Self>,
184         diag_handler: &Handler,
185         modules: Vec<ModuleCodegen<Self::Module>>,
186     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
187         back::write::link(cgcx, diag_handler, modules)
188     }
189     fn run_fat_lto(
190         cgcx: &CodegenContext<Self>,
191         modules: Vec<FatLTOInput<Self>>,
192         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
193     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
194         back::lto::run_fat(cgcx, modules, cached_modules)
195     }
196     fn run_thin_lto(
197         cgcx: &CodegenContext<Self>,
198         modules: Vec<(String, Self::ThinBuffer)>,
199         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
200     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
201         back::lto::run_thin(cgcx, modules, cached_modules)
202     }
203     unsafe fn optimize(
204         cgcx: &CodegenContext<Self>,
205         diag_handler: &Handler,
206         module: &ModuleCodegen<Self::Module>,
207         config: &ModuleConfig,
208     ) -> Result<(), FatalError> {
209         back::write::optimize(cgcx, diag_handler, module, config)
210     }
211     fn optimize_fat(
212         cgcx: &CodegenContext<Self>,
213         module: &mut ModuleCodegen<Self::Module>,
214     ) -> Result<(), FatalError> {
215         let diag_handler = cgcx.create_diag_handler();
216         back::lto::run_pass_manager(cgcx, &diag_handler, module, false)
217     }
218     unsafe fn optimize_thin(
219         cgcx: &CodegenContext<Self>,
220         thin: ThinModule<Self>,
221     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
222         back::lto::optimize_thin_module(thin, cgcx)
223     }
224     unsafe fn codegen(
225         cgcx: &CodegenContext<Self>,
226         diag_handler: &Handler,
227         module: ModuleCodegen<Self::Module>,
228         config: &ModuleConfig,
229     ) -> Result<CompiledModule, FatalError> {
230         back::write::codegen(cgcx, diag_handler, module, config)
231     }
232     fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
233         back::lto::prepare_thin(module)
234     }
235     fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
236         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
237     }
238 }
239
240 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
241 unsafe impl Sync for LlvmCodegenBackend {}
242
243 impl LlvmCodegenBackend {
244     pub fn new() -> Box<dyn CodegenBackend> {
245         Box::new(LlvmCodegenBackend(()))
246     }
247 }
248
249 impl CodegenBackend for LlvmCodegenBackend {
250     fn init(&self, sess: &Session) {
251         llvm_util::init(sess); // Make sure llvm is inited
252     }
253
254     fn provide(&self, providers: &mut Providers) {
255         providers.global_backend_features =
256             |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
257     }
258
259     fn print(&self, req: PrintRequest, sess: &Session) {
260         match req {
261             PrintRequest::RelocationModels => {
262                 println!("Available relocation models:");
263                 for name in &[
264                     "static",
265                     "pic",
266                     "pie",
267                     "dynamic-no-pic",
268                     "ropi",
269                     "rwpi",
270                     "ropi-rwpi",
271                     "default",
272                 ] {
273                     println!("    {}", name);
274                 }
275                 println!();
276             }
277             PrintRequest::CodeModels => {
278                 println!("Available code models:");
279                 for name in &["tiny", "small", "kernel", "medium", "large"] {
280                     println!("    {}", name);
281                 }
282                 println!();
283             }
284             PrintRequest::TlsModels => {
285                 println!("Available TLS models:");
286                 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
287                     println!("    {}", name);
288                 }
289                 println!();
290             }
291             PrintRequest::StackProtectorStrategies => {
292                 println!(
293                     r#"Available stack protector strategies:
294     all
295         Generate stack canaries in all functions.
296
297     strong
298         Generate stack canaries in a function if it either:
299         - has a local variable of `[T; N]` type, regardless of `T` and `N`
300         - takes the address of a local variable.
301
302           (Note that a local variable being borrowed is not equivalent to its
303           address being taken: e.g. some borrows may be removed by optimization,
304           while by-value argument passing may be implemented with reference to a
305           local stack variable in the ABI.)
306
307     basic
308         Generate stack canaries in functions with local variables of `[T; N]`
309         type, where `T` is byte-sized and `N` >= 8.
310
311     none
312         Do not generate stack canaries.
313 "#
314                 );
315             }
316             req => llvm_util::print(req, sess),
317         }
318     }
319
320     fn print_passes(&self) {
321         llvm_util::print_passes();
322     }
323
324     fn print_version(&self) {
325         llvm_util::print_version();
326     }
327
328     fn target_features(&self, sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
329         target_features(sess, allow_unstable)
330     }
331
332     fn codegen_crate<'tcx>(
333         &self,
334         tcx: TyCtxt<'tcx>,
335         metadata: EncodedMetadata,
336         need_metadata_module: bool,
337     ) -> Box<dyn Any> {
338         Box::new(rustc_codegen_ssa::base::codegen_crate(
339             LlvmCodegenBackend(()),
340             tcx,
341             crate::llvm_util::target_cpu(tcx.sess).to_string(),
342             metadata,
343             need_metadata_module,
344         ))
345     }
346
347     fn join_codegen(
348         &self,
349         ongoing_codegen: Box<dyn Any>,
350         sess: &Session,
351         outputs: &OutputFilenames,
352     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
353         let (codegen_results, work_products) = ongoing_codegen
354             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
355             .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
356             .join(sess);
357
358         sess.time("llvm_dump_timing_file", || {
359             if sess.opts.unstable_opts.llvm_time_trace {
360                 let file_name = outputs.with_extension("llvm_timings.json");
361                 llvm_util::time_trace_profiler_finish(&file_name);
362             }
363         });
364
365         Ok((codegen_results, work_products))
366     }
367
368     fn link(
369         &self,
370         sess: &Session,
371         codegen_results: CodegenResults,
372         outputs: &OutputFilenames,
373     ) -> Result<(), ErrorGuaranteed> {
374         use crate::back::archive::LlvmArchiveBuilderBuilder;
375         use rustc_codegen_ssa::back::link::link_binary;
376
377         // Run the linker on any artifacts that resulted from the LLVM run.
378         // This should produce either a finished executable or library.
379         link_binary(sess, &LlvmArchiveBuilderBuilder, &codegen_results, outputs)
380     }
381 }
382
383 pub struct ModuleLlvm {
384     llcx: &'static mut llvm::Context,
385     llmod_raw: *const llvm::Module,
386     tm: &'static mut llvm::TargetMachine,
387 }
388
389 unsafe impl Send for ModuleLlvm {}
390 unsafe impl Sync for ModuleLlvm {}
391
392 impl ModuleLlvm {
393     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
394         unsafe {
395             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
396             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
397             ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
398         }
399     }
400
401     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
402         unsafe {
403             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
404             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
405             ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
406         }
407     }
408
409     fn parse(
410         cgcx: &CodegenContext<LlvmCodegenBackend>,
411         name: &CStr,
412         buffer: &[u8],
413         handler: &Handler,
414     ) -> Result<Self, FatalError> {
415         unsafe {
416             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
417             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
418             let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
419             let tm = match (cgcx.tm_factory)(tm_factory_config) {
420                 Ok(m) => m,
421                 Err(e) => {
422                     handler.struct_err(&e).emit();
423                     return Err(FatalError);
424                 }
425             };
426
427             Ok(ModuleLlvm { llmod_raw, llcx, tm })
428         }
429     }
430
431     fn llmod(&self) -> &llvm::Module {
432         unsafe { &*self.llmod_raw }
433     }
434 }
435
436 impl Drop for ModuleLlvm {
437     fn drop(&mut self) {
438         unsafe {
439             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
440             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
441         }
442     }
443 }