]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Don't default on std crate when manipulating browser history
[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(crate_visibility_modifier)]
12 #![feature(custom_attribute)]
13 #![feature(extern_types)]
14 #![feature(in_band_lifetimes)]
15 #![allow(unused_attributes)]
16 #![feature(libc)]
17 #![feature(nll)]
18 #![feature(range_contains)]
19 #![feature(rustc_diagnostic_macros)]
20 #![feature(slice_sort_by_cached_key)]
21 #![feature(optin_builtin_traits)]
22 #![feature(concat_idents)]
23 #![feature(link_args)]
24 #![feature(static_nobundle)]
25
26 use back::write::create_target_machine;
27 use syntax_pos::symbol::Symbol;
28
29 extern crate flate2;
30 #[macro_use] extern crate bitflags;
31 extern crate libc;
32 #[macro_use] extern crate rustc;
33 extern crate jobserver;
34 extern crate num_cpus;
35 extern crate rustc_mir;
36 extern crate rustc_allocator;
37 extern crate rustc_apfloat;
38 extern crate rustc_target;
39 #[macro_use] extern crate rustc_data_structures;
40 extern crate rustc_demangle;
41 extern crate rustc_incremental;
42 extern crate rustc_llvm;
43 extern crate rustc_codegen_utils;
44 extern crate rustc_codegen_ssa;
45 extern crate rustc_fs_util;
46
47 #[macro_use] extern crate log;
48 #[macro_use] extern crate syntax;
49 extern crate syntax_pos;
50 extern crate rustc_errors as errors;
51 extern crate serialize;
52 extern crate cc; // Used to locate MSVC
53 extern crate tempfile;
54 extern crate memmap;
55
56 use rustc_codegen_ssa::traits::*;
57 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig};
58 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
59 use rustc_codegen_ssa::CompiledModule;
60 use errors::{FatalError, Handler};
61 use rustc::dep_graph::WorkProduct;
62 use rustc::util::time_graph::Timeline;
63 use syntax_pos::symbol::InternedString;
64 use rustc::mir::mono::Stats;
65 pub use llvm_util::target_features;
66 use std::any::Any;
67 use std::sync::{mpsc, Arc};
68
69 use rustc::dep_graph::DepGraph;
70 use rustc::middle::allocator::AllocatorKind;
71 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
72 use rustc::session::{Session, CompileIncomplete};
73 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest, OptLevel};
74 use rustc::ty::{self, TyCtxt};
75 use rustc::util::time_graph;
76 use rustc::util::profiling::ProfileCategory;
77 use rustc_mir::monomorphize;
78 use rustc_codegen_ssa::ModuleCodegen;
79 use rustc_codegen_utils::codegen_backend::CodegenBackend;
80
81 mod diagnostics;
82
83 mod back {
84     mod archive;
85     pub mod bytecode;
86     pub mod link;
87     pub mod lto;
88     pub mod write;
89     mod rpath;
90     pub mod wasm;
91 }
92
93 mod abi;
94 mod allocator;
95 mod asm;
96 mod attributes;
97 mod base;
98 mod builder;
99 mod callee;
100 mod common;
101 mod consts;
102 mod context;
103 mod debuginfo;
104 mod declare;
105 mod intrinsic;
106
107 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
108 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
109
110 mod llvm_util;
111 mod metadata;
112 mod mono_item;
113 mod type_;
114 mod type_of;
115 mod value;
116 mod va_arg;
117
118 #[derive(Clone)]
119 pub struct LlvmCodegenBackend(());
120
121 impl ExtraBackendMethods for LlvmCodegenBackend {
122     fn new_metadata(&self, tcx: TyCtxt, mod_name: &str) -> ModuleLlvm {
123         ModuleLlvm::new(tcx, mod_name)
124     }
125     fn write_metadata<'b, 'gcx>(
126         &self,
127         tcx: TyCtxt<'b, 'gcx, 'gcx>,
128         metadata: &ModuleLlvm
129     ) -> EncodedMetadata {
130         base::write_metadata(tcx, metadata)
131     }
132     fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
133         unsafe { allocator::codegen(tcx, mods, kind) }
134     }
135     fn compile_codegen_unit<'a, 'tcx: 'a>(
136         &self,
137         tcx: TyCtxt<'a, 'tcx, 'tcx>,
138         cgu_name: InternedString,
139     ) -> Stats {
140         base::compile_codegen_unit(tcx, cgu_name)
141     }
142     fn target_machine_factory(
143         &self,
144         sess: &Session,
145         optlvl: OptLevel,
146         find_features: bool
147     ) -> Arc<dyn Fn() ->
148         Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
149         back::write::target_machine_factory(sess, optlvl, find_features)
150     }
151     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
152         llvm_util::target_cpu(sess)
153     }
154 }
155
156 impl WriteBackendMethods for LlvmCodegenBackend {
157     type Module = ModuleLlvm;
158     type ModuleBuffer = back::lto::ModuleBuffer;
159     type Context = llvm::Context;
160     type TargetMachine = &'static mut llvm::TargetMachine;
161     type ThinData = back::lto::ThinData;
162     type ThinBuffer = back::lto::ThinBuffer;
163     fn print_pass_timings(&self) {
164             unsafe { llvm::LLVMRustPrintPassTimings(); }
165     }
166     fn run_fat_lto(
167         cgcx: &CodegenContext<Self>,
168         modules: Vec<ModuleCodegen<Self::Module>>,
169         timeline: &mut Timeline
170     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
171         back::lto::run_fat(cgcx, modules, timeline)
172     }
173     fn run_thin_lto(
174         cgcx: &CodegenContext<Self>,
175         modules: Vec<(String, Self::ThinBuffer)>,
176         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
177         timeline: &mut Timeline
178     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
179         back::lto::run_thin(cgcx, modules, cached_modules, timeline)
180     }
181     unsafe fn optimize(
182         cgcx: &CodegenContext<Self>,
183         diag_handler: &Handler,
184         module: &ModuleCodegen<Self::Module>,
185         config: &ModuleConfig,
186         timeline: &mut Timeline
187     ) -> Result<(), FatalError> {
188         back::write::optimize(cgcx, diag_handler, module, config, timeline)
189     }
190     unsafe fn optimize_thin(
191         cgcx: &CodegenContext<Self>,
192         thin: &mut ThinModule<Self>,
193         timeline: &mut Timeline
194     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
195         back::lto::optimize_thin_module(thin, cgcx, timeline)
196     }
197     unsafe fn codegen(
198         cgcx: &CodegenContext<Self>,
199         diag_handler: &Handler,
200         module: ModuleCodegen<Self::Module>,
201         config: &ModuleConfig,
202         timeline: &mut Timeline
203     ) -> Result<CompiledModule, FatalError> {
204         back::write::codegen(cgcx, diag_handler, module, config, timeline)
205     }
206     fn prepare_thin(
207         cgcx: &CodegenContext<Self>,
208         module: ModuleCodegen<Self::Module>
209     ) -> (String, Self::ThinBuffer) {
210         back::lto::prepare_thin(cgcx, module)
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(tcx: TyCtxt, mod_name: &str) -> Self {
366         unsafe {
367             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
368             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
369
370             ModuleLlvm {
371                 llmod_raw,
372                 llcx,
373                 tm: create_target_machine(tcx, 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 }