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;
62 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
63 #[path = "llvm/mod.rs"]
66 pub use super::llvm_::*;
78 pub struct LlvmCodegenBackend(());
80 impl ExtraBackendMethods for LlvmCodegenBackend {
81 fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
82 ModuleLlvm::new_metadata(tcx, mod_name)
85 fn write_compressed_metadata<'tcx>(
88 metadata: &EncodedMetadata,
89 llvm_module: &mut ModuleLlvm,
91 base::write_compressed_metadata(tcx, metadata, llvm_module)
93 fn codegen_allocator<'tcx>(
96 mods: &mut ModuleLlvm,
99 unsafe { allocator::codegen(tcx, mods, kind) }
101 fn compile_codegen_unit(
105 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
106 base::compile_codegen_unit(tcx, cgu_name)
108 fn target_machine_factory(
112 ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
113 back::write::target_machine_factory(sess, optlvl)
115 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
116 llvm_util::target_cpu(sess)
120 impl WriteBackendMethods for LlvmCodegenBackend {
121 type Module = ModuleLlvm;
122 type ModuleBuffer = back::lto::ModuleBuffer;
123 type Context = llvm::Context;
124 type TargetMachine = &'static mut llvm::TargetMachine;
125 type ThinData = back::lto::ThinData;
126 type ThinBuffer = back::lto::ThinBuffer;
127 fn print_pass_timings(&self) {
129 llvm::LLVMRustPrintPassTimings();
133 cgcx: &CodegenContext<Self>,
134 modules: Vec<FatLTOInput<Self>>,
135 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
136 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
137 back::lto::run_fat(cgcx, modules, cached_modules)
140 cgcx: &CodegenContext<Self>,
141 modules: Vec<(String, Self::ThinBuffer)>,
142 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
143 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
144 back::lto::run_thin(cgcx, modules, cached_modules)
147 cgcx: &CodegenContext<Self>,
148 diag_handler: &Handler,
149 module: &ModuleCodegen<Self::Module>,
150 config: &ModuleConfig,
151 ) -> Result<(), FatalError> {
152 back::write::optimize(cgcx, diag_handler, module, config)
154 unsafe fn optimize_thin(
155 cgcx: &CodegenContext<Self>,
156 thin: &mut ThinModule<Self>,
157 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
158 back::lto::optimize_thin_module(thin, cgcx)
161 cgcx: &CodegenContext<Self>,
162 diag_handler: &Handler,
163 module: ModuleCodegen<Self::Module>,
164 config: &ModuleConfig,
165 ) -> Result<CompiledModule, FatalError> {
166 back::write::codegen(cgcx, diag_handler, module, config)
168 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
169 back::lto::prepare_thin(module)
171 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
172 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
174 fn run_lto_pass_manager(
175 cgcx: &CodegenContext<Self>,
176 module: &ModuleCodegen<Self::Module>,
177 config: &ModuleConfig,
180 back::lto::run_pass_manager(cgcx, module, config, thin)
184 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
185 unsafe impl Sync for LlvmCodegenBackend {}
187 impl LlvmCodegenBackend {
188 pub fn new() -> Box<dyn CodegenBackend> {
189 Box::new(LlvmCodegenBackend(()))
193 impl CodegenBackend for LlvmCodegenBackend {
194 fn init(&self, sess: &Session) {
195 llvm_util::init(sess); // Make sure llvm is inited
198 fn print(&self, req: PrintRequest, sess: &Session) {
200 PrintRequest::RelocationModels => {
201 println!("Available relocation models:");
203 &["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
205 println!(" {}", name);
209 PrintRequest::CodeModels => {
210 println!("Available code models:");
211 for name in &["tiny", "small", "kernel", "medium", "large"] {
212 println!(" {}", name);
216 PrintRequest::TlsModels => {
217 println!("Available TLS models:");
218 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
219 println!(" {}", name);
223 req => llvm_util::print(req, sess),
227 fn print_passes(&self) {
228 llvm_util::print_passes();
231 fn print_version(&self) {
232 llvm_util::print_version();
235 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
236 target_features(sess)
239 fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
240 Box::new(metadata::LlvmMetadataLoader)
243 fn provide(&self, providers: &mut ty::query::Providers<'_>) {
244 attributes::provide(providers);
247 fn provide_extern(&self, providers: &mut ty::query::Providers<'_>) {
248 attributes::provide_extern(providers);
251 fn codegen_crate<'tcx>(
254 metadata: EncodedMetadata,
255 need_metadata_module: bool,
257 Box::new(rustc_codegen_ssa::base::codegen_crate(
258 LlvmCodegenBackend(()),
261 need_metadata_module,
267 ongoing_codegen: Box<dyn Any>,
269 dep_graph: &DepGraph,
270 ) -> Result<Box<dyn Any>, ErrorReported> {
271 let (codegen_results, work_products) = ongoing_codegen
272 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
273 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
275 if sess.opts.debugging_opts.incremental_info {
276 rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
279 sess.time("serialize_work_products", move || {
280 rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
283 sess.compile_status()?;
285 Ok(Box::new(codegen_results))
291 codegen_results: Box<dyn Any>,
292 outputs: &OutputFilenames,
293 ) -> Result<(), ErrorReported> {
294 let codegen_results = codegen_results
295 .downcast::<CodegenResults>()
296 .expect("Expected CodegenResults, found Box<Any>");
298 if sess.opts.debugging_opts.no_link {
299 // FIXME: use a binary format to encode the `.rlink` file
300 let rlink_data = json::encode(&codegen_results).map_err(|err| {
301 sess.fatal(&format!("failed to encode rlink: {}", err));
303 let rlink_file = outputs.with_extension(config::RLINK_EXT);
304 fs::write(&rlink_file, rlink_data).map_err(|err| {
305 sess.fatal(&format!("failed to write file {}: {}", rlink_file.display(), err));
310 // Run the linker on any artifacts that resulted from the LLVM run.
311 // This should produce either a finished executable or library.
312 sess.time("link_crate", || {
313 use crate::back::archive::LlvmArchiveBuilder;
314 use rustc_codegen_ssa::back::link::link_binary;
316 let target_cpu = crate::llvm_util::target_cpu(sess);
317 link_binary::<LlvmArchiveBuilder<'_>>(
321 &codegen_results.crate_name.as_str(),
326 // Now that we won't touch anything in the incremental compilation directory
327 // any more, we can finalize it (which involves renaming it)
328 rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
330 sess.time("llvm_dump_timing_file", || {
331 if sess.opts.debugging_opts.llvm_time_trace {
332 llvm_util::time_trace_profiler_finish("llvm_timings.json");
340 pub struct ModuleLlvm {
341 llcx: &'static mut llvm::Context,
342 llmod_raw: *const llvm::Module,
343 tm: &'static mut llvm::TargetMachine,
346 unsafe impl Send for ModuleLlvm {}
347 unsafe impl Sync for ModuleLlvm {}
350 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
352 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
353 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
354 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx) }
358 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
360 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
361 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
362 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
367 cgcx: &CodegenContext<LlvmCodegenBackend>,
371 ) -> Result<Self, FatalError> {
373 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
374 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
375 let tm = match (cgcx.tm_factory.0)() {
378 handler.struct_err(&e).emit();
379 return Err(FatalError);
383 Ok(ModuleLlvm { llmod_raw, llcx, tm })
387 fn llmod(&self) -> &llvm::Module {
388 unsafe { &*self.llmod_raw }
392 impl Drop for ModuleLlvm {
395 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
396 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));