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.
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.
11 //! The Rust compiler.
15 //! This API is completely unstable and subject to change.
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/")]
21 #![feature(box_patterns)]
22 #![feature(box_syntax)]
23 #![feature(custom_attribute)]
24 #![feature(fs_read_write)]
25 #![allow(unused_attributes)]
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)]
34 use rustc::dep_graph::WorkProduct;
35 use syntax_pos::symbol::Symbol;
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;
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
62 use back::bytecode::RLIB_BYTECODE_EXTENSION;
64 pub use llvm_util::target_features;
67 use std::path::PathBuf;
69 use std::collections::BTreeMap;
70 use rustc_data_structures::sync::Lrc;
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;
87 pub use rustc_trans_utils::symbol_names;
94 pub mod symbol_export;
124 pub struct LlvmTransCrate(());
126 impl !Send for LlvmTransCrate {} // Llvm is on a per-thread basis
127 impl !Sync for LlvmTransCrate {}
129 impl LlvmTransCrate {
130 pub fn new() -> Box<TransCrate> {
131 box LlvmTransCrate(())
135 impl TransCrate for LlvmTransCrate {
136 fn init(&self, sess: &Session) {
137 llvm_util::init(sess); // Make sure llvm is inited
140 fn print(&self, req: PrintRequest, sess: &Session) {
142 PrintRequest::RelocationModels => {
143 println!("Available relocation models:");
144 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
145 println!(" {}", name);
149 PrintRequest::CodeModels => {
150 println!("Available code models:");
151 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
152 println!(" {}", name);
156 PrintRequest::TlsModels => {
157 println!("Available TLS models:");
158 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
159 println!(" {}", name);
163 req => llvm_util::print(req, sess),
167 fn print_passes(&self) {
168 llvm_util::print_passes();
171 fn print_version(&self) {
172 llvm_util::print_version();
175 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
179 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
180 target_features(sess)
183 fn metadata_loader(&self) -> Box<MetadataLoader + Sync> {
184 box metadata::LlvmMetadataLoader
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);
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);
200 fn trans_crate<'a, 'tcx>(
202 tcx: TyCtxt<'a, 'tcx, 'tcx>,
203 rx: mpsc::Receiver<Box<Any + Send>>
205 box base::trans_crate(tcx, rx)
208 fn join_trans_and_link(
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);
224 "serialize work products",
225 move || rustc_incremental::save_work_products(sess, &dep_graph));
227 sess.compile_status()?;
229 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
230 i == OutputType::Metadata) {
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());
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);
248 /// This is the entrypoint for a hot plugged rustc_trans
250 pub fn __rustc_codegen_backend() -> Box<TransCrate> {
251 LlvmTransCrate::new()
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.
262 source: ModuleSource,
266 #[derive(Copy, Clone, Debug, PartialEq)]
273 impl ModuleTranslation {
274 fn llvm(&self) -> Option<&ModuleLlvm> {
276 ModuleSource::Translated(ref llvm) => Some(llvm),
277 ModuleSource::Preexisting(_) => None,
281 fn into_compiled_module(self,
284 emit_bc_compressed: bool,
285 outputs: &OutputFilenames) -> CompiledModule {
286 let pre_existing = match self.source {
287 ModuleSource::Preexisting(_) => true,
288 ModuleSource::Translated(_) => false,
290 let object = if emit_obj {
291 Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
295 let bytecode = if emit_bc {
296 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
300 let bytecode_compressed = if emit_bc_compressed {
301 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
302 .with_extension(RLIB_BYTECODE_EXTENSION))
308 llmod_id: self.llmod_id,
309 name: self.name.clone(),
320 struct CompiledModule {
325 object: Option<PathBuf>,
326 bytecode: Option<PathBuf>,
327 bytecode_compressed: Option<PathBuf>,
331 /// Copy the `.o` files or whatever from the incr. comp. directory.
332 Preexisting(WorkProduct),
334 /// Rebuild from this LLVM module.
335 Translated(ModuleLlvm),
340 llcx: llvm::ContextRef,
341 llmod: llvm::ModuleRef,
342 tm: llvm::TargetMachineRef,
345 unsafe impl Send for ModuleLlvm { }
346 unsafe impl Sync for ModuleLlvm { }
348 impl Drop for ModuleLlvm {
351 llvm::LLVMDisposeModule(self.llmod);
352 llvm::LLVMContextDispose(self.llcx);
353 llvm::LLVMRustDisposeTargetMachine(self.tm);
358 struct CrateTranslation {
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,
370 // Misc info we load from metadata to persist beyond the tcx
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>>,
390 __build_diagnostic_array! { librustc_trans, DIAGNOSTICS }