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::traits::*;
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_::*; }
133 pub struct LlvmCodegenBackend(());
135 impl ExtraBackendMethods for LlvmCodegenBackend {
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 codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
147 unsafe { allocator::codegen(tcx, mods, kind) }
149 fn compile_codegen_unit<'a, 'tcx: 'a>(
151 tcx: TyCtxt<'a, 'tcx, 'tcx>,
152 cgu_name: InternedString,
154 base::compile_codegen_unit(tcx, cgu_name)
156 fn target_machine_factory(
161 Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
162 back::write::target_machine_factory(sess, find_features)
164 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
165 llvm_util::target_cpu(sess)
169 impl WriteBackendMethods for LlvmCodegenBackend {
170 type Module = ModuleLlvm;
171 type ModuleBuffer = back::lto::ModuleBuffer;
172 type Context = llvm::Context;
173 type TargetMachine = &'static mut llvm::TargetMachine;
174 type ThinData = back::lto::ThinData;
175 type ThinBuffer = back::lto::ThinBuffer;
176 fn print_pass_timings(&self) {
177 unsafe { llvm::LLVMRustPrintPassTimings(); }
180 cgcx: &CodegenContext<Self>,
181 modules: Vec<ModuleCodegen<Self::Module>>,
182 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
183 timeline: &mut Timeline
184 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
185 back::lto::run(cgcx, modules, cached_modules, timeline)
188 cgcx: &CodegenContext<Self>,
189 diag_handler: &Handler,
190 module: &ModuleCodegen<Self::Module>,
191 config: &ModuleConfig,
192 timeline: &mut Timeline
193 ) -> Result<(), FatalError> {
194 back::write::optimize(cgcx, diag_handler, module, config, timeline)
196 unsafe fn optimize_thin(
197 cgcx: &CodegenContext<Self>,
198 thin: &mut ThinModule<Self>,
199 timeline: &mut Timeline
200 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
201 back::lto::optimize_thin_module(thin, cgcx, timeline)
204 cgcx: &CodegenContext<Self>,
205 diag_handler: &Handler,
206 module: ModuleCodegen<Self::Module>,
207 config: &ModuleConfig,
208 timeline: &mut Timeline
209 ) -> Result<CompiledModule, FatalError> {
210 back::write::codegen(cgcx, diag_handler, module, config, timeline)
212 fn run_lto_pass_manager(
213 cgcx: &CodegenContext<Self>,
214 module: &ModuleCodegen<Self::Module>,
215 config: &ModuleConfig,
218 back::lto::run_pass_manager(cgcx, module, config, thin)
222 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
223 unsafe impl Sync for LlvmCodegenBackend {}
225 impl LlvmCodegenBackend {
226 pub fn new() -> Box<dyn CodegenBackend> {
227 box LlvmCodegenBackend(())
231 impl CodegenBackend for LlvmCodegenBackend {
232 fn init(&self, sess: &Session) {
233 llvm_util::init(sess); // Make sure llvm is inited
236 fn print(&self, req: PrintRequest, sess: &Session) {
238 PrintRequest::RelocationModels => {
239 println!("Available relocation models:");
240 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
241 println!(" {}", name);
245 PrintRequest::CodeModels => {
246 println!("Available code models:");
247 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
248 println!(" {}", name);
252 PrintRequest::TlsModels => {
253 println!("Available TLS models:");
254 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
255 println!(" {}", name);
259 req => llvm_util::print(req, sess),
263 fn print_passes(&self) {
264 llvm_util::print_passes();
267 fn print_version(&self) {
268 llvm_util::print_version();
271 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
275 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
276 target_features(sess)
279 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
280 box metadata::LlvmMetadataLoader
283 fn provide(&self, providers: &mut ty::query::Providers) {
284 rustc_codegen_utils::symbol_names::provide(providers);
285 rustc_codegen_ssa::back::symbol_export::provide(providers);
286 rustc_codegen_ssa::base::provide_both(providers);
287 attributes::provide(providers);
290 fn provide_extern(&self, providers: &mut ty::query::Providers) {
291 rustc_codegen_ssa::back::symbol_export::provide_extern(providers);
292 rustc_codegen_ssa::base::provide_both(providers);
293 attributes::provide_extern(providers);
296 fn codegen_crate<'b, 'tcx>(
298 tcx: TyCtxt<'b, 'tcx, 'tcx>,
299 rx: mpsc::Receiver<Box<dyn Any + Send>>
301 box rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
304 fn join_codegen_and_link(
306 ongoing_codegen: Box<dyn Any>,
308 dep_graph: &DepGraph,
309 outputs: &OutputFilenames,
310 ) -> Result<(), CompileIncomplete>{
311 use rustc::util::common::time;
312 let (codegen_results, work_products) =
313 ongoing_codegen.downcast::
314 <rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
315 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
317 if sess.opts.debugging_opts.incremental_info {
318 rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
322 "serialize work products",
323 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
325 sess.compile_status()?;
327 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
328 i == OutputType::Metadata) {
332 // Run the linker on any artifacts that resulted from the LLVM run.
333 // This should produce either a finished executable or library.
334 sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
335 time(sess, "linking", || {
336 back::link::link_binary(sess, &codegen_results,
337 outputs, &codegen_results.crate_name.as_str());
339 sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
341 // Now that we won't touch anything in the incremental compilation directory
342 // any more, we can finalize it (which involves renaming it)
343 rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
349 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
351 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
352 LlvmCodegenBackend::new()
355 pub struct ModuleLlvm {
356 llcx: &'static mut llvm::Context,
357 llmod_raw: *const llvm::Module,
358 tm: &'static mut llvm::TargetMachine,
361 unsafe impl Send for ModuleLlvm { }
362 unsafe impl Sync for ModuleLlvm { }
365 fn new(sess: &Session, mod_name: &str) -> Self {
367 let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
368 let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
373 tm: create_target_machine(sess, false),
378 fn llmod(&self) -> &llvm::Module {
385 impl Drop for ModuleLlvm {
388 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
389 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
394 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }