]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Rollup merge of #61261 - spastorino:is-union-return-ty, r=oli-obk
[rust.git] / src / librustc_codegen_llvm / 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/")]
8
9 #![feature(box_patterns)]
10 #![feature(box_syntax)]
11 #![feature(crate_visibility_modifier)]
12 #![feature(custom_attribute)]
13 #![feature(extern_types)]
14 #![feature(in_band_lifetimes)]
15 #![allow(unused_attributes)]
16 #![feature(libc)]
17 #![feature(nll)]
18 #![feature(rustc_diagnostic_macros)]
19 #![feature(optin_builtin_traits)]
20 #![feature(concat_idents)]
21 #![feature(link_args)]
22 #![feature(static_nobundle)]
23 #![feature(trusted_len)]
24 #![deny(rust_2018_idioms)]
25 #![allow(explicit_outlives_requirements)]
26
27 use back::write::{create_target_machine, create_informational_target_machine};
28 use syntax_pos::symbol::Symbol;
29
30 extern crate flate2;
31 #[macro_use] extern crate bitflags;
32 extern crate libc;
33 #[macro_use] extern crate rustc;
34 extern crate rustc_mir;
35 extern crate rustc_allocator;
36 extern crate rustc_target;
37 #[macro_use] extern crate rustc_data_structures;
38 extern crate rustc_incremental;
39 extern crate rustc_codegen_utils;
40 extern crate rustc_codegen_ssa;
41 extern crate rustc_fs_util;
42
43 #[macro_use] extern crate log;
44 #[macro_use] extern crate syntax;
45 extern crate syntax_pos;
46 extern crate rustc_errors as errors;
47
48 use rustc_codegen_ssa::traits::*;
49 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, FatLTOInput};
50 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
51 use rustc_codegen_ssa::CompiledModule;
52 use errors::{FatalError, Handler};
53 use rustc::dep_graph::WorkProduct;
54 use syntax_pos::symbol::InternedString;
55 pub use llvm_util::target_features;
56 use std::any::Any;
57 use std::sync::{mpsc, Arc};
58
59 use rustc::dep_graph::DepGraph;
60 use rustc::middle::allocator::AllocatorKind;
61 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
62 use rustc::session::Session;
63 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest, OptLevel};
64 use rustc::ty::{self, TyCtxt};
65 use rustc::util::common::ErrorReported;
66 use rustc_mir::monomorphize;
67 use rustc_codegen_ssa::ModuleCodegen;
68 use rustc_codegen_utils::codegen_backend::CodegenBackend;
69
70 mod error_codes;
71
72 mod back {
73     pub mod archive;
74     pub mod bytecode;
75     pub mod lto;
76     pub mod write;
77 }
78
79 mod abi;
80 mod allocator;
81 mod asm;
82 mod attributes;
83 mod base;
84 mod builder;
85 mod callee;
86 mod common;
87 mod consts;
88 mod context;
89 mod debuginfo;
90 mod declare;
91 mod intrinsic;
92
93 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
94 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
95
96 mod llvm_util;
97 mod metadata;
98 mod mono_item;
99 mod type_;
100 mod type_of;
101 mod value;
102 mod va_arg;
103
104 #[derive(Clone)]
105 pub struct LlvmCodegenBackend(());
106
107 impl ExtraBackendMethods for LlvmCodegenBackend {
108     fn new_metadata(&self, tcx: TyCtxt<'_, '_, '_>, mod_name: &str) -> ModuleLlvm {
109         ModuleLlvm::new_metadata(tcx, mod_name)
110     }
111
112     fn write_compressed_metadata<'b, 'gcx>(
113         &self,
114         tcx: TyCtxt<'b, 'gcx, 'gcx>,
115         metadata: &EncodedMetadata,
116         llvm_module: &mut ModuleLlvm
117     ) {
118         base::write_compressed_metadata(tcx, metadata, llvm_module)
119     }
120     fn codegen_allocator<'b, 'gcx>(
121         &self,
122         tcx: TyCtxt<'b, 'gcx, 'gcx>,
123         mods: &mut ModuleLlvm,
124         kind: AllocatorKind
125     ) {
126         unsafe { allocator::codegen(tcx, mods, kind) }
127     }
128     fn compile_codegen_unit<'a, 'tcx: 'a>(
129         &self,
130         tcx: TyCtxt<'a, 'tcx, 'tcx>,
131         cgu_name: InternedString,
132     ) {
133         base::compile_codegen_unit(tcx, cgu_name);
134     }
135     fn target_machine_factory(
136         &self,
137         sess: &Session,
138         optlvl: OptLevel,
139         find_features: bool
140     ) -> Arc<dyn Fn() ->
141         Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
142         back::write::target_machine_factory(sess, optlvl, find_features)
143     }
144     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
145         llvm_util::target_cpu(sess)
146     }
147 }
148
149 impl WriteBackendMethods for LlvmCodegenBackend {
150     type Module = ModuleLlvm;
151     type ModuleBuffer = back::lto::ModuleBuffer;
152     type Context = llvm::Context;
153     type TargetMachine = &'static mut llvm::TargetMachine;
154     type ThinData = back::lto::ThinData;
155     type ThinBuffer = back::lto::ThinBuffer;
156     fn print_pass_timings(&self) {
157             unsafe { llvm::LLVMRustPrintPassTimings(); }
158     }
159     fn run_fat_lto(
160         cgcx: &CodegenContext<Self>,
161         modules: Vec<FatLTOInput<Self>>,
162         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
163     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
164         back::lto::run_fat(cgcx, modules, cached_modules)
165     }
166     fn run_thin_lto(
167         cgcx: &CodegenContext<Self>,
168         modules: Vec<(String, Self::ThinBuffer)>,
169         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
170     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
171         back::lto::run_thin(cgcx, modules, cached_modules)
172     }
173     unsafe fn optimize(
174         cgcx: &CodegenContext<Self>,
175         diag_handler: &Handler,
176         module: &ModuleCodegen<Self::Module>,
177         config: &ModuleConfig,
178     ) -> Result<(), FatalError> {
179         back::write::optimize(cgcx, diag_handler, module, config)
180     }
181     unsafe fn optimize_thin(
182         cgcx: &CodegenContext<Self>,
183         thin: &mut ThinModule<Self>,
184     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
185         back::lto::optimize_thin_module(thin, cgcx)
186     }
187     unsafe fn codegen(
188         cgcx: &CodegenContext<Self>,
189         diag_handler: &Handler,
190         module: ModuleCodegen<Self::Module>,
191         config: &ModuleConfig,
192     ) -> Result<CompiledModule, FatalError> {
193         back::write::codegen(cgcx, diag_handler, module, config)
194     }
195     fn prepare_thin(
196         module: ModuleCodegen<Self::Module>
197     ) -> (String, Self::ThinBuffer) {
198         back::lto::prepare_thin(module)
199     }
200     fn serialize_module(
201         module: ModuleCodegen<Self::Module>
202     ) -> (String, Self::ModuleBuffer) {
203         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
204     }
205     fn run_lto_pass_manager(
206         cgcx: &CodegenContext<Self>,
207         module: &ModuleCodegen<Self::Module>,
208         config: &ModuleConfig,
209         thin: bool
210     ) {
211         back::lto::run_pass_manager(cgcx, module, config, thin)
212     }
213 }
214
215 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
216 unsafe impl Sync for LlvmCodegenBackend {}
217
218 impl LlvmCodegenBackend {
219     pub fn new() -> Box<dyn CodegenBackend> {
220         box LlvmCodegenBackend(())
221     }
222 }
223
224 impl CodegenBackend for LlvmCodegenBackend {
225     fn init(&self, sess: &Session) {
226         llvm_util::init(sess); // Make sure llvm is inited
227     }
228
229     fn print(&self, req: PrintRequest, sess: &Session) {
230         match req {
231             PrintRequest::RelocationModels => {
232                 println!("Available relocation models:");
233                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
234                     println!("    {}", name);
235                 }
236                 println!("");
237             }
238             PrintRequest::CodeModels => {
239                 println!("Available code models:");
240                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
241                     println!("    {}", name);
242                 }
243                 println!("");
244             }
245             PrintRequest::TlsModels => {
246                 println!("Available TLS models:");
247                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
248                     println!("    {}", name);
249                 }
250                 println!("");
251             }
252             req => llvm_util::print(req, sess),
253         }
254     }
255
256     fn print_passes(&self) {
257         llvm_util::print_passes();
258     }
259
260     fn print_version(&self) {
261         llvm_util::print_version();
262     }
263
264     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
265         &DIAGNOSTICS
266     }
267
268     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
269         target_features(sess)
270     }
271
272     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
273         box metadata::LlvmMetadataLoader
274     }
275
276     fn provide(&self, providers: &mut ty::query::Providers<'_>) {
277         rustc_codegen_utils::symbol_names::provide(providers);
278         rustc_codegen_ssa::back::symbol_export::provide(providers);
279         rustc_codegen_ssa::base::provide_both(providers);
280         attributes::provide(providers);
281     }
282
283     fn provide_extern(&self, providers: &mut ty::query::Providers<'_>) {
284         rustc_codegen_ssa::back::symbol_export::provide_extern(providers);
285         rustc_codegen_ssa::base::provide_both(providers);
286         attributes::provide_extern(providers);
287     }
288
289     fn codegen_crate<'b, 'tcx>(
290         &self,
291         tcx: TyCtxt<'b, 'tcx, 'tcx>,
292         metadata: EncodedMetadata,
293         need_metadata_module: bool,
294         rx: mpsc::Receiver<Box<dyn Any + Send>>
295     ) -> Box<dyn Any> {
296         box rustc_codegen_ssa::base::codegen_crate(
297             LlvmCodegenBackend(()), tcx, metadata, need_metadata_module, rx)
298     }
299
300     fn join_codegen_and_link(
301         &self,
302         ongoing_codegen: Box<dyn Any>,
303         sess: &Session,
304         dep_graph: &DepGraph,
305         outputs: &OutputFilenames,
306     ) -> Result<(), ErrorReported> {
307         use rustc::util::common::time;
308         let (codegen_results, work_products) =
309             ongoing_codegen.downcast::
310                 <rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
311                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
312                 .join(sess);
313         if sess.opts.debugging_opts.incremental_info {
314             rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
315         }
316
317         time(sess,
318              "serialize work products",
319              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
320
321         sess.compile_status()?;
322
323         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
324                                                    i == OutputType::Metadata) {
325             return Ok(());
326         }
327
328         // Run the linker on any artifacts that resulted from the LLVM run.
329         // This should produce either a finished executable or library.
330         sess.profiler(|p| p.start_activity("link_crate"));
331         time(sess, "linking", || {
332             use rustc_codegen_ssa::back::link::link_binary;
333             use crate::back::archive::LlvmArchiveBuilder;
334
335             let target_cpu = crate::llvm_util::target_cpu(sess);
336             link_binary::<LlvmArchiveBuilder<'_>>(
337                 sess,
338                 &codegen_results,
339                 outputs,
340                 &codegen_results.crate_name.as_str(),
341                 target_cpu,
342             );
343         });
344         sess.profiler(|p| p.end_activity("link_crate"));
345
346         // Now that we won't touch anything in the incremental compilation directory
347         // any more, we can finalize it (which involves renaming it)
348         rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
349
350         Ok(())
351     }
352 }
353
354 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
355 #[no_mangle]
356 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
357     LlvmCodegenBackend::new()
358 }
359
360 pub struct ModuleLlvm {
361     llcx: &'static mut llvm::Context,
362     llmod_raw: *const llvm::Module,
363     tm: &'static mut llvm::TargetMachine,
364 }
365
366 unsafe impl Send for ModuleLlvm { }
367 unsafe impl Sync for ModuleLlvm { }
368
369 impl ModuleLlvm {
370     fn new(tcx: TyCtxt<'_, '_, '_>, mod_name: &str) -> Self {
371         unsafe {
372             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
373             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
374             ModuleLlvm {
375                 llmod_raw,
376                 llcx,
377                 tm: create_target_machine(tcx, false),
378             }
379         }
380     }
381
382     fn new_metadata(tcx: TyCtxt<'_, '_, '_>, mod_name: &str) -> Self {
383         unsafe {
384             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
385             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
386             ModuleLlvm {
387                 llmod_raw,
388                 llcx,
389                 tm: create_informational_target_machine(&tcx.sess, false),
390             }
391         }
392     }
393
394     fn parse(
395         cgcx: &CodegenContext<LlvmCodegenBackend>,
396         name: &str,
397         buffer: &back::lto::ModuleBuffer,
398         handler: &Handler,
399     ) -> Result<Self, FatalError> {
400         unsafe {
401             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
402             let llmod_raw = buffer.parse(name, llcx, handler)?;
403             let tm = match (cgcx.tm_factory.0)() {
404                 Ok(m) => m,
405                 Err(e) => {
406                     handler.struct_err(&e).emit();
407                     return Err(FatalError)
408                 }
409             };
410
411             Ok(ModuleLlvm {
412                 llmod_raw,
413                 llcx,
414                 tm,
415             })
416         }
417     }
418
419     fn llmod(&self) -> &llvm::Module {
420         unsafe {
421             &*self.llmod_raw
422         }
423     }
424 }
425
426 impl Drop for ModuleLlvm {
427     fn drop(&mut self) {
428         unsafe {
429             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
430             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
431         }
432     }
433 }
434
435 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }