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