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