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