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_methods)]
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 #[macro_use] extern crate rustc_data_structures;
47 extern crate rustc_demangle;
48 extern crate rustc_incremental;
49 extern crate rustc_llvm as llvm;
50 extern crate rustc_platform_intrinsics as intrinsics;
51 extern crate rustc_trans_utils;
53 #[macro_use] extern crate log;
54 #[macro_use] extern crate syntax;
55 extern crate syntax_pos;
56 extern crate rustc_errors as errors;
57 extern crate serialize;
58 extern crate cc; // Used to locate MSVC
61 use back::bytecode::RLIB_BYTECODE_EXTENSION;
63 pub use llvm_util::target_features;
66 use std::path::PathBuf;
68 use std::collections::BTreeMap;
69 use rustc_data_structures::sync::Lrc;
71 use rustc::dep_graph::DepGraph;
72 use rustc::hir::def_id::CrateNum;
73 use rustc::middle::cstore::MetadataLoader;
74 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
75 use rustc::middle::lang_items::LangItem;
76 use rustc::session::{Session, CompileIncomplete};
77 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
78 use rustc::ty::{self, TyCtxt};
79 use rustc::util::nodemap::{FxHashSet, FxHashMap};
80 use rustc_mir::monomorphize;
81 use rustc_trans_utils::trans_crate::TransCrate;
86 pub use rustc_trans_utils::symbol_names;
93 pub mod symbol_export;
123 pub struct LlvmTransCrate(());
125 impl !Send for LlvmTransCrate {} // Llvm is on a per-thread basis
126 impl !Sync for LlvmTransCrate {}
128 impl LlvmTransCrate {
129 pub fn new() -> Box<TransCrate> {
130 box LlvmTransCrate(())
134 impl TransCrate for LlvmTransCrate {
135 fn init(&self, sess: &Session) {
136 llvm_util::init(sess); // Make sure llvm is inited
139 fn print(&self, req: PrintRequest, sess: &Session) {
141 PrintRequest::RelocationModels => {
142 println!("Available relocation models:");
143 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
144 println!(" {}", name);
148 PrintRequest::CodeModels => {
149 println!("Available code models:");
150 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
151 println!(" {}", name);
155 PrintRequest::TlsModels => {
156 println!("Available TLS models:");
157 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
158 println!(" {}", name);
162 req => llvm_util::print(req, sess),
166 fn print_passes(&self) {
167 llvm_util::print_passes();
170 fn print_version(&self) {
171 llvm_util::print_version();
174 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
178 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
179 target_features(sess)
182 fn metadata_loader(&self) -> Box<MetadataLoader + Sync> {
183 box metadata::LlvmMetadataLoader
186 fn provide(&self, providers: &mut ty::maps::Providers) {
187 back::symbol_names::provide(providers);
188 back::symbol_export::provide(providers);
189 base::provide(providers);
190 attributes::provide(providers);
193 fn provide_extern(&self, providers: &mut ty::maps::Providers) {
194 back::symbol_export::provide_extern(providers);
195 base::provide_extern(providers);
196 attributes::provide_extern(providers);
199 fn trans_crate<'a, 'tcx>(
201 tcx: TyCtxt<'a, 'tcx, 'tcx>,
202 rx: mpsc::Receiver<Box<Any + Send>>
204 box base::trans_crate(tcx, rx)
207 fn join_trans_and_link(
211 dep_graph: &DepGraph,
212 outputs: &OutputFilenames,
213 ) -> Result<(), CompileIncomplete>{
214 use rustc::util::common::time;
215 let (trans, work_products) = trans.downcast::<::back::write::OngoingCrateTranslation>()
216 .expect("Expected LlvmTransCrate's OngoingCrateTranslation, found Box<Any>")
218 if sess.opts.debugging_opts.incremental_info {
219 back::write::dump_incremental_data(&trans);
223 "serialize work products",
224 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
226 sess.compile_status()?;
228 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
229 i == OutputType::Metadata) {
233 // Run the linker on any artifacts that resulted from the LLVM run.
234 // This should produce either a finished executable or library.
235 time(sess, "linking", || {
236 back::link::link_binary(sess, &trans, outputs, &trans.crate_name.as_str());
239 // Now that we won't touch anything in the incremental compilation directory
240 // any more, we can finalize it (which involves renaming it)
241 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
247 /// This is the entrypoint for a hot plugged rustc_trans
249 pub fn __rustc_codegen_backend() -> Box<TransCrate> {
250 LlvmTransCrate::new()
253 struct ModuleTranslation {
254 /// The name of the module. When the crate may be saved between
255 /// compilations, incremental compilation requires that name be
256 /// unique amongst **all** crates. Therefore, it should contain
257 /// something unique to this crate (e.g., a module path) as well
258 /// as the crate name and disambiguator.
261 source: ModuleSource,
265 #[derive(Copy, Clone, Debug, PartialEq)]
272 impl ModuleTranslation {
273 fn llvm(&self) -> Option<&ModuleLlvm> {
275 ModuleSource::Translated(ref llvm) => Some(llvm),
276 ModuleSource::Preexisting(_) => None,
280 fn into_compiled_module(self,
283 emit_bc_compressed: bool,
284 outputs: &OutputFilenames) -> CompiledModule {
285 let pre_existing = match self.source {
286 ModuleSource::Preexisting(_) => true,
287 ModuleSource::Translated(_) => false,
289 let object = if emit_obj {
290 Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
294 let bytecode = if emit_bc {
295 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
299 let bytecode_compressed = if emit_bc_compressed {
300 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
301 .with_extension(RLIB_BYTECODE_EXTENSION))
307 llmod_id: self.llmod_id,
308 name: self.name.clone(),
319 struct CompiledModule {
324 object: Option<PathBuf>,
325 bytecode: Option<PathBuf>,
326 bytecode_compressed: Option<PathBuf>,
330 /// Copy the `.o` files or whatever from the incr. comp. directory.
331 Preexisting(WorkProduct),
333 /// Rebuild from this LLVM module.
334 Translated(ModuleLlvm),
339 llcx: llvm::ContextRef,
340 llmod: llvm::ModuleRef,
341 tm: llvm::TargetMachineRef,
344 unsafe impl Send for ModuleLlvm { }
345 unsafe impl Sync for ModuleLlvm { }
347 impl Drop for ModuleLlvm {
350 llvm::LLVMDisposeModule(self.llmod);
351 llvm::LLVMContextDispose(self.llcx);
352 llvm::LLVMRustDisposeTargetMachine(self.tm);
357 struct CrateTranslation {
359 modules: Vec<CompiledModule>,
360 allocator_module: Option<CompiledModule>,
361 metadata_module: CompiledModule,
362 link: rustc::middle::cstore::LinkMeta,
363 metadata: rustc::middle::cstore::EncodedMetadata,
364 windows_subsystem: Option<String>,
365 linker_info: back::linker::LinkerInfo,
366 crate_info: CrateInfo,
369 // Misc info we load from metadata to persist beyond the tcx
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_custom_sections: BTreeMap<String, Vec<u8>>,
384 wasm_imports: FxHashMap<String, String>,
385 lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
386 missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
389 __build_diagnostic_array! { librustc_trans, DIAGNOSTICS }