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(crate_visibility_modifier)]
24 #![feature(custom_attribute)]
25 #![feature(extern_types)]
26 #![feature(fs_read_write)]
27 #![feature(in_band_lifetimes)]
28 #![allow(unused_attributes)]
31 #![feature(range_contains)]
32 #![feature(rustc_diagnostic_macros)]
33 #![feature(slice_sort_by_cached_key)]
34 #![feature(optin_builtin_traits)]
35 #![feature(concat_idents)]
36 #![feature(link_args)]
37 #![feature(static_nobundle)]
39 use back::write::create_target_machine;
40 use rustc::dep_graph::WorkProduct;
41 use syntax_pos::symbol::Symbol;
43 #[macro_use] extern crate bitflags;
46 #[macro_use] extern crate rustc;
47 extern crate jobserver;
48 extern crate num_cpus;
49 extern crate rustc_mir;
50 extern crate rustc_allocator;
51 extern crate rustc_apfloat;
52 extern crate rustc_target;
53 #[macro_use] extern crate rustc_data_structures;
54 extern crate rustc_demangle;
55 extern crate rustc_incremental;
56 extern crate rustc_llvm;
57 extern crate rustc_platform_intrinsics as intrinsics;
58 extern crate rustc_codegen_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
66 extern crate tempfile;
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::middle::lang_items::LangItem;
82 use rustc::session::{Session, CompileIncomplete};
83 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
84 use rustc::ty::{self, TyCtxt};
85 use rustc::util::time_graph;
86 use rustc::util::nodemap::{FxHashSet, FxHashMap};
87 use rustc_mir::monomorphize;
88 use rustc_codegen_utils::codegen_backend::CodegenBackend;
93 pub use rustc_codegen_utils::symbol_names;
100 pub mod symbol_export;
130 pub struct LlvmCodegenBackend(());
132 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
133 impl !Sync for LlvmCodegenBackend {}
135 impl LlvmCodegenBackend {
136 pub fn new() -> Box<dyn CodegenBackend> {
137 box LlvmCodegenBackend(())
141 impl CodegenBackend for LlvmCodegenBackend {
142 fn init(&self, sess: &Session) {
143 llvm_util::init(sess); // Make sure llvm is inited
146 fn print(&self, req: PrintRequest, sess: &Session) {
148 PrintRequest::RelocationModels => {
149 println!("Available relocation models:");
150 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
151 println!(" {}", name);
155 PrintRequest::CodeModels => {
156 println!("Available code models:");
157 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
158 println!(" {}", name);
162 PrintRequest::TlsModels => {
163 println!("Available TLS models:");
164 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
165 println!(" {}", name);
169 req => llvm_util::print(req, sess),
173 fn print_passes(&self) {
174 llvm_util::print_passes();
177 fn print_version(&self) {
178 llvm_util::print_version();
181 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
185 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
186 target_features(sess)
189 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
190 box metadata::LlvmMetadataLoader
193 fn provide(&self, providers: &mut ty::query::Providers) {
194 back::symbol_names::provide(providers);
195 back::symbol_export::provide(providers);
196 base::provide(providers);
197 attributes::provide(providers);
200 fn provide_extern(&self, providers: &mut ty::query::Providers) {
201 back::symbol_export::provide_extern(providers);
202 base::provide_extern(providers);
203 attributes::provide_extern(providers);
206 fn codegen_crate<'a, 'tcx>(
208 tcx: TyCtxt<'a, 'tcx, 'tcx>,
209 rx: mpsc::Receiver<Box<dyn Any + Send>>
211 box base::codegen_crate(tcx, rx)
214 fn join_codegen_and_link(
216 ongoing_codegen: Box<dyn Any>,
218 dep_graph: &DepGraph,
219 outputs: &OutputFilenames,
220 ) -> Result<(), CompileIncomplete>{
221 use rustc::util::common::time;
222 let (ongoing_codegen, work_products) =
223 ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
224 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
226 if sess.opts.debugging_opts.incremental_info {
227 back::write::dump_incremental_data(&ongoing_codegen);
231 "serialize work products",
232 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
234 sess.compile_status()?;
236 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
237 i == OutputType::Metadata) {
241 // Run the linker on any artifacts that resulted from the LLVM run.
242 // This should produce either a finished executable or library.
243 time(sess, "linking", || {
244 back::link::link_binary(sess, &ongoing_codegen,
245 outputs, &ongoing_codegen.crate_name.as_str());
248 // Now that we won't touch anything in the incremental compilation directory
249 // any more, we can finalize it (which involves renaming it)
250 rustc_incremental::finalize_session_directory(sess, ongoing_codegen.link.crate_hash);
256 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
258 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
259 LlvmCodegenBackend::new()
262 struct ModuleCodegen {
263 /// The name of the module. When the crate may be saved between
264 /// compilations, incremental compilation requires that name be
265 /// unique amongst **all** crates. Therefore, it should contain
266 /// something unique to this crate (e.g., a module path) as well
267 /// as the crate name and disambiguator.
270 source: ModuleSource,
274 #[derive(Copy, Clone, Debug, PartialEq)]
282 fn llvm(&self) -> Option<&ModuleLlvm> {
284 ModuleSource::Codegened(ref llvm) => Some(llvm),
285 ModuleSource::Preexisting(_) => None,
289 fn into_compiled_module(self,
292 emit_bc_compressed: bool,
293 outputs: &OutputFilenames) -> CompiledModule {
294 let pre_existing = match self.source {
295 ModuleSource::Preexisting(_) => true,
296 ModuleSource::Codegened(_) => false,
298 let object = if emit_obj {
299 Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
303 let bytecode = if emit_bc {
304 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
308 let bytecode_compressed = if emit_bc_compressed {
309 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
310 .with_extension(RLIB_BYTECODE_EXTENSION))
316 llmod_id: self.llmod_id,
317 name: self.name.clone(),
328 struct CompiledModule {
333 object: Option<PathBuf>,
334 bytecode: Option<PathBuf>,
335 bytecode_compressed: Option<PathBuf>,
339 /// Copy the `.o` files or whatever from the incr. comp. directory.
340 Preexisting(WorkProduct),
342 /// Rebuild from this LLVM module.
343 Codegened(ModuleLlvm),
347 llcx: &'static mut llvm::Context,
348 llmod_raw: *const llvm::Module,
349 tm: &'static mut llvm::TargetMachine,
352 unsafe impl Send for ModuleLlvm { }
353 unsafe impl Sync for ModuleLlvm { }
356 fn new(sess: &Session, mod_name: &str) -> Self {
358 let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
359 let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
364 tm: create_target_machine(sess, false),
369 fn llmod(&self) -> &llvm::Module {
376 impl Drop for ModuleLlvm {
379 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
380 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
385 struct CodegenResults {
387 modules: Vec<CompiledModule>,
388 allocator_module: Option<CompiledModule>,
389 metadata_module: CompiledModule,
390 link: rustc::middle::cstore::LinkMeta,
391 metadata: rustc::middle::cstore::EncodedMetadata,
392 windows_subsystem: Option<String>,
393 linker_info: back::linker::LinkerInfo,
394 crate_info: CrateInfo,
397 /// Misc info we load from metadata to persist beyond the tcx
399 panic_runtime: Option<CrateNum>,
400 compiler_builtins: Option<CrateNum>,
401 profiler_runtime: Option<CrateNum>,
402 sanitizer_runtime: Option<CrateNum>,
403 is_no_builtins: FxHashSet<CrateNum>,
404 native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
405 crate_name: FxHashMap<CrateNum, String>,
406 used_libraries: Lrc<Vec<NativeLibrary>>,
407 link_args: Lrc<Vec<String>>,
408 used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
409 used_crates_static: Vec<(CrateNum, LibSource)>,
410 used_crates_dynamic: Vec<(CrateNum, LibSource)>,
411 wasm_imports: FxHashMap<String, String>,
412 lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
413 missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
416 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }