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