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 syntax_pos::symbol::Symbol;
42 #[macro_use] 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_target;
52 #[macro_use] extern crate rustc_data_structures;
53 extern crate rustc_demangle;
54 extern crate rustc_incremental;
55 extern crate rustc_llvm;
56 extern crate rustc_platform_intrinsics as intrinsics;
57 extern crate rustc_codegen_utils;
58 extern crate rustc_codegen_ssa;
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;
71 use time_graph::TimeGraph;
72 use std::sync::mpsc::Receiver;
73 use back::write::{self, OngoingCodegen};
74 use syntax_pos::symbol::InternedString;
75 use rustc::mir::mono::Stats;
77 pub use llvm_util::target_features;
80 use rustc_data_structures::sync::Lrc;
82 use rustc::dep_graph::DepGraph;
83 use rustc::hir::def_id::CrateNum;
84 use rustc::middle::allocator::AllocatorKind;
85 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
86 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
87 use rustc::middle::lang_items::LangItem;
88 use rustc::session::{Session, CompileIncomplete};
89 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
90 use rustc::ty::{self, TyCtxt};
91 use rustc::util::time_graph;
92 use rustc::util::nodemap::{FxHashSet, FxHashMap};
93 use rustc::util::profiling::ProfileCategory;
94 use rustc_mir::monomorphize;
95 use rustc_codegen_ssa::{ModuleCodegen, CompiledModule};
96 use rustc_codegen_utils::codegen_backend::CodegenBackend;
97 use rustc_data_structures::svh::Svh;
128 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
129 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
140 pub struct LlvmCodegenBackend(());
142 impl BackendMethods for LlvmCodegenBackend {
143 type Module = ModuleLlvm;
144 type OngoingCodegen = OngoingCodegen;
146 fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
147 ModuleLlvm::new(sess, mod_name)
149 fn write_metadata<'b, 'gcx>(
151 tcx: TyCtxt<'b, 'gcx, 'gcx>,
152 metadata: &ModuleLlvm
153 ) -> EncodedMetadata {
154 base::write_metadata(tcx, metadata)
156 fn start_async_codegen(
159 time_graph: Option<TimeGraph>,
160 metadata: EncodedMetadata,
161 coordinator_receive: Receiver<Box<dyn Any + Send>>,
163 ) -> OngoingCodegen {
164 write::start_async_codegen(tcx, time_graph, metadata, coordinator_receive, total_cgus)
166 fn submit_pre_codegened_module_to_llvm(
168 codegen: &OngoingCodegen,
170 module: ModuleCodegen<ModuleLlvm>
172 codegen.submit_pre_codegened_module_to_llvm(tcx, module)
174 fn codegen_aborted(codegen: OngoingCodegen) {
175 codegen.codegen_aborted();
177 fn codegen_finished(&self, codegen: &OngoingCodegen, tcx: TyCtxt) {
178 codegen.codegen_finished(tcx)
180 fn check_for_errors(&self, codegen: &OngoingCodegen, sess: &Session) {
181 codegen.check_for_errors(sess)
183 fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
184 unsafe { allocator::codegen(tcx, mods, kind) }
186 fn wait_for_signal_to_codegen_item(&self, codegen: &OngoingCodegen) {
187 codegen.wait_for_signal_to_codegen_item()
189 fn compile_codegen_unit<'a, 'tcx: 'a>(
191 tcx: TyCtxt<'a, 'tcx, 'tcx>,
192 cgu_name: InternedString,
194 base::compile_codegen_unit(tcx, cgu_name)
199 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
200 impl !Sync for LlvmCodegenBackend {}
202 impl LlvmCodegenBackend {
203 pub fn new() -> Box<dyn CodegenBackend> {
204 box LlvmCodegenBackend(())
208 impl CodegenBackend for LlvmCodegenBackend {
209 fn init(&self, sess: &Session) {
210 llvm_util::init(sess); // Make sure llvm is inited
213 fn print(&self, req: PrintRequest, sess: &Session) {
215 PrintRequest::RelocationModels => {
216 println!("Available relocation models:");
217 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
218 println!(" {}", name);
222 PrintRequest::CodeModels => {
223 println!("Available code models:");
224 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
225 println!(" {}", name);
229 PrintRequest::TlsModels => {
230 println!("Available TLS models:");
231 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
232 println!(" {}", name);
236 req => llvm_util::print(req, sess),
240 fn print_passes(&self) {
241 llvm_util::print_passes();
244 fn print_version(&self) {
245 llvm_util::print_version();
248 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
252 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
253 target_features(sess)
256 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
257 box metadata::LlvmMetadataLoader
260 fn provide(&self, providers: &mut ty::query::Providers) {
261 rustc_codegen_utils::symbol_export::provide(providers);
262 rustc_codegen_utils::symbol_names::provide(providers);
263 base::provide_both(providers);
264 attributes::provide(providers);
267 fn provide_extern(&self, providers: &mut ty::query::Providers) {
268 rustc_codegen_utils::symbol_export::provide_extern(providers);
269 base::provide_both(providers);
270 attributes::provide_extern(providers);
273 fn codegen_crate<'a, 'tcx>(
275 tcx: TyCtxt<'a, 'tcx, 'tcx>,
276 rx: mpsc::Receiver<Box<dyn Any + Send>>
278 box base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
281 fn join_codegen_and_link(
283 ongoing_codegen: Box<dyn Any>,
285 dep_graph: &DepGraph,
286 outputs: &OutputFilenames,
287 ) -> Result<(), CompileIncomplete>{
288 use rustc::util::common::time;
289 let (ongoing_codegen, work_products) =
290 ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
291 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
293 if sess.opts.debugging_opts.incremental_info {
294 back::write::dump_incremental_data(&ongoing_codegen);
298 "serialize work products",
299 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
301 sess.compile_status()?;
303 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
304 i == OutputType::Metadata) {
308 // Run the linker on any artifacts that resulted from the LLVM run.
309 // This should produce either a finished executable or library.
310 sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
311 time(sess, "linking", || {
312 back::link::link_binary(sess, &ongoing_codegen,
313 outputs, &ongoing_codegen.crate_name.as_str());
315 sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
317 // Now that we won't touch anything in the incremental compilation directory
318 // any more, we can finalize it (which involves renaming it)
319 rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
325 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
327 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
328 LlvmCodegenBackend::new()
331 pub struct ModuleLlvm {
332 llcx: &'static mut llvm::Context,
333 llmod_raw: *const llvm::Module,
334 tm: &'static mut llvm::TargetMachine,
337 unsafe impl Send for ModuleLlvm { }
338 unsafe impl Sync for ModuleLlvm { }
341 fn new(sess: &Session, mod_name: &str) -> Self {
343 let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
344 let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
349 tm: create_target_machine(sess, false),
354 fn llmod(&self) -> &llvm::Module {
361 impl Drop for ModuleLlvm {
364 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
365 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
370 struct CodegenResults {
372 modules: Vec<CompiledModule>,
373 allocator_module: Option<CompiledModule>,
374 metadata_module: CompiledModule,
376 metadata: rustc::middle::cstore::EncodedMetadata,
377 windows_subsystem: Option<String>,
378 linker_info: rustc_codegen_utils::linker::LinkerInfo,
379 crate_info: CrateInfo,
382 /// Misc info we load from metadata to persist beyond the tcx
384 panic_runtime: Option<CrateNum>,
385 compiler_builtins: Option<CrateNum>,
386 profiler_runtime: Option<CrateNum>,
387 sanitizer_runtime: Option<CrateNum>,
388 is_no_builtins: FxHashSet<CrateNum>,
389 native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
390 crate_name: FxHashMap<CrateNum, String>,
391 used_libraries: Lrc<Vec<NativeLibrary>>,
392 link_args: Lrc<Vec<String>>,
393 used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
394 used_crates_static: Vec<(CrateNum, LibSource)>,
395 used_crates_dynamic: Vec<(CrateNum, LibSource)>,
396 wasm_imports: FxHashMap<String, String>,
397 lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
398 missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
401 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }