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(rustc_diagnostic_macros)]
19 #![feature(optin_builtin_traits)]
20 #![feature(concat_idents)]
21 #![feature(link_args)]
22 #![feature(static_nobundle)]
23 #![deny(rust_2018_idioms)]
24 #![allow(explicit_outlives_requirements)]
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 rustc_mir;
34 extern crate rustc_allocator;
35 extern crate rustc_target;
36 #[macro_use] extern crate rustc_data_structures;
37 extern crate rustc_incremental;
38 extern crate rustc_codegen_utils;
39 extern crate rustc_codegen_ssa;
40 extern crate rustc_fs_util;
42 #[macro_use] extern crate log;
43 #[macro_use] extern crate syntax;
44 extern crate syntax_pos;
45 extern crate rustc_errors as errors;
46 extern crate serialize;
47 extern crate tempfile;
49 use rustc_codegen_ssa::traits::*;
50 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, FatLTOInput};
51 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
52 use rustc_codegen_ssa::CompiledModule;
53 use errors::{FatalError, Handler};
54 use rustc::dep_graph::WorkProduct;
55 use syntax_pos::symbol::InternedString;
56 use rustc::mir::mono::Stats;
57 pub use llvm_util::target_features;
59 use std::sync::{mpsc, Arc};
61 use rustc::dep_graph::DepGraph;
62 use rustc::middle::allocator::AllocatorKind;
63 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
64 use rustc::session::Session;
65 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest, OptLevel};
66 use rustc::ty::{self, TyCtxt};
67 use rustc::util::profiling::ProfileCategory;
68 use rustc::util::common::ErrorReported;
69 use rustc_mir::monomorphize;
70 use rustc_codegen_ssa::ModuleCodegen;
71 use rustc_codegen_utils::codegen_backend::CodegenBackend;
99 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
100 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
111 pub struct LlvmCodegenBackend(());
113 impl ExtraBackendMethods for LlvmCodegenBackend {
114 fn new_metadata(&self, tcx: TyCtxt<'_, '_, '_>, mod_name: &str) -> ModuleLlvm {
115 ModuleLlvm::new(tcx, mod_name)
117 fn write_metadata<'b, 'gcx>(
119 tcx: TyCtxt<'b, 'gcx, 'gcx>,
120 metadata: &mut ModuleLlvm
121 ) -> EncodedMetadata {
122 base::write_metadata(tcx, metadata)
124 fn codegen_allocator<'b, 'gcx>(
126 tcx: TyCtxt<'b, 'gcx, 'gcx>,
127 mods: &mut ModuleLlvm,
130 unsafe { allocator::codegen(tcx, mods, kind) }
132 fn compile_codegen_unit<'a, 'tcx: 'a>(
134 tcx: TyCtxt<'a, 'tcx, 'tcx>,
135 cgu_name: InternedString,
137 base::compile_codegen_unit(tcx, cgu_name)
139 fn target_machine_factory(
145 Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
146 back::write::target_machine_factory(sess, optlvl, find_features)
148 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
149 llvm_util::target_cpu(sess)
153 impl WriteBackendMethods for LlvmCodegenBackend {
154 type Module = ModuleLlvm;
155 type ModuleBuffer = back::lto::ModuleBuffer;
156 type Context = llvm::Context;
157 type TargetMachine = &'static mut llvm::TargetMachine;
158 type ThinData = back::lto::ThinData;
159 type ThinBuffer = back::lto::ThinBuffer;
160 fn print_pass_timings(&self) {
161 unsafe { llvm::LLVMRustPrintPassTimings(); }
164 cgcx: &CodegenContext<Self>,
165 modules: Vec<FatLTOInput<Self>>,
166 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
167 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
168 back::lto::run_fat(cgcx, modules, cached_modules)
171 cgcx: &CodegenContext<Self>,
172 modules: Vec<(String, Self::ThinBuffer)>,
173 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
174 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
175 back::lto::run_thin(cgcx, modules, cached_modules)
178 cgcx: &CodegenContext<Self>,
179 diag_handler: &Handler,
180 module: &ModuleCodegen<Self::Module>,
181 config: &ModuleConfig,
182 ) -> Result<(), FatalError> {
183 back::write::optimize(cgcx, diag_handler, module, config)
185 unsafe fn optimize_thin(
186 cgcx: &CodegenContext<Self>,
187 thin: &mut ThinModule<Self>,
188 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
189 back::lto::optimize_thin_module(thin, cgcx)
192 cgcx: &CodegenContext<Self>,
193 diag_handler: &Handler,
194 module: ModuleCodegen<Self::Module>,
195 config: &ModuleConfig,
196 ) -> Result<CompiledModule, FatalError> {
197 back::write::codegen(cgcx, diag_handler, module, config)
200 module: ModuleCodegen<Self::Module>
201 ) -> (String, Self::ThinBuffer) {
202 back::lto::prepare_thin(module)
205 module: ModuleCodegen<Self::Module>
206 ) -> (String, Self::ModuleBuffer) {
207 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
209 fn run_lto_pass_manager(
210 cgcx: &CodegenContext<Self>,
211 module: &ModuleCodegen<Self::Module>,
212 config: &ModuleConfig,
215 back::lto::run_pass_manager(cgcx, module, config, thin)
219 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
220 unsafe impl Sync for LlvmCodegenBackend {}
222 impl LlvmCodegenBackend {
223 pub fn new() -> Box<dyn CodegenBackend> {
224 box LlvmCodegenBackend(())
228 impl CodegenBackend for LlvmCodegenBackend {
229 fn init(&self, sess: &Session) {
230 llvm_util::init(sess); // Make sure llvm is inited
233 fn print(&self, req: PrintRequest, sess: &Session) {
235 PrintRequest::RelocationModels => {
236 println!("Available relocation models:");
237 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
238 println!(" {}", name);
242 PrintRequest::CodeModels => {
243 println!("Available code models:");
244 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
245 println!(" {}", name);
249 PrintRequest::TlsModels => {
250 println!("Available TLS models:");
251 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
252 println!(" {}", name);
256 req => llvm_util::print(req, sess),
260 fn print_passes(&self) {
261 llvm_util::print_passes();
264 fn print_version(&self) {
265 llvm_util::print_version();
268 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
272 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
273 target_features(sess)
276 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
277 box metadata::LlvmMetadataLoader
280 fn provide(&self, providers: &mut ty::query::Providers<'_>) {
281 rustc_codegen_utils::symbol_names::provide(providers);
282 rustc_codegen_ssa::back::symbol_export::provide(providers);
283 rustc_codegen_ssa::base::provide_both(providers);
284 attributes::provide(providers);
287 fn provide_extern(&self, providers: &mut ty::query::Providers<'_>) {
288 rustc_codegen_ssa::back::symbol_export::provide_extern(providers);
289 rustc_codegen_ssa::base::provide_both(providers);
290 attributes::provide_extern(providers);
293 fn codegen_crate<'b, 'tcx>(
295 tcx: TyCtxt<'b, 'tcx, 'tcx>,
296 rx: mpsc::Receiver<Box<dyn Any + Send>>
298 box rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
301 fn join_codegen_and_link(
303 ongoing_codegen: Box<dyn Any>,
305 dep_graph: &DepGraph,
306 outputs: &OutputFilenames,
307 ) -> Result<(), ErrorReported>{
308 use rustc::util::common::time;
309 let (codegen_results, work_products) =
310 ongoing_codegen.downcast::
311 <rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
312 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
314 if sess.opts.debugging_opts.incremental_info {
315 rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
319 "serialize work products",
320 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
322 sess.compile_status()?;
324 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
325 i == OutputType::Metadata) {
329 // Run the linker on any artifacts that resulted from the LLVM run.
330 // This should produce either a finished executable or library.
331 sess.profiler(|p| p.start_activity(ProfileCategory::Linking, "link_crate"));
332 time(sess, "linking", || {
333 back::link::link_binary(sess, &codegen_results,
334 outputs, &codegen_results.crate_name.as_str());
336 sess.profiler(|p| p.end_activity(ProfileCategory::Linking, "link_crate"));
338 // Now that we won't touch anything in the incremental compilation directory
339 // any more, we can finalize it (which involves renaming it)
340 rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
346 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
348 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
349 LlvmCodegenBackend::new()
352 pub struct ModuleLlvm {
353 llcx: &'static mut llvm::Context,
354 llmod_raw: *const llvm::Module,
355 tm: &'static mut llvm::TargetMachine,
358 unsafe impl Send for ModuleLlvm { }
359 unsafe impl Sync for ModuleLlvm { }
362 fn new(tcx: TyCtxt<'_, '_, '_>, mod_name: &str) -> Self {
364 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
365 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
370 tm: create_target_machine(tcx, false),
376 cgcx: &CodegenContext<LlvmCodegenBackend>,
378 buffer: &back::lto::ModuleBuffer,
380 ) -> Result<Self, FatalError> {
382 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
383 let llmod_raw = buffer.parse(name, llcx, handler)?;
384 let tm = match (cgcx.tm_factory.0)() {
387 handler.struct_err(&e).emit();
388 return Err(FatalError)
400 fn llmod(&self) -> &llvm::Module {
407 impl Drop for ModuleLlvm {
410 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
411 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
416 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }