5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
8 #![feature(bool_to_option)]
9 #![feature(const_cstr_unchecked)]
10 #![feature(crate_visibility_modifier)]
11 #![feature(extern_types)]
12 #![feature(in_band_lifetimes)]
14 #![feature(or_patterns)]
15 #![feature(trusted_len)]
16 #![recursion_limit = "256"]
18 use back::write::{create_informational_target_machine, create_target_machine};
20 pub use llvm_util::target_features;
21 use rustc_ast::expand::allocator::AllocatorKind;
22 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
23 use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, ModuleConfig};
24 use rustc_codegen_ssa::traits::*;
25 use rustc_codegen_ssa::ModuleCodegen;
26 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
27 use rustc_errors::{ErrorReported, FatalError, Handler};
28 use rustc_middle::dep_graph::{DepGraph, WorkProduct};
29 use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
30 use rustc_middle::ty::{self, TyCtxt};
31 use rustc_serialize::json;
32 use rustc_session::config::{self, OptLevel, OutputFilenames, PrintRequest};
33 use rustc_session::Session;
34 use rustc_span::symbol::Symbol;
63 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
64 #[path = "llvm/mod.rs"]
67 pub use super::llvm_::*;
79 pub struct LlvmCodegenBackend(());
81 impl ExtraBackendMethods for LlvmCodegenBackend {
82 fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
83 ModuleLlvm::new_metadata(tcx, mod_name)
86 fn write_compressed_metadata<'tcx>(
89 metadata: &EncodedMetadata,
90 llvm_module: &mut ModuleLlvm,
92 base::write_compressed_metadata(tcx, metadata, llvm_module)
94 fn codegen_allocator<'tcx>(
97 mods: &mut ModuleLlvm,
100 unsafe { allocator::codegen(tcx, mods, kind) }
102 fn compile_codegen_unit(
106 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
107 base::compile_codegen_unit(tcx, cgu_name)
109 fn target_machine_factory(
113 ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
114 back::write::target_machine_factory(sess, optlvl)
116 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
117 llvm_util::target_cpu(sess)
121 impl WriteBackendMethods for LlvmCodegenBackend {
122 type Module = ModuleLlvm;
123 type ModuleBuffer = back::lto::ModuleBuffer;
124 type Context = llvm::Context;
125 type TargetMachine = &'static mut llvm::TargetMachine;
126 type ThinData = back::lto::ThinData;
127 type ThinBuffer = back::lto::ThinBuffer;
128 fn print_pass_timings(&self) {
130 llvm::LLVMRustPrintPassTimings();
134 cgcx: &CodegenContext<Self>,
135 modules: Vec<FatLTOInput<Self>>,
136 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
137 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
138 back::lto::run_fat(cgcx, modules, cached_modules)
141 cgcx: &CodegenContext<Self>,
142 modules: Vec<(String, Self::ThinBuffer)>,
143 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
144 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
145 back::lto::run_thin(cgcx, modules, cached_modules)
148 cgcx: &CodegenContext<Self>,
149 diag_handler: &Handler,
150 module: &ModuleCodegen<Self::Module>,
151 config: &ModuleConfig,
152 ) -> Result<(), FatalError> {
153 back::write::optimize(cgcx, diag_handler, module, config)
155 unsafe fn optimize_thin(
156 cgcx: &CodegenContext<Self>,
157 thin: &mut ThinModule<Self>,
158 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
159 back::lto::optimize_thin_module(thin, cgcx)
162 cgcx: &CodegenContext<Self>,
163 diag_handler: &Handler,
164 module: ModuleCodegen<Self::Module>,
165 config: &ModuleConfig,
166 ) -> Result<CompiledModule, FatalError> {
167 back::write::codegen(cgcx, diag_handler, module, config)
169 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
170 back::lto::prepare_thin(module)
172 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
173 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
175 fn run_lto_pass_manager(
176 cgcx: &CodegenContext<Self>,
177 module: &ModuleCodegen<Self::Module>,
178 config: &ModuleConfig,
181 back::lto::run_pass_manager(cgcx, module, config, thin)
185 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
186 unsafe impl Sync for LlvmCodegenBackend {}
188 impl LlvmCodegenBackend {
189 pub fn new() -> Box<dyn CodegenBackend> {
190 Box::new(LlvmCodegenBackend(()))
194 impl CodegenBackend for LlvmCodegenBackend {
195 fn init(&self, sess: &Session) {
196 llvm_util::init(sess); // Make sure llvm is inited
199 fn print(&self, req: PrintRequest, sess: &Session) {
201 PrintRequest::RelocationModels => {
202 println!("Available relocation models:");
204 &["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
206 println!(" {}", name);
210 PrintRequest::CodeModels => {
211 println!("Available code models:");
212 for name in &["tiny", "small", "kernel", "medium", "large"] {
213 println!(" {}", name);
217 PrintRequest::TlsModels => {
218 println!("Available TLS models:");
219 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
220 println!(" {}", name);
224 req => llvm_util::print(req, sess),
228 fn print_passes(&self) {
229 llvm_util::print_passes();
232 fn print_version(&self) {
233 llvm_util::print_version();
236 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
237 target_features(sess)
240 fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
241 Box::new(metadata::LlvmMetadataLoader)
244 fn provide(&self, providers: &mut ty::query::Providers<'_>) {
245 attributes::provide(providers);
248 fn provide_extern(&self, providers: &mut ty::query::Providers<'_>) {
249 attributes::provide_extern(providers);
252 fn codegen_crate<'tcx>(
255 metadata: EncodedMetadata,
256 need_metadata_module: bool,
258 Box::new(rustc_codegen_ssa::base::codegen_crate(
259 LlvmCodegenBackend(()),
262 need_metadata_module,
268 ongoing_codegen: Box<dyn Any>,
270 dep_graph: &DepGraph,
271 ) -> Result<Box<dyn Any>, ErrorReported> {
272 let (codegen_results, work_products) = ongoing_codegen
273 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
274 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
276 if sess.opts.debugging_opts.incremental_info {
277 rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
280 sess.time("serialize_work_products", move || {
281 rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
284 sess.compile_status()?;
286 Ok(Box::new(codegen_results))
292 codegen_results: Box<dyn Any>,
293 outputs: &OutputFilenames,
294 ) -> Result<(), ErrorReported> {
295 let codegen_results = codegen_results
296 .downcast::<CodegenResults>()
297 .expect("Expected CodegenResults, found Box<Any>");
299 if sess.opts.debugging_opts.no_link {
300 // FIXME: use a binary format to encode the `.rlink` file
301 let rlink_data = json::encode(&codegen_results).map_err(|err| {
302 sess.fatal(&format!("failed to encode rlink: {}", err));
304 let rlink_file = outputs.with_extension(config::RLINK_EXT);
305 fs::write(&rlink_file, rlink_data).map_err(|err| {
306 sess.fatal(&format!("failed to write file {}: {}", rlink_file.display(), err));
311 // Run the linker on any artifacts that resulted from the LLVM run.
312 // This should produce either a finished executable or library.
313 sess.time("link_crate", || {
314 use crate::back::archive::LlvmArchiveBuilder;
315 use rustc_codegen_ssa::back::link::link_binary;
317 let target_cpu = crate::llvm_util::target_cpu(sess);
318 link_binary::<LlvmArchiveBuilder<'_>>(
322 &codegen_results.crate_name.as_str(),
327 // Now that we won't touch anything in the incremental compilation directory
328 // any more, we can finalize it (which involves renaming it)
329 rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
331 sess.time("llvm_dump_timing_file", || {
332 if sess.opts.debugging_opts.llvm_time_trace {
333 llvm_util::time_trace_profiler_finish("llvm_timings.json");
341 pub struct ModuleLlvm {
342 llcx: &'static mut llvm::Context,
343 llmod_raw: *const llvm::Module,
344 tm: &'static mut llvm::TargetMachine,
347 unsafe impl Send for ModuleLlvm {}
348 unsafe impl Sync for ModuleLlvm {}
351 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
353 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
354 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
355 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx) }
359 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
361 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
362 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
363 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
368 cgcx: &CodegenContext<LlvmCodegenBackend>,
372 ) -> Result<Self, FatalError> {
374 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
375 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
376 let tm = match (cgcx.tm_factory.0)() {
379 handler.struct_err(&e).emit();
380 return Err(FatalError);
384 Ok(ModuleLlvm { llmod_raw, llcx, tm })
388 fn llmod(&self) -> &llvm::Module {
389 unsafe { &*self.llmod_raw }
393 impl Drop for ModuleLlvm {
396 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
397 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));