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;
43 #[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;
70 use rustc_codegen_ssa::interfaces::*;
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;
81 use rustc::dep_graph::DepGraph;
82 use rustc::middle::allocator::AllocatorKind;
83 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
84 use rustc::session::{Session, CompileIncomplete};
85 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
86 use rustc::ty::{self, TyCtxt};
87 use rustc::util::time_graph;
88 use rustc::util::profiling::ProfileCategory;
89 use rustc_mir::monomorphize;
90 use rustc_codegen_ssa::{ModuleCodegen, CompiledModule, CachedModuleCodegen, CrateInfo};
91 use rustc_codegen_utils::codegen_backend::CodegenBackend;
92 use rustc_data_structures::svh::Svh;
120 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
121 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
130 pub struct LlvmCodegenBackend(());
132 impl BackendMethods for LlvmCodegenBackend {
133 type Module = ModuleLlvm;
134 type OngoingCodegen = OngoingCodegen;
136 fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
137 ModuleLlvm::new(sess, mod_name)
139 fn write_metadata<'b, 'gcx>(
141 tcx: TyCtxt<'b, 'gcx, 'gcx>,
142 metadata: &ModuleLlvm
143 ) -> EncodedMetadata {
144 base::write_metadata(tcx, metadata)
146 fn start_async_codegen(
149 time_graph: Option<TimeGraph>,
150 metadata: EncodedMetadata,
151 coordinator_receive: Receiver<Box<dyn Any + Send>>,
153 ) -> OngoingCodegen {
154 write::start_async_codegen(tcx, time_graph, metadata, coordinator_receive, total_cgus)
156 fn submit_pre_codegened_module_to_backend(
158 codegen: &OngoingCodegen,
160 module: ModuleCodegen<ModuleLlvm>
162 codegen.submit_pre_codegened_module_to_llvm(tcx, module)
164 fn submit_pre_lto_module_to_backend(&self, tcx: TyCtxt, module: CachedModuleCodegen) {
165 write::submit_pre_lto_module_to_llvm(tcx, module)
167 fn submit_post_lto_module_to_backend(&self, tcx: TyCtxt, module: CachedModuleCodegen) {
168 write::submit_post_lto_module_to_llvm(tcx, module)
170 fn codegen_aborted(codegen: OngoingCodegen) {
171 codegen.codegen_aborted();
173 fn codegen_finished(&self, codegen: &OngoingCodegen, tcx: TyCtxt) {
174 codegen.codegen_finished(tcx)
176 fn check_for_errors(&self, codegen: &OngoingCodegen, sess: &Session) {
177 codegen.check_for_errors(sess)
179 fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
180 unsafe { allocator::codegen(tcx, mods, kind) }
182 fn wait_for_signal_to_codegen_item(&self, codegen: &OngoingCodegen) {
183 codegen.wait_for_signal_to_codegen_item()
185 fn compile_codegen_unit<'a, 'tcx: 'a>(
187 tcx: TyCtxt<'a, 'tcx, 'tcx>,
188 cgu_name: InternedString,
190 base::compile_codegen_unit(tcx, cgu_name)
195 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
196 impl !Sync for LlvmCodegenBackend {}
198 impl LlvmCodegenBackend {
199 pub fn new() -> Box<dyn CodegenBackend> {
200 box LlvmCodegenBackend(())
204 impl CodegenBackend for LlvmCodegenBackend {
205 fn init(&self, sess: &Session) {
206 llvm_util::init(sess); // Make sure llvm is inited
209 fn print(&self, req: PrintRequest, sess: &Session) {
211 PrintRequest::RelocationModels => {
212 println!("Available relocation models:");
213 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
214 println!(" {}", name);
218 PrintRequest::CodeModels => {
219 println!("Available code models:");
220 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
221 println!(" {}", name);
225 PrintRequest::TlsModels => {
226 println!("Available TLS models:");
227 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
228 println!(" {}", name);
232 req => llvm_util::print(req, sess),
236 fn print_passes(&self) {
237 llvm_util::print_passes();
240 fn print_version(&self) {
241 llvm_util::print_version();
244 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
248 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
249 target_features(sess)
252 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
253 box metadata::LlvmMetadataLoader
256 fn provide(&self, providers: &mut ty::query::Providers) {
257 rustc_codegen_utils::symbol_export::provide(providers);
258 rustc_codegen_utils::symbol_names::provide(providers);
259 rustc_codegen_ssa::base::provide_both(providers);
260 attributes::provide(providers);
263 fn provide_extern(&self, providers: &mut ty::query::Providers) {
264 rustc_codegen_utils::symbol_export::provide_extern(providers);
265 rustc_codegen_ssa::base::provide_both(providers);
266 attributes::provide_extern(providers);
269 fn codegen_crate<'a, 'tcx>(
271 tcx: TyCtxt<'a, 'tcx, 'tcx>,
272 rx: mpsc::Receiver<Box<dyn Any + Send>>
274 box rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
277 fn join_codegen_and_link(
279 ongoing_codegen: Box<dyn Any>,
281 dep_graph: &DepGraph,
282 outputs: &OutputFilenames,
283 ) -> Result<(), CompileIncomplete>{
284 use rustc::util::common::time;
285 let (ongoing_codegen, work_products) =
286 ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
287 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
289 if sess.opts.debugging_opts.incremental_info {
290 back::write::dump_incremental_data(&ongoing_codegen);
294 "serialize work products",
295 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
297 sess.compile_status()?;
299 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
300 i == OutputType::Metadata) {
304 // Run the linker on any artifacts that resulted from the LLVM run.
305 // This should produce either a finished executable or library.
306 sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
307 time(sess, "linking", || {
308 back::link::link_binary(sess, &ongoing_codegen,
309 outputs, &ongoing_codegen.crate_name.as_str());
311 sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
313 // Now that we won't touch anything in the incremental compilation directory
314 // any more, we can finalize it (which involves renaming it)
315 rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
321 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
323 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
324 LlvmCodegenBackend::new()
327 pub struct ModuleLlvm {
328 llcx: &'static mut llvm::Context,
329 llmod_raw: *const llvm::Module,
330 tm: &'static mut llvm::TargetMachine,
333 unsafe impl Send for ModuleLlvm { }
334 unsafe impl Sync for ModuleLlvm { }
337 fn new(sess: &Session, mod_name: &str) -> Self {
339 let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
340 let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
345 tm: create_target_machine(sess, false),
350 fn llmod(&self) -> &llvm::Module {
357 impl Drop for ModuleLlvm {
360 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
361 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
366 struct CodegenResults {
368 modules: Vec<CompiledModule>,
369 allocator_module: Option<CompiledModule>,
370 metadata_module: CompiledModule,
372 metadata: rustc::middle::cstore::EncodedMetadata,
373 windows_subsystem: Option<String>,
374 linker_info: rustc_codegen_utils::linker::LinkerInfo,
375 crate_info: CrateInfo,
377 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }