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