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