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