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