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