]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/lib.rs
Rollup merge of #77877 - scottmcm:fewer-try-trait-method-references, r=shepmaster
[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(bool_to_option)]
9 #![feature(const_cstr_unchecked)]
10 #![feature(crate_visibility_modifier)]
11 #![feature(extern_types)]
12 #![feature(in_band_lifetimes)]
13 #![feature(nll)]
14 #![feature(or_patterns)]
15 #![recursion_limit = "256"]
16
17 use back::write::{create_informational_target_machine, create_target_machine};
18
19 pub use llvm_util::target_features;
20 use rustc_ast::expand::allocator::AllocatorKind;
21 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
22 use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, ModuleConfig};
23 use rustc_codegen_ssa::traits::*;
24 use rustc_codegen_ssa::ModuleCodegen;
25 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
26 use rustc_data_structures::fx::FxHashMap;
27 use rustc_errors::{ErrorReported, FatalError, Handler};
28 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
29 use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
30 use rustc_middle::ty::{self, TyCtxt};
31 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
32 use rustc_session::Session;
33 use rustc_span::symbol::Symbol;
34
35 use std::any::Any;
36 use std::ffi::CStr;
37 use std::sync::Arc;
38
39 mod back {
40     pub mod archive;
41     pub mod lto;
42     mod profiling;
43     pub mod write;
44 }
45
46 mod abi;
47 mod allocator;
48 mod asm;
49 mod attributes;
50 mod base;
51 mod builder;
52 mod callee;
53 mod common;
54 mod consts;
55 mod context;
56 mod coverageinfo;
57 mod debuginfo;
58 mod declare;
59 mod intrinsic;
60
61 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
62 #[path = "llvm/mod.rs"]
63 mod llvm_;
64 pub mod llvm {
65     pub use super::llvm_::*;
66 }
67
68 mod llvm_util;
69 mod metadata;
70 mod mono_item;
71 mod type_;
72 mod type_of;
73 mod va_arg;
74 mod value;
75
76 #[derive(Clone)]
77 pub struct LlvmCodegenBackend(());
78
79 impl ExtraBackendMethods for LlvmCodegenBackend {
80     fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
81         ModuleLlvm::new_metadata(tcx, mod_name)
82     }
83
84     fn write_compressed_metadata<'tcx>(
85         &self,
86         tcx: TyCtxt<'tcx>,
87         metadata: &EncodedMetadata,
88         llvm_module: &mut ModuleLlvm,
89     ) {
90         base::write_compressed_metadata(tcx, metadata, llvm_module)
91     }
92     fn codegen_allocator<'tcx>(
93         &self,
94         tcx: TyCtxt<'tcx>,
95         mods: &mut ModuleLlvm,
96         kind: AllocatorKind,
97         has_alloc_error_handler: bool,
98     ) {
99         unsafe { allocator::codegen(tcx, mods, kind, has_alloc_error_handler) }
100     }
101     fn compile_codegen_unit(
102         &self,
103         tcx: TyCtxt<'_>,
104         cgu_name: Symbol,
105     ) -> (ModuleCodegen<ModuleLlvm>, u64) {
106         base::compile_codegen_unit(tcx, cgu_name)
107     }
108     fn target_machine_factory(
109         &self,
110         sess: &Session,
111         optlvl: OptLevel,
112     ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
113         back::write::target_machine_factory(sess, optlvl)
114     }
115     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
116         llvm_util::target_cpu(sess)
117     }
118     fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
119         llvm_util::tune_cpu(sess)
120     }
121 }
122
123 impl WriteBackendMethods for LlvmCodegenBackend {
124     type Module = ModuleLlvm;
125     type ModuleBuffer = back::lto::ModuleBuffer;
126     type Context = llvm::Context;
127     type TargetMachine = &'static mut llvm::TargetMachine;
128     type ThinData = back::lto::ThinData;
129     type ThinBuffer = back::lto::ThinBuffer;
130     fn print_pass_timings(&self) {
131         unsafe {
132             llvm::LLVMRustPrintPassTimings();
133         }
134     }
135     fn run_link(
136         cgcx: &CodegenContext<Self>,
137         diag_handler: &Handler,
138         modules: Vec<ModuleCodegen<Self::Module>>,
139     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
140         back::write::link(cgcx, diag_handler, modules)
141     }
142     fn run_fat_lto(
143         cgcx: &CodegenContext<Self>,
144         modules: Vec<FatLTOInput<Self>>,
145         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
146     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
147         back::lto::run_fat(cgcx, modules, cached_modules)
148     }
149     fn run_thin_lto(
150         cgcx: &CodegenContext<Self>,
151         modules: Vec<(String, Self::ThinBuffer)>,
152         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
153     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
154         back::lto::run_thin(cgcx, modules, cached_modules)
155     }
156     unsafe fn optimize(
157         cgcx: &CodegenContext<Self>,
158         diag_handler: &Handler,
159         module: &ModuleCodegen<Self::Module>,
160         config: &ModuleConfig,
161     ) -> Result<(), FatalError> {
162         back::write::optimize(cgcx, diag_handler, module, config)
163     }
164     unsafe fn optimize_thin(
165         cgcx: &CodegenContext<Self>,
166         thin: &mut ThinModule<Self>,
167     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
168         back::lto::optimize_thin_module(thin, cgcx)
169     }
170     unsafe fn codegen(
171         cgcx: &CodegenContext<Self>,
172         diag_handler: &Handler,
173         module: ModuleCodegen<Self::Module>,
174         config: &ModuleConfig,
175     ) -> Result<CompiledModule, FatalError> {
176         back::write::codegen(cgcx, diag_handler, module, config)
177     }
178     fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
179         back::lto::prepare_thin(module)
180     }
181     fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
182         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
183     }
184     fn run_lto_pass_manager(
185         cgcx: &CodegenContext<Self>,
186         module: &ModuleCodegen<Self::Module>,
187         config: &ModuleConfig,
188         thin: bool,
189     ) {
190         back::lto::run_pass_manager(cgcx, module, config, thin)
191     }
192 }
193
194 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
195 unsafe impl Sync for LlvmCodegenBackend {}
196
197 impl LlvmCodegenBackend {
198     pub fn new() -> Box<dyn CodegenBackend> {
199         Box::new(LlvmCodegenBackend(()))
200     }
201 }
202
203 impl CodegenBackend for LlvmCodegenBackend {
204     fn init(&self, sess: &Session) {
205         llvm_util::init(sess); // Make sure llvm is inited
206     }
207
208     fn print(&self, req: PrintRequest, sess: &Session) {
209         match req {
210             PrintRequest::RelocationModels => {
211                 println!("Available relocation models:");
212                 for name in
213                     &["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
214                 {
215                     println!("    {}", name);
216                 }
217                 println!();
218             }
219             PrintRequest::CodeModels => {
220                 println!("Available code models:");
221                 for name in &["tiny", "small", "kernel", "medium", "large"] {
222                     println!("    {}", name);
223                 }
224                 println!();
225             }
226             PrintRequest::TlsModels => {
227                 println!("Available TLS models:");
228                 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
229                     println!("    {}", name);
230                 }
231                 println!();
232             }
233             req => llvm_util::print(req, sess),
234         }
235     }
236
237     fn print_passes(&self) {
238         llvm_util::print_passes();
239     }
240
241     fn print_version(&self) {
242         llvm_util::print_version();
243     }
244
245     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
246         target_features(sess)
247     }
248
249     fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
250         Box::new(metadata::LlvmMetadataLoader)
251     }
252
253     fn provide(&self, providers: &mut ty::query::Providers) {
254         attributes::provide_both(providers);
255     }
256
257     fn provide_extern(&self, providers: &mut ty::query::Providers) {
258         attributes::provide_both(providers);
259     }
260
261     fn codegen_crate<'tcx>(
262         &self,
263         tcx: TyCtxt<'tcx>,
264         metadata: EncodedMetadata,
265         need_metadata_module: bool,
266     ) -> Box<dyn Any> {
267         Box::new(rustc_codegen_ssa::base::codegen_crate(
268             LlvmCodegenBackend(()),
269             tcx,
270             metadata,
271             need_metadata_module,
272         ))
273     }
274
275     fn join_codegen(
276         &self,
277         ongoing_codegen: Box<dyn Any>,
278         sess: &Session,
279     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
280         let (codegen_results, work_products) = ongoing_codegen
281             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
282             .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
283             .join(sess);
284
285         sess.time("llvm_dump_timing_file", || {
286             if sess.opts.debugging_opts.llvm_time_trace {
287                 llvm_util::time_trace_profiler_finish("llvm_timings.json");
288             }
289         });
290
291         Ok((codegen_results, work_products))
292     }
293
294     fn link(
295         &self,
296         sess: &Session,
297         codegen_results: CodegenResults,
298         outputs: &OutputFilenames,
299     ) -> Result<(), ErrorReported> {
300         // Run the linker on any artifacts that resulted from the LLVM run.
301         // This should produce either a finished executable or library.
302         sess.time("link_crate", || {
303             use crate::back::archive::LlvmArchiveBuilder;
304             use rustc_codegen_ssa::back::link::link_binary;
305
306             let target_cpu = crate::llvm_util::target_cpu(sess);
307             link_binary::<LlvmArchiveBuilder<'_>>(
308                 sess,
309                 &codegen_results,
310                 outputs,
311                 &codegen_results.crate_name.as_str(),
312                 target_cpu,
313             );
314         });
315
316         Ok(())
317     }
318 }
319
320 pub struct ModuleLlvm {
321     llcx: &'static mut llvm::Context,
322     llmod_raw: *const llvm::Module,
323     tm: &'static mut llvm::TargetMachine,
324 }
325
326 unsafe impl Send for ModuleLlvm {}
327 unsafe impl Sync for ModuleLlvm {}
328
329 impl ModuleLlvm {
330     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
331         unsafe {
332             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
333             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
334             ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx) }
335         }
336     }
337
338     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
339         unsafe {
340             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
341             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
342             ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
343         }
344     }
345
346     fn parse(
347         cgcx: &CodegenContext<LlvmCodegenBackend>,
348         name: &CStr,
349         buffer: &[u8],
350         handler: &Handler,
351     ) -> Result<Self, FatalError> {
352         unsafe {
353             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
354             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
355             let tm = match (cgcx.tm_factory.0)() {
356                 Ok(m) => m,
357                 Err(e) => {
358                     handler.struct_err(&e).emit();
359                     return Err(FatalError);
360                 }
361             };
362
363             Ok(ModuleLlvm { llmod_raw, llcx, tm })
364         }
365     }
366
367     fn llmod(&self) -> &llvm::Module {
368         unsafe { &*self.llmod_raw }
369     }
370 }
371
372 impl Drop for ModuleLlvm {
373     fn drop(&mut self) {
374         unsafe {
375             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
376             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
377         }
378     }
379 }