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