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 rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig};
72 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
73 use rustc_codegen_ssa::CompiledModule;
74 use errors::{FatalError, Handler};
75 use rustc::dep_graph::WorkProduct;
76 use rustc::util::time_graph::Timeline;
77 use syntax_pos::symbol::InternedString;
78 use rustc::mir::mono::Stats;
79 pub use llvm_util::target_features;
81 use std::sync::{mpsc, Arc};
83 use rustc::dep_graph::DepGraph;
84 use rustc::middle::allocator::AllocatorKind;
85 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
86 use rustc::session::{Session, CompileIncomplete};
87 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
88 use rustc::ty::{self, TyCtxt};
89 use rustc::util::time_graph;
90 use rustc::util::profiling::ProfileCategory;
91 use rustc_mir::monomorphize;
92 use rustc_codegen_ssa::ModuleCodegen;
93 use rustc_codegen_utils::codegen_backend::CodegenBackend;
121 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
122 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
132 pub struct LlvmCodegenBackend(());
134 impl ExtraBackendMethods for LlvmCodegenBackend {
135 fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
136 ModuleLlvm::new(sess, mod_name)
138 fn write_metadata<'b, 'gcx>(
140 tcx: TyCtxt<'b, 'gcx, 'gcx>,
141 metadata: &ModuleLlvm
142 ) -> EncodedMetadata {
143 base::write_metadata(tcx, metadata)
145 fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
146 unsafe { allocator::codegen(tcx, mods, kind) }
148 fn compile_codegen_unit<'a, 'tcx: 'a>(
150 tcx: TyCtxt<'a, 'tcx, 'tcx>,
151 cgu_name: InternedString,
153 base::compile_codegen_unit(tcx, cgu_name)
155 fn target_machine_factory(
160 Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
161 back::write::target_machine_factory(sess, find_features)
163 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
164 llvm_util::target_cpu(sess)
168 impl Clone for &'static mut llvm::TargetMachine {
169 fn clone(&self) -> Self {
170 // This method should never be called. It is put here because in
171 // rustc_codegen_ssa::back::write::CodegenContext, the TargetMachine is contained in a
172 // closure returned by a function under an Arc. The clone-deriving algorithm works when the
173 // struct contains the original LLVM TargetMachine type but not any more when supplied with
174 // a generic type. Hence this dummy Clone implementation.
179 impl WriteBackendMethods for LlvmCodegenBackend {
180 type Module = ModuleLlvm;
181 type ModuleBuffer = back::lto::ModuleBuffer;
182 type Context = llvm::Context;
183 type TargetMachine = &'static mut llvm::TargetMachine;
184 type ThinData = back::lto::ThinData;
185 type ThinBuffer = back::lto::ThinBuffer;
186 fn print_pass_timings(&self) {
187 unsafe { llvm::LLVMRustPrintPassTimings(); }
190 cgcx: &CodegenContext<Self>,
191 modules: Vec<ModuleCodegen<Self::Module>>,
192 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
193 timeline: &mut Timeline
194 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
195 back::lto::run(cgcx, modules, cached_modules, timeline)
198 cgcx: &CodegenContext<Self>,
199 diag_handler: &Handler,
200 module: &ModuleCodegen<Self::Module>,
201 config: &ModuleConfig,
202 timeline: &mut Timeline
203 ) -> Result<(), FatalError> {
204 back::write::optimize(cgcx, diag_handler, module, config, timeline)
206 unsafe fn optimize_thin(
207 cgcx: &CodegenContext<Self>,
208 thin: &mut ThinModule<Self>,
209 timeline: &mut Timeline
210 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
211 back::lto::optimize_thin_module(thin, cgcx, timeline)
214 cgcx: &CodegenContext<Self>,
215 diag_handler: &Handler,
216 module: ModuleCodegen<Self::Module>,
217 config: &ModuleConfig,
218 timeline: &mut Timeline
219 ) -> Result<CompiledModule, FatalError> {
220 back::write::codegen(cgcx, diag_handler, module, config, timeline)
222 fn run_lto_pass_manager(
223 cgcx: &CodegenContext<Self>,
224 module: &ModuleCodegen<Self::Module>,
225 config: &ModuleConfig,
228 back::lto::run_pass_manager(cgcx, module, config, thin)
232 unsafe impl<'a> Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
233 unsafe impl<'a> Sync for LlvmCodegenBackend {}
235 impl LlvmCodegenBackend {
236 pub fn new() -> Box<dyn CodegenBackend> {
237 box LlvmCodegenBackend(())
241 impl<'a> CodegenBackend for LlvmCodegenBackend {
242 fn init(&self, sess: &Session) {
243 llvm_util::init(sess); // Make sure llvm is inited
246 fn print(&self, req: PrintRequest, sess: &Session) {
248 PrintRequest::RelocationModels => {
249 println!("Available relocation models:");
250 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
251 println!(" {}", name);
255 PrintRequest::CodeModels => {
256 println!("Available code models:");
257 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
258 println!(" {}", name);
262 PrintRequest::TlsModels => {
263 println!("Available TLS models:");
264 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
265 println!(" {}", name);
269 req => llvm_util::print(req, sess),
273 fn print_passes(&self) {
274 llvm_util::print_passes();
277 fn print_version(&self) {
278 llvm_util::print_version();
281 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
285 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
286 target_features(sess)
289 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
290 box metadata::LlvmMetadataLoader
293 fn provide(&self, providers: &mut ty::query::Providers) {
294 rustc_codegen_utils::symbol_names::provide(providers);
295 rustc_codegen_ssa::back::symbol_export::provide(providers);
296 rustc_codegen_ssa::base::provide_both(providers);
297 attributes::provide(providers);
300 fn provide_extern(&self, providers: &mut ty::query::Providers) {
301 rustc_codegen_ssa::back::symbol_export::provide_extern(providers);
302 rustc_codegen_ssa::base::provide_both(providers);
303 attributes::provide_extern(providers);
306 fn codegen_crate<'b, 'tcx>(
308 tcx: TyCtxt<'b, 'tcx, 'tcx>,
309 rx: mpsc::Receiver<Box<dyn Any + Send>>
311 box rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
314 fn join_codegen_and_link(
316 ongoing_codegen: Box<dyn Any>,
318 dep_graph: &DepGraph,
319 outputs: &OutputFilenames,
320 ) -> Result<(), CompileIncomplete>{
321 use rustc::util::common::time;
322 let (codegen_results, work_products) =
323 ongoing_codegen.downcast::
324 <rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
325 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
327 if sess.opts.debugging_opts.incremental_info {
328 rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
332 "serialize work products",
333 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
335 sess.compile_status()?;
337 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
338 i == OutputType::Metadata) {
342 // Run the linker on any artifacts that resulted from the LLVM run.
343 // This should produce either a finished executable or library.
344 sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
345 time(sess, "linking", || {
346 back::link::link_binary(sess, &codegen_results,
347 outputs, &codegen_results.crate_name.as_str());
349 sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
351 // Now that we won't touch anything in the incremental compilation directory
352 // any more, we can finalize it (which involves renaming it)
353 rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
359 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
361 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
362 LlvmCodegenBackend::new()
365 pub struct ModuleLlvm {
366 llcx: &'static mut llvm::Context,
367 llmod_raw: *const llvm::Module,
368 tm: &'static mut llvm::TargetMachine,
371 unsafe impl Send for ModuleLlvm { }
372 unsafe impl Sync for ModuleLlvm { }
375 fn new(sess: &Session, mod_name: &str) -> Self {
377 let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
378 let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
383 tm: create_target_machine(sess, false),
388 fn llmod(&self) -> &llvm::Module {
395 impl Drop for ModuleLlvm {
398 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
399 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
404 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }