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_binaryen;
53 extern crate rustc_const_math;
54 extern crate rustc_data_structures;
55 extern crate rustc_demangle;
56 extern crate rustc_incremental;
57 extern crate rustc_llvm as llvm;
58 extern crate rustc_platform_intrinsics as intrinsics;
59 extern crate rustc_trans_utils;
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;
67 extern crate cc; // Used to locate MSVC
70 use back::bytecode::RLIB_BYTECODE_EXTENSION;
72 pub use llvm_util::target_features;
75 use std::path::PathBuf;
77 use rustc_data_structures::sync::Lrc;
79 use rustc::dep_graph::DepGraph;
80 use rustc::hir::def_id::CrateNum;
81 use rustc::middle::cstore::MetadataLoader;
82 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
83 use rustc::session::{Session, CompileIncomplete};
84 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
85 use rustc::ty::{self, TyCtxt};
86 use rustc::util::nodemap::{FxHashSet, FxHashMap};
87 use rustc_mir::monomorphize;
88 use rustc_trans_utils::trans_crate::TransCrate;
93 pub use rustc_trans_utils::symbol_names;
100 pub mod symbol_export;
146 pub struct LlvmTransCrate(());
148 impl !Send for LlvmTransCrate {} // Llvm is on a per-thread basis
149 impl !Sync for LlvmTransCrate {}
151 impl LlvmTransCrate {
152 pub fn new() -> Box<TransCrate> {
153 box LlvmTransCrate(())
157 impl TransCrate for LlvmTransCrate {
158 fn init(&self, sess: &Session) {
159 llvm_util::init(sess); // Make sure llvm is inited
162 fn print(&self, req: PrintRequest, sess: &Session) {
164 PrintRequest::RelocationModels => {
165 println!("Available relocation models:");
166 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
167 println!(" {}", name);
171 PrintRequest::CodeModels => {
172 println!("Available code models:");
173 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
174 println!(" {}", name);
178 PrintRequest::TlsModels => {
179 println!("Available TLS models:");
180 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
181 println!(" {}", name);
185 req => llvm_util::print(req, sess),
189 fn print_passes(&self) {
190 llvm_util::print_passes();
193 fn print_version(&self) {
194 llvm_util::print_version();
197 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
201 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
202 target_features(sess)
205 fn metadata_loader(&self) -> Box<MetadataLoader> {
206 box metadata::LlvmMetadataLoader
209 fn provide(&self, providers: &mut ty::maps::Providers) {
210 back::symbol_names::provide(providers);
211 back::symbol_export::provide(providers);
212 base::provide(providers);
213 attributes::provide(providers);
216 fn provide_extern(&self, providers: &mut ty::maps::Providers) {
217 back::symbol_export::provide_extern(providers);
220 fn trans_crate<'a, 'tcx>(
222 tcx: TyCtxt<'a, 'tcx, 'tcx>,
223 rx: mpsc::Receiver<Box<Any + Send>>
225 box base::trans_crate(tcx, rx)
228 fn join_trans_and_link(
232 dep_graph: &DepGraph,
233 outputs: &OutputFilenames,
234 ) -> Result<(), CompileIncomplete>{
235 use rustc::util::common::time;
236 let trans = trans.downcast::<::back::write::OngoingCrateTranslation>()
237 .expect("Expected LlvmTransCrate's OngoingCrateTranslation, found Box<Any>")
238 .join(sess, dep_graph);
239 if sess.opts.debugging_opts.incremental_info {
240 back::write::dump_incremental_data(&trans);
243 time(sess.time_passes(),
244 "serialize work products",
245 move || rustc_incremental::save_work_products(sess, &dep_graph));
247 sess.compile_status()?;
249 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
250 i == OutputType::Metadata) {
254 // Run the linker on any artifacts that resulted from the LLVM run.
255 // This should produce either a finished executable or library.
256 time(sess.time_passes(), "linking", || {
257 back::link::link_binary(sess, &trans, outputs, &trans.crate_name.as_str());
260 // Now that we won't touch anything in the incremental compilation directory
261 // any more, we can finalize it (which involves renaming it)
262 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
268 /// This is the entrypoint for a hot plugged rustc_trans
270 pub fn __rustc_codegen_backend() -> Box<TransCrate> {
271 LlvmTransCrate::new()
274 struct ModuleTranslation {
275 /// The name of the module. When the crate may be saved between
276 /// compilations, incremental compilation requires that name be
277 /// unique amongst **all** crates. Therefore, it should contain
278 /// something unique to this crate (e.g., a module path) as well
279 /// as the crate name and disambiguator.
282 source: ModuleSource,
286 #[derive(Copy, Clone, Debug, PartialEq)]
293 impl ModuleTranslation {
294 fn llvm(&self) -> Option<&ModuleLlvm> {
296 ModuleSource::Translated(ref llvm) => Some(llvm),
297 ModuleSource::Preexisting(_) => None,
301 fn into_compiled_module(self,
304 emit_bc_compressed: bool,
305 outputs: &OutputFilenames) -> CompiledModule {
306 let pre_existing = match self.source {
307 ModuleSource::Preexisting(_) => true,
308 ModuleSource::Translated(_) => false,
310 let object = if emit_obj {
311 Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
315 let bytecode = if emit_bc {
316 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
320 let bytecode_compressed = if emit_bc_compressed {
321 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
322 .with_extension(RLIB_BYTECODE_EXTENSION))
328 llmod_id: self.llmod_id,
329 name: self.name.clone(),
340 struct CompiledModule {
345 object: Option<PathBuf>,
346 bytecode: Option<PathBuf>,
347 bytecode_compressed: Option<PathBuf>,
351 /// Copy the `.o` files or whatever from the incr. comp. directory.
352 Preexisting(WorkProduct),
354 /// Rebuild from this LLVM module.
355 Translated(ModuleLlvm),
360 llcx: llvm::ContextRef,
361 llmod: llvm::ModuleRef,
362 tm: llvm::TargetMachineRef,
365 unsafe impl Send for ModuleLlvm { }
366 unsafe impl Sync for ModuleLlvm { }
368 impl Drop for ModuleLlvm {
371 llvm::LLVMDisposeModule(self.llmod);
372 llvm::LLVMContextDispose(self.llcx);
373 llvm::LLVMRustDisposeTargetMachine(self.tm);
378 struct CrateTranslation {
380 modules: Vec<CompiledModule>,
381 allocator_module: Option<CompiledModule>,
382 metadata_module: CompiledModule,
383 link: rustc::middle::cstore::LinkMeta,
384 metadata: rustc::middle::cstore::EncodedMetadata,
385 windows_subsystem: Option<String>,
386 linker_info: back::linker::LinkerInfo,
387 crate_info: CrateInfo,
390 // Misc info we load from metadata to persist beyond the tcx
392 panic_runtime: Option<CrateNum>,
393 compiler_builtins: Option<CrateNum>,
394 profiler_runtime: Option<CrateNum>,
395 sanitizer_runtime: Option<CrateNum>,
396 is_no_builtins: FxHashSet<CrateNum>,
397 native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
398 crate_name: FxHashMap<CrateNum, String>,
399 used_libraries: Lrc<Vec<NativeLibrary>>,
400 link_args: Lrc<Vec<String>>,
401 used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
402 used_crates_static: Vec<(CrateNum, LibSource)>,
403 used_crates_dynamic: Vec<(CrateNum, LibSource)>,
406 __build_diagnostic_array! { librustc_trans, DIAGNOSTICS }