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