]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Added compile codegen to backend trait
[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 rustc::dep_graph::WorkProduct;
41 use syntax_pos::symbol::Symbol;
42
43 #[macro_use] extern crate bitflags;
44 extern crate flate2;
45 extern crate libc;
46 #[macro_use] extern crate rustc;
47 extern crate jobserver;
48 extern crate num_cpus;
49 extern crate rustc_mir;
50 extern crate rustc_allocator;
51 extern crate rustc_apfloat;
52 extern crate rustc_target;
53 #[macro_use] extern crate rustc_data_structures;
54 extern crate rustc_demangle;
55 extern crate rustc_incremental;
56 extern crate rustc_llvm;
57 extern crate rustc_platform_intrinsics as intrinsics;
58 extern crate rustc_codegen_utils;
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 back::bytecode::RLIB_BYTECODE_EXTENSION;
71 use interfaces::*;
72 use time_graph::TimeGraph;
73 use std::sync::mpsc::Receiver;
74 use back::write::{self, OngoingCodegen};
75 use syntax_pos::symbol::InternedString;
76 use rustc::mir::mono::Stats;
77
78 pub use llvm_util::target_features;
79 use std::any::Any;
80 use std::sync::mpsc;
81 use rustc_data_structures::sync::Lrc;
82
83 use rustc::dep_graph::DepGraph;
84 use rustc::hir::def_id::CrateNum;
85 use rustc::middle::allocator::AllocatorKind;
86 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
87 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
88 use rustc::middle::lang_items::LangItem;
89 use rustc::session::{Session, CompileIncomplete};
90 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
91 use rustc::ty::{self, TyCtxt};
92 use rustc::util::time_graph;
93 use rustc::util::nodemap::{FxHashSet, FxHashMap};
94 use rustc::util::profiling::ProfileCategory;
95 use rustc_mir::monomorphize;
96 use rustc_codegen_utils::{CompiledModule, ModuleKind};
97 use rustc_codegen_utils::codegen_backend::CodegenBackend;
98 use rustc_data_structures::svh::Svh;
99
100 mod diagnostics;
101
102 mod back {
103     mod archive;
104     pub mod bytecode;
105     pub mod link;
106     pub mod lto;
107     pub mod write;
108     mod rpath;
109     pub mod wasm;
110 }
111
112 mod interfaces;
113
114 mod abi;
115 mod allocator;
116 mod asm;
117 mod attributes;
118 mod base;
119 mod builder;
120 mod callee;
121 mod common;
122 mod consts;
123 mod context;
124 mod debuginfo;
125 mod declare;
126 mod glue;
127 mod intrinsic;
128
129 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
130 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
131
132 mod llvm_util;
133 mod metadata;
134 mod meth;
135 mod mir;
136 mod mono_item;
137 mod type_;
138 mod type_of;
139 mod value;
140
141 pub struct LlvmCodegenBackend(());
142
143 impl BackendMethods for LlvmCodegenBackend {
144     type Module = ModuleLlvm;
145     type OngoingCodegen = OngoingCodegen;
146
147     fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
148         ModuleLlvm::new(sess, mod_name)
149     }
150     fn write_metadata<'b, 'gcx>(
151         &self,
152         tcx: TyCtxt<'b, 'gcx, 'gcx>,
153         metadata: &ModuleLlvm
154     ) -> EncodedMetadata {
155         base::write_metadata(tcx, metadata)
156     }
157     fn start_async_codegen(
158         &self,
159         tcx: TyCtxt,
160         time_graph: Option<TimeGraph>,
161         metadata: EncodedMetadata,
162         coordinator_receive: Receiver<Box<dyn Any + Send>>,
163         total_cgus: usize
164     ) -> OngoingCodegen {
165         write::start_async_codegen(tcx, time_graph, metadata, coordinator_receive, total_cgus)
166     }
167     fn submit_pre_codegened_module_to_llvm(
168         &self,
169         codegen: &OngoingCodegen,
170         tcx: TyCtxt,
171         module: ModuleCodegen<ModuleLlvm>
172     ) {
173         codegen.submit_pre_codegened_module_to_llvm(tcx, module)
174     }
175     fn codegen_aborted(codegen: OngoingCodegen) {
176         codegen.codegen_aborted();
177     }
178     fn codegen_finished(&self, codegen: &OngoingCodegen, tcx: TyCtxt) {
179         codegen.codegen_finished(tcx)
180     }
181     fn check_for_errors(&self, codegen: &OngoingCodegen, sess: &Session) {
182         codegen.check_for_errors(sess)
183     }
184     fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
185         unsafe { allocator::codegen(tcx, mods, kind) }
186     }
187     fn wait_for_signal_to_codegen_item(&self, codegen: &OngoingCodegen) {
188         codegen.wait_for_signal_to_codegen_item()
189     }
190     fn compile_codegen_unit<'a, 'tcx: 'a>(
191         &self,
192         tcx: TyCtxt<'a, 'tcx, 'tcx>,
193         cgu_name: InternedString,
194     ) -> Stats {
195         base::compile_codegen_unit(tcx, cgu_name)
196     }
197 }
198
199
200 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
201 impl !Sync for LlvmCodegenBackend {}
202
203 impl LlvmCodegenBackend {
204     pub fn new() -> Box<dyn CodegenBackend> {
205         box LlvmCodegenBackend(())
206     }
207 }
208
209 impl CodegenBackend for LlvmCodegenBackend {
210     fn init(&self, sess: &Session) {
211         llvm_util::init(sess); // Make sure llvm is inited
212     }
213
214     fn print(&self, req: PrintRequest, sess: &Session) {
215         match req {
216             PrintRequest::RelocationModels => {
217                 println!("Available relocation models:");
218                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
219                     println!("    {}", name);
220                 }
221                 println!("");
222             }
223             PrintRequest::CodeModels => {
224                 println!("Available code models:");
225                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
226                     println!("    {}", name);
227                 }
228                 println!("");
229             }
230             PrintRequest::TlsModels => {
231                 println!("Available TLS models:");
232                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
233                     println!("    {}", name);
234                 }
235                 println!("");
236             }
237             req => llvm_util::print(req, sess),
238         }
239     }
240
241     fn print_passes(&self) {
242         llvm_util::print_passes();
243     }
244
245     fn print_version(&self) {
246         llvm_util::print_version();
247     }
248
249     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
250         &DIAGNOSTICS
251     }
252
253     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
254         target_features(sess)
255     }
256
257     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
258         box metadata::LlvmMetadataLoader
259     }
260
261     fn provide(&self, providers: &mut ty::query::Providers) {
262         rustc_codegen_utils::symbol_export::provide(providers);
263         rustc_codegen_utils::symbol_names::provide(providers);
264         base::provide_both(providers);
265         attributes::provide(providers);
266     }
267
268     fn provide_extern(&self, providers: &mut ty::query::Providers) {
269         rustc_codegen_utils::symbol_export::provide_extern(providers);
270         base::provide_both(providers);
271         attributes::provide_extern(providers);
272     }
273
274     fn codegen_crate<'a, 'tcx>(
275         &self,
276         tcx: TyCtxt<'a, 'tcx, 'tcx>,
277         rx: mpsc::Receiver<Box<dyn Any + Send>>
278     ) -> Box<dyn Any> {
279         box base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
280     }
281
282     fn join_codegen_and_link(
283         &self,
284         ongoing_codegen: Box<dyn Any>,
285         sess: &Session,
286         dep_graph: &DepGraph,
287         outputs: &OutputFilenames,
288     ) -> Result<(), CompileIncomplete>{
289         use rustc::util::common::time;
290         let (ongoing_codegen, work_products) =
291             ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
292                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
293                 .join(sess);
294         if sess.opts.debugging_opts.incremental_info {
295             back::write::dump_incremental_data(&ongoing_codegen);
296         }
297
298         time(sess,
299              "serialize work products",
300              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
301
302         sess.compile_status()?;
303
304         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
305                                                    i == OutputType::Metadata) {
306             return Ok(());
307         }
308
309         // Run the linker on any artifacts that resulted from the LLVM run.
310         // This should produce either a finished executable or library.
311         sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
312         time(sess, "linking", || {
313             back::link::link_binary(sess, &ongoing_codegen,
314                                     outputs, &ongoing_codegen.crate_name.as_str());
315         });
316         sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
317
318         // Now that we won't touch anything in the incremental compilation directory
319         // any more, we can finalize it (which involves renaming it)
320         rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
321
322         Ok(())
323     }
324 }
325
326 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
327 #[no_mangle]
328 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
329     LlvmCodegenBackend::new()
330 }
331
332 pub struct ModuleCodegen<M> {
333     /// The name of the module. When the crate may be saved between
334     /// compilations, incremental compilation requires that name be
335     /// unique amongst **all** crates.  Therefore, it should contain
336     /// something unique to this crate (e.g., a module path) as well
337     /// as the crate name and disambiguator.
338     /// We currently generate these names via CodegenUnit::build_cgu_name().
339     name: String,
340     module_llvm: M,
341     kind: ModuleKind,
342 }
343
344 struct CachedModuleCodegen {
345     name: String,
346     source: WorkProduct,
347 }
348
349 impl ModuleCodegen<ModuleLlvm> {
350     fn into_compiled_module(self,
351                             emit_obj: bool,
352                             emit_bc: bool,
353                             emit_bc_compressed: bool,
354                             outputs: &OutputFilenames) -> CompiledModule {
355         let object = if emit_obj {
356             Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
357         } else {
358             None
359         };
360         let bytecode = if emit_bc {
361             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
362         } else {
363             None
364         };
365         let bytecode_compressed = if emit_bc_compressed {
366             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
367                         .with_extension(RLIB_BYTECODE_EXTENSION))
368         } else {
369             None
370         };
371
372         CompiledModule {
373             name: self.name.clone(),
374             kind: self.kind,
375             object,
376             bytecode,
377             bytecode_compressed,
378         }
379     }
380 }
381
382 pub struct ModuleLlvm {
383     llcx: &'static mut llvm::Context,
384     llmod_raw: *const llvm::Module,
385     tm: &'static mut llvm::TargetMachine,
386 }
387
388 unsafe impl Send for ModuleLlvm { }
389 unsafe impl Sync for ModuleLlvm { }
390
391 impl ModuleLlvm {
392     fn new(sess: &Session, mod_name: &str) -> Self {
393         unsafe {
394             let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
395             let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
396
397             ModuleLlvm {
398                 llmod_raw,
399                 llcx,
400                 tm: create_target_machine(sess, false),
401             }
402         }
403     }
404
405     fn llmod(&self) -> &llvm::Module {
406         unsafe {
407             &*self.llmod_raw
408         }
409     }
410 }
411
412 impl Drop for ModuleLlvm {
413     fn drop(&mut self) {
414         unsafe {
415             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
416             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
417         }
418     }
419 }
420
421 struct CodegenResults {
422     crate_name: Symbol,
423     modules: Vec<CompiledModule>,
424     allocator_module: Option<CompiledModule>,
425     metadata_module: CompiledModule,
426     crate_hash: Svh,
427     metadata: rustc::middle::cstore::EncodedMetadata,
428     windows_subsystem: Option<String>,
429     linker_info: rustc_codegen_utils::linker::LinkerInfo,
430     crate_info: CrateInfo,
431 }
432
433 /// Misc info we load from metadata to persist beyond the tcx
434 struct CrateInfo {
435     panic_runtime: Option<CrateNum>,
436     compiler_builtins: Option<CrateNum>,
437     profiler_runtime: Option<CrateNum>,
438     sanitizer_runtime: Option<CrateNum>,
439     is_no_builtins: FxHashSet<CrateNum>,
440     native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
441     crate_name: FxHashMap<CrateNum, String>,
442     used_libraries: Lrc<Vec<NativeLibrary>>,
443     link_args: Lrc<Vec<String>>,
444     used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
445     used_crates_static: Vec<(CrateNum, LibSource)>,
446     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
447     wasm_imports: FxHashMap<String, String>,
448     lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
449     missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
450 }
451
452 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }