5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(bool_to_option)]
9 #![feature(crate_visibility_modifier)]
10 #![feature(let_chains)]
12 #![feature(extern_types)]
13 #![feature(once_cell)]
15 #![feature(iter_intersperse)]
16 #![recursion_limit = "256"]
17 #![allow(rustc::potential_query_instability)]
20 extern crate rustc_macros;
22 use back::write::{create_informational_target_machine, create_target_machine};
24 pub use llvm_util::target_features;
25 use rustc_ast::expand::allocator::AllocatorKind;
26 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
27 use rustc_codegen_ssa::back::write::{
28 CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
30 use rustc_codegen_ssa::traits::*;
31 use rustc_codegen_ssa::ModuleCodegen;
32 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
33 use rustc_data_structures::fx::FxHashMap;
34 use rustc_errors::{ErrorGuaranteed, FatalError, Handler};
35 use rustc_metadata::EncodedMetadata;
36 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
37 use rustc_middle::ty::query::Providers;
38 use rustc_middle::ty::TyCtxt;
39 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
40 use rustc_session::Session;
41 use rustc_span::symbol::Symbol;
68 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
69 #[path = "llvm/mod.rs"]
72 pub use super::llvm_::*;
83 pub struct LlvmCodegenBackend(());
85 struct TimeTraceProfiler {
89 impl TimeTraceProfiler {
90 fn new(enabled: bool) -> Self {
92 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
94 TimeTraceProfiler { enabled }
98 impl Drop for TimeTraceProfiler {
101 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
106 impl ExtraBackendMethods for LlvmCodegenBackend {
107 fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
108 ModuleLlvm::new_metadata(tcx, mod_name)
111 fn codegen_allocator<'tcx>(
114 module_llvm: &mut ModuleLlvm,
117 has_alloc_error_handler: bool,
119 unsafe { allocator::codegen(tcx, module_llvm, module_name, kind, has_alloc_error_handler) }
121 fn compile_codegen_unit(
125 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
126 base::compile_codegen_unit(tcx, cgu_name)
128 fn target_machine_factory(
132 target_features: &[String],
133 ) -> TargetMachineFactoryFn<Self> {
134 back::write::target_machine_factory(sess, optlvl, target_features)
136 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
137 llvm_util::target_cpu(sess)
139 fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
140 llvm_util::tune_cpu(sess)
143 fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
149 std::thread::spawn(move || {
150 let _profiler = TimeTraceProfiler::new(time_trace);
155 fn spawn_named_thread<F, T>(
159 ) -> std::io::Result<std::thread::JoinHandle<T>>
165 std::thread::Builder::new().name(name).spawn(move || {
166 let _profiler = TimeTraceProfiler::new(time_trace);
172 impl WriteBackendMethods for LlvmCodegenBackend {
173 type Module = ModuleLlvm;
174 type ModuleBuffer = back::lto::ModuleBuffer;
175 type Context = llvm::Context;
176 type TargetMachine = &'static mut llvm::TargetMachine;
177 type ThinData = back::lto::ThinData;
178 type ThinBuffer = back::lto::ThinBuffer;
179 fn print_pass_timings(&self) {
181 llvm::LLVMRustPrintPassTimings();
185 cgcx: &CodegenContext<Self>,
186 diag_handler: &Handler,
187 modules: Vec<ModuleCodegen<Self::Module>>,
188 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
189 back::write::link(cgcx, diag_handler, modules)
192 cgcx: &CodegenContext<Self>,
193 modules: Vec<FatLTOInput<Self>>,
194 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
195 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
196 back::lto::run_fat(cgcx, modules, cached_modules)
199 cgcx: &CodegenContext<Self>,
200 modules: Vec<(String, Self::ThinBuffer)>,
201 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
202 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
203 back::lto::run_thin(cgcx, modules, cached_modules)
206 cgcx: &CodegenContext<Self>,
207 diag_handler: &Handler,
208 module: &ModuleCodegen<Self::Module>,
209 config: &ModuleConfig,
210 ) -> Result<(), FatalError> {
211 back::write::optimize(cgcx, diag_handler, module, config)
213 unsafe fn optimize_thin(
214 cgcx: &CodegenContext<Self>,
215 thin: &mut ThinModule<Self>,
216 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
217 back::lto::optimize_thin_module(thin, cgcx)
220 cgcx: &CodegenContext<Self>,
221 diag_handler: &Handler,
222 module: ModuleCodegen<Self::Module>,
223 config: &ModuleConfig,
224 ) -> Result<CompiledModule, FatalError> {
225 back::write::codegen(cgcx, diag_handler, module, config)
227 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
228 back::lto::prepare_thin(module)
230 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
231 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
233 fn run_lto_pass_manager(
234 cgcx: &CodegenContext<Self>,
235 module: &ModuleCodegen<Self::Module>,
236 config: &ModuleConfig,
238 ) -> Result<(), FatalError> {
239 let diag_handler = cgcx.create_diag_handler();
240 back::lto::run_pass_manager(cgcx, &diag_handler, module, config, thin)
244 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
245 unsafe impl Sync for LlvmCodegenBackend {}
247 impl LlvmCodegenBackend {
248 pub fn new() -> Box<dyn CodegenBackend> {
249 Box::new(LlvmCodegenBackend(()))
253 impl CodegenBackend for LlvmCodegenBackend {
254 fn init(&self, sess: &Session) {
255 llvm_util::init(sess); // Make sure llvm is inited
258 fn provide(&self, providers: &mut Providers) {
259 providers.global_backend_features =
260 |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
263 fn print(&self, req: PrintRequest, sess: &Session) {
265 PrintRequest::RelocationModels => {
266 println!("Available relocation models:");
277 println!(" {}", name);
281 PrintRequest::CodeModels => {
282 println!("Available code models:");
283 for name in &["tiny", "small", "kernel", "medium", "large"] {
284 println!(" {}", name);
288 PrintRequest::TlsModels => {
289 println!("Available TLS models:");
290 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
291 println!(" {}", name);
295 PrintRequest::StackProtectorStrategies => {
297 r#"Available stack protector strategies:
299 Generate stack canaries in all functions.
302 Generate stack canaries in a function if it either:
303 - has a local variable of `[T; N]` type, regardless of `T` and `N`
304 - takes the address of a local variable.
306 (Note that a local variable being borrowed is not equivalent to its
307 address being taken: e.g. some borrows may be removed by optimization,
308 while by-value argument passing may be implemented with reference to a
309 local stack variable in the ABI.)
312 Generate stack canaries in functions with:
313 - local variables of `[T; N]` type, where `T` is byte-sized and `N` > 8.
316 Do not generate stack canaries.
320 req => llvm_util::print(req, sess),
324 fn print_passes(&self) {
325 llvm_util::print_passes();
328 fn print_version(&self) {
329 llvm_util::print_version();
332 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
333 target_features(sess)
336 fn codegen_crate<'tcx>(
339 metadata: EncodedMetadata,
340 need_metadata_module: bool,
342 Box::new(rustc_codegen_ssa::base::codegen_crate(
343 LlvmCodegenBackend(()),
345 crate::llvm_util::target_cpu(tcx.sess).to_string(),
347 need_metadata_module,
353 ongoing_codegen: Box<dyn Any>,
355 outputs: &OutputFilenames,
356 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
357 let (codegen_results, work_products) = ongoing_codegen
358 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
359 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
362 sess.time("llvm_dump_timing_file", || {
363 if sess.opts.debugging_opts.llvm_time_trace {
364 let file_name = outputs.with_extension("llvm_timings.json");
365 llvm_util::time_trace_profiler_finish(&file_name);
369 Ok((codegen_results, work_products))
375 codegen_results: CodegenResults,
376 outputs: &OutputFilenames,
377 ) -> Result<(), ErrorGuaranteed> {
378 use crate::back::archive::LlvmArchiveBuilder;
379 use rustc_codegen_ssa::back::link::link_binary;
381 // Run the linker on any artifacts that resulted from the LLVM run.
382 // This should produce either a finished executable or library.
383 link_binary::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs)
387 pub struct ModuleLlvm {
388 llcx: &'static mut llvm::Context,
389 llmod_raw: *const llvm::Module,
390 tm: &'static mut llvm::TargetMachine,
393 unsafe impl Send for ModuleLlvm {}
394 unsafe impl Sync for ModuleLlvm {}
397 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
399 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
400 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
401 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
405 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
407 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
408 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
409 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
414 cgcx: &CodegenContext<LlvmCodegenBackend>,
418 ) -> Result<Self, FatalError> {
420 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
421 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
422 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
423 let tm = match (cgcx.tm_factory)(tm_factory_config) {
426 handler.struct_err(&e).emit();
427 return Err(FatalError);
431 Ok(ModuleLlvm { llmod_raw, llcx, tm })
435 fn llmod(&self) -> &llvm::Module {
436 unsafe { &*self.llmod_raw }
440 impl Drop for ModuleLlvm {
443 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
444 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));