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(in_band_lifetimes)]
27 #![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;
59 extern crate rustc_fs_util;
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;
66 extern crate cc; // Used to locate MSVC
67 extern crate tempfile;
70 use back::bytecode::RLIB_BYTECODE_EXTENSION;
72 use time_graph::TimeGraph;
73 use std::sync::mpsc::Receiver;
74 use back::write::{self, OngoingCodegen};
76 pub use llvm_util::target_features;
79 use rustc_data_structures::sync::Lrc;
81 use rustc::dep_graph::DepGraph;
82 use rustc::hir::def_id::CrateNum;
83 use rustc::middle::allocator::AllocatorKind;
84 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
85 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
86 use rustc::middle::lang_items::LangItem;
87 use rustc::session::{Session, CompileIncomplete};
88 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
89 use rustc::ty::{self, TyCtxt};
90 use rustc::util::time_graph;
91 use rustc::util::nodemap::{FxHashSet, FxHashMap};
92 use rustc::util::profiling::ProfileCategory;
93 use rustc_mir::monomorphize;
94 use rustc_codegen_utils::{CompiledModule, ModuleKind};
95 use rustc_codegen_utils::codegen_backend::CodegenBackend;
96 use rustc_data_structures::svh::Svh;
127 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
128 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
139 pub struct LlvmCodegenBackend(());
141 impl BackendMethods for LlvmCodegenBackend {
142 type Metadata = ModuleLlvm;
143 type OngoingCodegen = OngoingCodegen;
145 fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
146 ModuleLlvm::new(sess, mod_name)
148 fn write_metadata<'a, 'gcx>(
150 tcx: TyCtxt<'a, 'gcx, 'gcx>,
151 metadata: &ModuleLlvm
152 ) -> EncodedMetadata {
153 base::write_metadata(tcx, metadata)
155 fn start_async_codegen(
158 time_graph: Option<TimeGraph>,
159 metadata: EncodedMetadata,
160 coordinator_receive: Receiver<Box<dyn Any + Send>>,
162 ) -> OngoingCodegen {
163 write::start_async_codegen(tcx, time_graph, metadata, coordinator_receive, total_cgus)
165 fn submit_pre_codegened_module_to_llvm(
167 codegen: &OngoingCodegen,
169 module: ModuleCodegen<ModuleLlvm>
171 codegen.submit_pre_codegened_module_to_llvm(tcx, module)
173 fn codegen_aborted(codegen: OngoingCodegen) {
174 codegen.codegen_aborted();
176 fn codegen_finished(&self, codegen: &OngoingCodegen, tcx: TyCtxt) {
177 codegen.codegen_finished(tcx)
179 fn check_for_errors(&self, codegen: &OngoingCodegen, sess: &Session) {
180 codegen.check_for_errors(sess)
182 fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
183 unsafe { allocator::codegen(tcx, mods, kind) }
185 fn wait_for_signal_to_codegen_item(&self, codegen: &OngoingCodegen) {
186 codegen.wait_for_signal_to_codegen_item()
191 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
192 impl !Sync for LlvmCodegenBackend {}
194 impl LlvmCodegenBackend {
195 pub fn new() -> Box<dyn CodegenBackend> {
196 box LlvmCodegenBackend(())
200 impl CodegenBackend for LlvmCodegenBackend {
201 fn init(&self, sess: &Session) {
202 llvm_util::init(sess); // Make sure llvm is inited
205 fn print(&self, req: PrintRequest, sess: &Session) {
207 PrintRequest::RelocationModels => {
208 println!("Available relocation models:");
209 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
210 println!(" {}", name);
214 PrintRequest::CodeModels => {
215 println!("Available code models:");
216 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
217 println!(" {}", name);
221 PrintRequest::TlsModels => {
222 println!("Available TLS models:");
223 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
224 println!(" {}", name);
228 req => llvm_util::print(req, sess),
232 fn print_passes(&self) {
233 llvm_util::print_passes();
236 fn print_version(&self) {
237 llvm_util::print_version();
240 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
244 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
245 target_features(sess)
248 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
249 box metadata::LlvmMetadataLoader
252 fn provide(&self, providers: &mut ty::query::Providers) {
253 rustc_codegen_utils::symbol_export::provide(providers);
254 rustc_codegen_utils::symbol_names::provide(providers);
255 base::provide_both(providers);
256 attributes::provide(providers);
259 fn provide_extern(&self, providers: &mut ty::query::Providers) {
260 rustc_codegen_utils::symbol_export::provide_extern(providers);
261 base::provide_both(providers);
262 attributes::provide_extern(providers);
265 fn codegen_crate<'a, 'tcx>(
267 tcx: TyCtxt<'a, 'tcx, 'tcx>,
268 rx: mpsc::Receiver<Box<dyn Any + Send>>
270 box base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
273 fn join_codegen_and_link(
275 ongoing_codegen: Box<dyn Any>,
277 dep_graph: &DepGraph,
278 outputs: &OutputFilenames,
279 ) -> Result<(), CompileIncomplete>{
280 use rustc::util::common::time;
281 let (ongoing_codegen, work_products) =
282 ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
283 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
285 if sess.opts.debugging_opts.incremental_info {
286 back::write::dump_incremental_data(&ongoing_codegen);
290 "serialize work products",
291 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
293 sess.compile_status()?;
295 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
296 i == OutputType::Metadata) {
300 // Run the linker on any artifacts that resulted from the LLVM run.
301 // This should produce either a finished executable or library.
302 sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
303 time(sess, "linking", || {
304 back::link::link_binary(sess, &ongoing_codegen,
305 outputs, &ongoing_codegen.crate_name.as_str());
307 sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
309 // Now that we won't touch anything in the incremental compilation directory
310 // any more, we can finalize it (which involves renaming it)
311 rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
317 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
319 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
320 LlvmCodegenBackend::new()
323 pub struct ModuleCodegen<M> {
324 /// The name of the module. When the crate may be saved between
325 /// compilations, incremental compilation requires that name be
326 /// unique amongst **all** crates. Therefore, it should contain
327 /// something unique to this crate (e.g., a module path) as well
328 /// as the crate name and disambiguator.
329 /// We currently generate these names via CodegenUnit::build_cgu_name().
335 struct CachedModuleCodegen {
340 impl ModuleCodegen<ModuleLlvm> {
341 fn into_compiled_module(self,
344 emit_bc_compressed: bool,
345 outputs: &OutputFilenames) -> CompiledModule {
346 let object = if emit_obj {
347 Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
351 let bytecode = if emit_bc {
352 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
356 let bytecode_compressed = if emit_bc_compressed {
357 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
358 .with_extension(RLIB_BYTECODE_EXTENSION))
364 name: self.name.clone(),
373 pub struct ModuleLlvm {
374 llcx: &'static mut llvm::Context,
375 llmod_raw: *const llvm::Module,
376 tm: &'static mut llvm::TargetMachine,
379 unsafe impl Send for ModuleLlvm { }
380 unsafe impl Sync for ModuleLlvm { }
383 fn new(sess: &Session, mod_name: &str) -> Self {
385 let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
386 let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
391 tm: create_target_machine(sess, false),
396 fn llmod(&self) -> &llvm::Module {
403 impl Drop for ModuleLlvm {
406 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
407 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
412 struct CodegenResults {
414 modules: Vec<CompiledModule>,
415 allocator_module: Option<CompiledModule>,
416 metadata_module: CompiledModule,
418 metadata: rustc::middle::cstore::EncodedMetadata,
419 windows_subsystem: Option<String>,
420 linker_info: rustc_codegen_utils::linker::LinkerInfo,
421 crate_info: CrateInfo,
424 /// Misc info we load from metadata to persist beyond the tcx
426 panic_runtime: Option<CrateNum>,
427 compiler_builtins: Option<CrateNum>,
428 profiler_runtime: Option<CrateNum>,
429 sanitizer_runtime: Option<CrateNum>,
430 is_no_builtins: FxHashSet<CrateNum>,
431 native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
432 crate_name: FxHashMap<CrateNum, String>,
433 used_libraries: Lrc<Vec<NativeLibrary>>,
434 link_args: Lrc<Vec<String>>,
435 used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
436 used_crates_static: Vec<(CrateNum, LibSource)>,
437 used_crates_dynamic: Vec<(CrateNum, LibSource)>,
438 wasm_imports: FxHashMap<String, String>,
439 lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
440 missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
443 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }