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/")]
22 #![feature(box_patterns)]
23 #![feature(box_syntax)]
24 #![feature(custom_attribute)]
25 #![feature(fs_read_write)]
26 #![allow(unused_attributes)]
27 #![feature(i128_type)]
29 #![feature(inclusive_range)]
30 #![feature(inclusive_range_syntax)]
33 #![feature(rustc_diagnostic_macros)]
34 #![feature(slice_patterns)]
35 #![feature(conservative_impl_trait)]
36 #![feature(optin_builtin_traits)]
38 use rustc::dep_graph::WorkProduct;
39 use syntax_pos::symbol::Symbol;
42 extern crate bitflags;
45 #[macro_use] extern crate rustc;
46 extern crate jobserver;
47 extern crate num_cpus;
48 extern crate rustc_mir;
49 extern crate rustc_allocator;
50 extern crate rustc_apfloat;
51 extern crate rustc_back;
52 extern crate rustc_const_math;
53 #[macro_use] extern crate rustc_data_structures;
54 extern crate rustc_demangle;
55 extern crate rustc_incremental;
56 extern crate rustc_llvm as llvm;
57 extern crate rustc_platform_intrinsics as intrinsics;
58 extern crate rustc_trans_utils;
60 #[macro_use] extern crate log;
61 #[macro_use] extern crate syntax;
62 extern crate syntax_pos;
63 extern crate rustc_errors as errors;
64 extern crate serialize;
65 extern crate cc; // Used to locate MSVC
68 use back::bytecode::RLIB_BYTECODE_EXTENSION;
70 pub use llvm_util::target_features;
73 use std::path::PathBuf;
75 use rustc_data_structures::sync::Lrc;
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::session::{Session, CompileIncomplete};
82 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
83 use rustc::ty::{self, TyCtxt};
84 use rustc::util::nodemap::{FxHashSet, FxHashMap};
85 use rustc_mir::monomorphize;
86 use rustc_trans_utils::trans_crate::TransCrate;
91 pub use rustc_trans_utils::symbol_names;
98 pub mod symbol_export;
144 pub struct LlvmTransCrate(());
146 impl !Send for LlvmTransCrate {} // Llvm is on a per-thread basis
147 impl !Sync for LlvmTransCrate {}
149 impl LlvmTransCrate {
150 pub fn new() -> Box<TransCrate> {
151 box LlvmTransCrate(())
155 impl TransCrate for LlvmTransCrate {
156 fn init(&self, sess: &Session) {
157 llvm_util::init(sess); // Make sure llvm is inited
160 fn print(&self, req: PrintRequest, sess: &Session) {
162 PrintRequest::RelocationModels => {
163 println!("Available relocation models:");
164 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
165 println!(" {}", name);
169 PrintRequest::CodeModels => {
170 println!("Available code models:");
171 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
172 println!(" {}", name);
176 PrintRequest::TlsModels => {
177 println!("Available TLS models:");
178 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
179 println!(" {}", name);
183 req => llvm_util::print(req, sess),
187 fn print_passes(&self) {
188 llvm_util::print_passes();
191 fn print_version(&self) {
192 llvm_util::print_version();
195 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
199 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
200 target_features(sess)
203 fn metadata_loader(&self) -> Box<MetadataLoader> {
204 box metadata::LlvmMetadataLoader
207 fn provide(&self, providers: &mut ty::maps::Providers) {
208 back::symbol_names::provide(providers);
209 back::symbol_export::provide(providers);
210 base::provide(providers);
211 attributes::provide(providers);
214 fn provide_extern(&self, providers: &mut ty::maps::Providers) {
215 back::symbol_export::provide_extern(providers);
218 fn trans_crate<'a, 'tcx>(
220 tcx: TyCtxt<'a, 'tcx, 'tcx>,
221 rx: mpsc::Receiver<Box<Any + Send>>
223 box base::trans_crate(tcx, rx)
226 fn join_trans_and_link(
230 dep_graph: &DepGraph,
231 outputs: &OutputFilenames,
232 ) -> Result<(), CompileIncomplete>{
233 use rustc::util::common::time;
234 let trans = trans.downcast::<::back::write::OngoingCrateTranslation>()
235 .expect("Expected LlvmTransCrate's OngoingCrateTranslation, found Box<Any>")
236 .join(sess, dep_graph);
237 if sess.opts.debugging_opts.incremental_info {
238 back::write::dump_incremental_data(&trans);
241 time(sess.time_passes(),
242 "serialize work products",
243 move || rustc_incremental::save_work_products(sess, &dep_graph));
245 sess.compile_status()?;
247 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
248 i == OutputType::Metadata) {
252 // Run the linker on any artifacts that resulted from the LLVM run.
253 // This should produce either a finished executable or library.
254 time(sess.time_passes(), "linking", || {
255 back::link::link_binary(sess, &trans, outputs, &trans.crate_name.as_str());
258 // Now that we won't touch anything in the incremental compilation directory
259 // any more, we can finalize it (which involves renaming it)
260 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
266 /// This is the entrypoint for a hot plugged rustc_trans
268 pub fn __rustc_codegen_backend() -> Box<TransCrate> {
269 LlvmTransCrate::new()
272 struct ModuleTranslation {
273 /// The name of the module. When the crate may be saved between
274 /// compilations, incremental compilation requires that name be
275 /// unique amongst **all** crates. Therefore, it should contain
276 /// something unique to this crate (e.g., a module path) as well
277 /// as the crate name and disambiguator.
280 source: ModuleSource,
284 #[derive(Copy, Clone, Debug, PartialEq)]
291 impl ModuleTranslation {
292 fn llvm(&self) -> Option<&ModuleLlvm> {
294 ModuleSource::Translated(ref llvm) => Some(llvm),
295 ModuleSource::Preexisting(_) => None,
299 fn into_compiled_module(self,
302 emit_bc_compressed: bool,
303 outputs: &OutputFilenames) -> CompiledModule {
304 let pre_existing = match self.source {
305 ModuleSource::Preexisting(_) => true,
306 ModuleSource::Translated(_) => false,
308 let object = if emit_obj {
309 Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
313 let bytecode = if emit_bc {
314 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
318 let bytecode_compressed = if emit_bc_compressed {
319 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
320 .with_extension(RLIB_BYTECODE_EXTENSION))
326 llmod_id: self.llmod_id,
327 name: self.name.clone(),
338 struct CompiledModule {
343 object: Option<PathBuf>,
344 bytecode: Option<PathBuf>,
345 bytecode_compressed: Option<PathBuf>,
349 /// Copy the `.o` files or whatever from the incr. comp. directory.
350 Preexisting(WorkProduct),
352 /// Rebuild from this LLVM module.
353 Translated(ModuleLlvm),
358 llcx: llvm::ContextRef,
359 llmod: llvm::ModuleRef,
360 tm: llvm::TargetMachineRef,
363 unsafe impl Send for ModuleLlvm { }
364 unsafe impl Sync for ModuleLlvm { }
366 impl Drop for ModuleLlvm {
369 llvm::LLVMDisposeModule(self.llmod);
370 llvm::LLVMContextDispose(self.llcx);
371 llvm::LLVMRustDisposeTargetMachine(self.tm);
376 struct CrateTranslation {
378 modules: Vec<CompiledModule>,
379 allocator_module: Option<CompiledModule>,
380 metadata_module: CompiledModule,
381 link: rustc::middle::cstore::LinkMeta,
382 metadata: rustc::middle::cstore::EncodedMetadata,
383 windows_subsystem: Option<String>,
384 linker_info: back::linker::LinkerInfo,
385 crate_info: CrateInfo,
388 // Misc info we load from metadata to persist beyond the tcx
390 panic_runtime: Option<CrateNum>,
391 compiler_builtins: Option<CrateNum>,
392 profiler_runtime: Option<CrateNum>,
393 sanitizer_runtime: Option<CrateNum>,
394 is_no_builtins: FxHashSet<CrateNum>,
395 native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
396 crate_name: FxHashMap<CrateNum, String>,
397 used_libraries: Lrc<Vec<NativeLibrary>>,
398 link_args: Lrc<Vec<String>>,
399 used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
400 used_crates_static: Vec<(CrateNum, LibSource)>,
401 used_crates_dynamic: Vec<(CrateNum, LibSource)>,
404 __build_diagnostic_array! { librustc_trans, DIAGNOSTICS }