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