]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Rollup merge of #53110 - Xanewok:save-analysis-remap-path, r=nrc
[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(quote)]
30 #![feature(range_contains)]
31 #![feature(rustc_diagnostic_macros)]
32 #![feature(slice_sort_by_cached_key)]
33 #![feature(optin_builtin_traits)]
34 #![feature(concat_idents)]
35 #![feature(link_args)]
36 #![feature(static_nobundle)]
37
38 use back::write::create_target_machine;
39 use rustc::dep_graph::WorkProduct;
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
59 #[macro_use] extern crate log;
60 #[macro_use] extern crate syntax;
61 extern crate syntax_pos;
62 extern crate rustc_errors as errors;
63 extern crate serialize;
64 extern crate cc; // Used to locate MSVC
65 extern crate tempfile;
66
67 use back::bytecode::RLIB_BYTECODE_EXTENSION;
68
69 pub use llvm_util::target_features;
70
71 use std::any::Any;
72 use std::path::PathBuf;
73 use std::sync::mpsc;
74 use rustc_data_structures::sync::Lrc;
75
76 use rustc::dep_graph::DepGraph;
77 use rustc::hir::def_id::CrateNum;
78 use rustc::middle::cstore::MetadataLoader;
79 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
80 use rustc::middle::lang_items::LangItem;
81 use rustc::session::{Session, CompileIncomplete};
82 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
83 use rustc::ty::{self, TyCtxt};
84 use rustc::util::time_graph;
85 use rustc::util::nodemap::{FxHashSet, FxHashMap};
86 use rustc::util::profiling::ProfileCategory;
87 use rustc_mir::monomorphize;
88 use rustc_codegen_utils::codegen_backend::CodegenBackend;
89
90 mod diagnostics;
91
92 mod back {
93     pub use rustc_codegen_utils::symbol_names;
94     mod archive;
95     pub mod bytecode;
96     mod command;
97     pub mod linker;
98     pub mod link;
99     mod lto;
100     pub mod symbol_export;
101     pub mod write;
102     mod rpath;
103     pub mod wasm;
104 }
105
106 mod abi;
107 mod allocator;
108 mod asm;
109 mod attributes;
110 mod base;
111 mod builder;
112 mod callee;
113 mod common;
114 mod consts;
115 mod context;
116 mod debuginfo;
117 mod declare;
118 mod glue;
119 mod intrinsic;
120 pub mod llvm;
121 mod llvm_util;
122 mod metadata;
123 mod meth;
124 mod mir;
125 mod mono_item;
126 mod type_;
127 mod type_of;
128 mod value;
129
130 pub struct LlvmCodegenBackend(());
131
132 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
133 impl !Sync for LlvmCodegenBackend {}
134
135 impl LlvmCodegenBackend {
136     pub fn new() -> Box<dyn CodegenBackend> {
137         box LlvmCodegenBackend(())
138     }
139 }
140
141 impl CodegenBackend for LlvmCodegenBackend {
142     fn init(&self, sess: &Session) {
143         llvm_util::init(sess); // Make sure llvm is inited
144     }
145
146     fn print(&self, req: PrintRequest, sess: &Session) {
147         match req {
148             PrintRequest::RelocationModels => {
149                 println!("Available relocation models:");
150                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
151                     println!("    {}", name);
152                 }
153                 println!("");
154             }
155             PrintRequest::CodeModels => {
156                 println!("Available code models:");
157                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
158                     println!("    {}", name);
159                 }
160                 println!("");
161             }
162             PrintRequest::TlsModels => {
163                 println!("Available TLS models:");
164                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
165                     println!("    {}", name);
166                 }
167                 println!("");
168             }
169             req => llvm_util::print(req, sess),
170         }
171     }
172
173     fn print_passes(&self) {
174         llvm_util::print_passes();
175     }
176
177     fn print_version(&self) {
178         llvm_util::print_version();
179     }
180
181     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
182         &DIAGNOSTICS
183     }
184
185     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
186         target_features(sess)
187     }
188
189     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
190         box metadata::LlvmMetadataLoader
191     }
192
193     fn provide(&self, providers: &mut ty::query::Providers) {
194         back::symbol_names::provide(providers);
195         back::symbol_export::provide(providers);
196         base::provide(providers);
197         attributes::provide(providers);
198     }
199
200     fn provide_extern(&self, providers: &mut ty::query::Providers) {
201         back::symbol_export::provide_extern(providers);
202         base::provide_extern(providers);
203         attributes::provide_extern(providers);
204     }
205
206     fn codegen_crate<'a, 'tcx>(
207         &self,
208         tcx: TyCtxt<'a, 'tcx, 'tcx>,
209         rx: mpsc::Receiver<Box<dyn Any + Send>>
210     ) -> Box<dyn Any> {
211         box base::codegen_crate(tcx, rx)
212     }
213
214     fn join_codegen_and_link(
215         &self,
216         ongoing_codegen: Box<dyn Any>,
217         sess: &Session,
218         dep_graph: &DepGraph,
219         outputs: &OutputFilenames,
220     ) -> Result<(), CompileIncomplete>{
221         use rustc::util::common::time;
222         let (ongoing_codegen, work_products) =
223             ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
224                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
225                 .join(sess);
226         if sess.opts.debugging_opts.incremental_info {
227             back::write::dump_incremental_data(&ongoing_codegen);
228         }
229
230         time(sess,
231              "serialize work products",
232              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
233
234         sess.compile_status()?;
235
236         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
237                                                    i == OutputType::Metadata) {
238             return Ok(());
239         }
240
241         // Run the linker on any artifacts that resulted from the LLVM run.
242         // This should produce either a finished executable or library.
243         sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
244         time(sess, "linking", || {
245             back::link::link_binary(sess, &ongoing_codegen,
246                                     outputs, &ongoing_codegen.crate_name.as_str());
247         });
248         sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
249
250         // Now that we won't touch anything in the incremental compilation directory
251         // any more, we can finalize it (which involves renaming it)
252         rustc_incremental::finalize_session_directory(sess, ongoing_codegen.link.crate_hash);
253
254         Ok(())
255     }
256 }
257
258 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
259 #[no_mangle]
260 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
261     LlvmCodegenBackend::new()
262 }
263
264 struct ModuleCodegen {
265     /// The name of the module. When the crate may be saved between
266     /// compilations, incremental compilation requires that name be
267     /// unique amongst **all** crates.  Therefore, it should contain
268     /// something unique to this crate (e.g., a module path) as well
269     /// as the crate name and disambiguator.
270     name: String,
271     llmod_id: String,
272     source: ModuleSource,
273     kind: ModuleKind,
274 }
275
276 #[derive(Copy, Clone, Debug, PartialEq)]
277 enum ModuleKind {
278     Regular,
279     Metadata,
280     Allocator,
281 }
282
283 impl ModuleCodegen {
284     fn llvm(&self) -> Option<&ModuleLlvm> {
285         match self.source {
286             ModuleSource::Codegened(ref llvm) => Some(llvm),
287             ModuleSource::Preexisting(_) => None,
288         }
289     }
290
291     fn into_compiled_module(self,
292                                 emit_obj: bool,
293                                 emit_bc: bool,
294                                 emit_bc_compressed: bool,
295                                 outputs: &OutputFilenames) -> CompiledModule {
296         let pre_existing = match self.source {
297             ModuleSource::Preexisting(_) => true,
298             ModuleSource::Codegened(_) => false,
299         };
300         let object = if emit_obj {
301             Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
302         } else {
303             None
304         };
305         let bytecode = if emit_bc {
306             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
307         } else {
308             None
309         };
310         let bytecode_compressed = if emit_bc_compressed {
311             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
312                     .with_extension(RLIB_BYTECODE_EXTENSION))
313         } else {
314             None
315         };
316
317         CompiledModule {
318             llmod_id: self.llmod_id,
319             name: self.name.clone(),
320             kind: self.kind,
321             pre_existing,
322             object,
323             bytecode,
324             bytecode_compressed,
325         }
326     }
327 }
328
329 #[derive(Debug)]
330 struct CompiledModule {
331     name: String,
332     llmod_id: String,
333     kind: ModuleKind,
334     pre_existing: bool,
335     object: Option<PathBuf>,
336     bytecode: Option<PathBuf>,
337     bytecode_compressed: Option<PathBuf>,
338 }
339
340 enum ModuleSource {
341     /// Copy the `.o` files or whatever from the incr. comp. directory.
342     Preexisting(WorkProduct),
343
344     /// Rebuild from this LLVM module.
345     Codegened(ModuleLlvm),
346 }
347
348 struct ModuleLlvm {
349     llcx: &'static mut llvm::Context,
350     llmod_raw: *const llvm::Module,
351     tm: &'static mut llvm::TargetMachine,
352 }
353
354 unsafe impl Send for ModuleLlvm { }
355 unsafe impl Sync for ModuleLlvm { }
356
357 impl ModuleLlvm {
358     fn new(sess: &Session, mod_name: &str) -> Self {
359         unsafe {
360             let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
361             let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
362
363             ModuleLlvm {
364                 llmod_raw,
365                 llcx,
366                 tm: create_target_machine(sess, false),
367             }
368         }
369     }
370
371     fn llmod(&self) -> &llvm::Module {
372         unsafe {
373             &*self.llmod_raw
374         }
375     }
376 }
377
378 impl Drop for ModuleLlvm {
379     fn drop(&mut self) {
380         unsafe {
381             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
382             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
383         }
384     }
385 }
386
387 struct CodegenResults {
388     crate_name: Symbol,
389     modules: Vec<CompiledModule>,
390     allocator_module: Option<CompiledModule>,
391     metadata_module: CompiledModule,
392     link: rustc::middle::cstore::LinkMeta,
393     metadata: rustc::middle::cstore::EncodedMetadata,
394     windows_subsystem: Option<String>,
395     linker_info: back::linker::LinkerInfo,
396     crate_info: CrateInfo,
397 }
398
399 /// Misc info we load from metadata to persist beyond the tcx
400 struct CrateInfo {
401     panic_runtime: Option<CrateNum>,
402     compiler_builtins: Option<CrateNum>,
403     profiler_runtime: Option<CrateNum>,
404     sanitizer_runtime: Option<CrateNum>,
405     is_no_builtins: FxHashSet<CrateNum>,
406     native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
407     crate_name: FxHashMap<CrateNum, String>,
408     used_libraries: Lrc<Vec<NativeLibrary>>,
409     link_args: Lrc<Vec<String>>,
410     used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
411     used_crates_static: Vec<(CrateNum, LibSource)>,
412     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
413     wasm_imports: FxHashMap<String, String>,
414     lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
415     missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
416 }
417
418 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }