5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
9 #![feature(box_patterns)]
10 #![feature(box_syntax)]
11 #![feature(crate_visibility_modifier)]
12 #![feature(custom_attribute)]
13 #![feature(extern_types)]
14 #![feature(in_band_lifetimes)]
15 #![allow(unused_attributes)]
18 #![feature(range_contains)]
19 #![feature(rustc_diagnostic_macros)]
20 #![feature(slice_sort_by_cached_key)]
21 #![feature(optin_builtin_traits)]
22 #![feature(concat_idents)]
23 #![feature(link_args)]
24 #![feature(static_nobundle)]
26 use back::write::create_target_machine;
27 use syntax_pos::symbol::Symbol;
30 #[macro_use] extern crate bitflags;
32 #[macro_use] extern crate rustc;
33 extern crate jobserver;
34 extern crate num_cpus;
35 extern crate rustc_mir;
36 extern crate rustc_allocator;
37 extern crate rustc_apfloat;
38 extern crate rustc_target;
39 #[macro_use] extern crate rustc_data_structures;
40 extern crate rustc_demangle;
41 extern crate rustc_incremental;
42 extern crate rustc_llvm;
43 extern crate rustc_codegen_utils;
44 extern crate rustc_codegen_ssa;
45 extern crate rustc_fs_util;
47 #[macro_use] extern crate log;
48 #[macro_use] extern crate syntax;
49 extern crate syntax_pos;
50 extern crate rustc_errors as errors;
51 extern crate serialize;
52 extern crate cc; // Used to locate MSVC
53 extern crate tempfile;
56 use rustc_codegen_ssa::traits::*;
57 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig};
58 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
59 use rustc_codegen_ssa::CompiledModule;
60 use errors::{FatalError, Handler};
61 use rustc::dep_graph::WorkProduct;
62 use rustc::util::time_graph::Timeline;
63 use syntax_pos::symbol::InternedString;
64 use rustc::mir::mono::Stats;
65 pub use llvm_util::target_features;
67 use std::sync::{mpsc, Arc};
69 use rustc::dep_graph::DepGraph;
70 use rustc::middle::allocator::AllocatorKind;
71 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
72 use rustc::session::{Session, CompileIncomplete};
73 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest, OptLevel};
74 use rustc::ty::{self, TyCtxt};
75 use rustc::util::time_graph;
76 use rustc::util::profiling::ProfileCategory;
77 use rustc_mir::monomorphize;
78 use rustc_codegen_ssa::ModuleCodegen;
79 use rustc_codegen_utils::codegen_backend::CodegenBackend;
107 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
108 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
119 pub struct LlvmCodegenBackend(());
121 impl ExtraBackendMethods for LlvmCodegenBackend {
122 fn new_metadata(&self, tcx: TyCtxt, mod_name: &str) -> ModuleLlvm {
123 ModuleLlvm::new(tcx, mod_name)
125 fn write_metadata<'b, 'gcx>(
127 tcx: TyCtxt<'b, 'gcx, 'gcx>,
128 metadata: &ModuleLlvm
129 ) -> EncodedMetadata {
130 base::write_metadata(tcx, metadata)
132 fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
133 unsafe { allocator::codegen(tcx, mods, kind) }
135 fn compile_codegen_unit<'a, 'tcx: 'a>(
137 tcx: TyCtxt<'a, 'tcx, 'tcx>,
138 cgu_name: InternedString,
140 base::compile_codegen_unit(tcx, cgu_name)
142 fn target_machine_factory(
148 Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
149 back::write::target_machine_factory(sess, optlvl, find_features)
151 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
152 llvm_util::target_cpu(sess)
156 impl WriteBackendMethods for LlvmCodegenBackend {
157 type Module = ModuleLlvm;
158 type ModuleBuffer = back::lto::ModuleBuffer;
159 type Context = llvm::Context;
160 type TargetMachine = &'static mut llvm::TargetMachine;
161 type ThinData = back::lto::ThinData;
162 type ThinBuffer = back::lto::ThinBuffer;
163 fn print_pass_timings(&self) {
164 unsafe { llvm::LLVMRustPrintPassTimings(); }
167 cgcx: &CodegenContext<Self>,
168 modules: Vec<ModuleCodegen<Self::Module>>,
169 timeline: &mut Timeline
170 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
171 back::lto::run_fat(cgcx, modules, timeline)
174 cgcx: &CodegenContext<Self>,
175 modules: Vec<(String, Self::ThinBuffer)>,
176 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
177 timeline: &mut Timeline
178 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
179 back::lto::run_thin(cgcx, modules, cached_modules, timeline)
182 cgcx: &CodegenContext<Self>,
183 diag_handler: &Handler,
184 module: &ModuleCodegen<Self::Module>,
185 config: &ModuleConfig,
186 timeline: &mut Timeline
187 ) -> Result<(), FatalError> {
188 back::write::optimize(cgcx, diag_handler, module, config, timeline)
190 unsafe fn optimize_thin(
191 cgcx: &CodegenContext<Self>,
192 thin: &mut ThinModule<Self>,
193 timeline: &mut Timeline
194 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
195 back::lto::optimize_thin_module(thin, cgcx, timeline)
198 cgcx: &CodegenContext<Self>,
199 diag_handler: &Handler,
200 module: ModuleCodegen<Self::Module>,
201 config: &ModuleConfig,
202 timeline: &mut Timeline
203 ) -> Result<CompiledModule, FatalError> {
204 back::write::codegen(cgcx, diag_handler, module, config, timeline)
207 cgcx: &CodegenContext<Self>,
208 module: ModuleCodegen<Self::Module>
209 ) -> (String, Self::ThinBuffer) {
210 back::lto::prepare_thin(cgcx, module)
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(tcx: TyCtxt, mod_name: &str) -> Self {
367 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
368 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
373 tm: create_target_machine(tcx, 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 }