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