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