rustc_codegen_llvm/
lib.rs

1//! The Rust compiler.
2//!
3//! # Note
4//!
5//! This API is completely unstable and subject to change.
6
7// tidy-alphabetical-start
8#![feature(assert_matches)]
9#![feature(extern_types)]
10#![feature(file_buffered)]
11#![feature(if_let_guard)]
12#![feature(impl_trait_in_assoc_type)]
13#![feature(iter_intersperse)]
14#![feature(macro_derive)]
15#![feature(once_cell_try)]
16#![feature(trim_prefix_suffix)]
17#![feature(try_blocks)]
18// tidy-alphabetical-end
19
20use std::any::Any;
21use std::ffi::CStr;
22use std::mem::ManuallyDrop;
23use std::path::PathBuf;
24
25use back::owned_target_machine::OwnedTargetMachine;
26use back::write::{create_informational_target_machine, create_target_machine};
27use context::SimpleCx;
28use errors::ParseTargetMachineConfig;
29use llvm_util::target_config;
30use rustc_ast::expand::allocator::AllocatorMethod;
31use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule};
32use rustc_codegen_ssa::back::write::{
33    CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
34};
35use rustc_codegen_ssa::traits::*;
36use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen, TargetConfig};
37use rustc_data_structures::fx::FxIndexMap;
38use rustc_errors::DiagCtxtHandle;
39use rustc_metadata::EncodedMetadata;
40use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
41use rustc_middle::ty::TyCtxt;
42use rustc_middle::util::Providers;
43use rustc_session::Session;
44use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
45use rustc_span::Symbol;
46use rustc_target::spec::{RelocModel, TlsModel};
47
48use crate::llvm::ToLlvmBool;
49
50mod abi;
51mod allocator;
52mod asm;
53mod attributes;
54mod back;
55mod base;
56mod builder;
57mod callee;
58mod common;
59mod consts;
60mod context;
61mod coverageinfo;
62mod debuginfo;
63mod declare;
64mod errors;
65mod intrinsic;
66mod llvm;
67mod llvm_util;
68mod macros;
69mod mono_item;
70mod type_;
71mod type_of;
72mod typetree;
73mod va_arg;
74mod value;
75
76rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
77
78pub(crate) use macros::TryFromU32;
79
80#[derive(Clone)]
81pub struct LlvmCodegenBackend(());
82
83struct TimeTraceProfiler {
84    enabled: bool,
85}
86
87impl TimeTraceProfiler {
88    fn new(enabled: bool) -> Self {
89        if enabled {
90            unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
91        }
92        TimeTraceProfiler { enabled }
93    }
94}
95
96impl Drop for TimeTraceProfiler {
97    fn drop(&mut self) {
98        if self.enabled {
99            unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
100        }
101    }
102}
103
104impl ExtraBackendMethods for LlvmCodegenBackend {
105    fn codegen_allocator<'tcx>(
106        &self,
107        tcx: TyCtxt<'tcx>,
108        module_name: &str,
109        methods: &[AllocatorMethod],
110    ) -> ModuleLlvm {
111        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
112        let cx =
113            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
114        unsafe {
115            allocator::codegen(tcx, cx, module_name, methods);
116        }
117        module_llvm
118    }
119    fn compile_codegen_unit(
120        &self,
121        tcx: TyCtxt<'_>,
122        cgu_name: Symbol,
123    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
124        base::compile_codegen_unit(tcx, cgu_name)
125    }
126    fn target_machine_factory(
127        &self,
128        sess: &Session,
129        optlvl: OptLevel,
130        target_features: &[String],
131    ) -> TargetMachineFactoryFn<Self> {
132        back::write::target_machine_factory(sess, optlvl, target_features)
133    }
134
135    fn spawn_named_thread<F, T>(
136        time_trace: bool,
137        name: String,
138        f: F,
139    ) -> std::io::Result<std::thread::JoinHandle<T>>
140    where
141        F: FnOnce() -> T,
142        F: Send + 'static,
143        T: Send + 'static,
144    {
145        std::thread::Builder::new().name(name).spawn(move || {
146            let _profiler = TimeTraceProfiler::new(time_trace);
147            f()
148        })
149    }
150}
151
152impl WriteBackendMethods for LlvmCodegenBackend {
153    type Module = ModuleLlvm;
154    type ModuleBuffer = back::lto::ModuleBuffer;
155    type TargetMachine = OwnedTargetMachine;
156    type TargetMachineError = crate::errors::LlvmError<'static>;
157    type ThinData = back::lto::ThinData;
158    type ThinBuffer = back::lto::ThinBuffer;
159    fn print_pass_timings(&self) {
160        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
161        print!("{timings}");
162    }
163    fn print_statistics(&self) {
164        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
165        print!("{stats}");
166    }
167    fn run_and_optimize_fat_lto(
168        cgcx: &CodegenContext<Self>,
169        exported_symbols_for_lto: &[String],
170        each_linked_rlib_for_lto: &[PathBuf],
171        modules: Vec<FatLtoInput<Self>>,
172    ) -> ModuleCodegen<Self::Module> {
173        let mut module =
174            back::lto::run_fat(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, modules);
175
176        let dcx = cgcx.create_dcx();
177        let dcx = dcx.handle();
178        back::lto::run_pass_manager(cgcx, dcx, &mut module, false);
179
180        module
181    }
182    fn run_thin_lto(
183        cgcx: &CodegenContext<Self>,
184        exported_symbols_for_lto: &[String],
185        each_linked_rlib_for_lto: &[PathBuf],
186        modules: Vec<(String, Self::ThinBuffer)>,
187        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
188    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
189        back::lto::run_thin(
190            cgcx,
191            exported_symbols_for_lto,
192            each_linked_rlib_for_lto,
193            modules,
194            cached_modules,
195        )
196    }
197    fn optimize(
198        cgcx: &CodegenContext<Self>,
199        dcx: DiagCtxtHandle<'_>,
200        module: &mut ModuleCodegen<Self::Module>,
201        config: &ModuleConfig,
202    ) {
203        back::write::optimize(cgcx, dcx, module, config)
204    }
205    fn optimize_thin(
206        cgcx: &CodegenContext<Self>,
207        thin: ThinModule<Self>,
208    ) -> ModuleCodegen<Self::Module> {
209        back::lto::optimize_thin_module(thin, cgcx)
210    }
211    fn codegen(
212        cgcx: &CodegenContext<Self>,
213        module: ModuleCodegen<Self::Module>,
214        config: &ModuleConfig,
215    ) -> CompiledModule {
216        back::write::codegen(cgcx, module, config)
217    }
218    fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
219        back::lto::prepare_thin(module)
220    }
221    fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
222        (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
223    }
224}
225
226impl LlvmCodegenBackend {
227    pub fn new() -> Box<dyn CodegenBackend> {
228        Box::new(LlvmCodegenBackend(()))
229    }
230}
231
232impl CodegenBackend for LlvmCodegenBackend {
233    fn locale_resource(&self) -> &'static str {
234        crate::DEFAULT_LOCALE_RESOURCE
235    }
236
237    fn name(&self) -> &'static str {
238        "llvm"
239    }
240
241    fn init(&self, sess: &Session) {
242        llvm_util::init(sess); // Make sure llvm is inited
243
244        // autodiff is based on Enzyme, a library which we might not have available, when it was
245        // neither build, nor downloaded via rustup. If autodiff is used, but not available we emit
246        // an early error here and abort compilation.
247        {
248            use rustc_session::config::AutoDiff;
249
250            use crate::back::lto::enable_autodiff_settings;
251            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
252                if let Err(_) = llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
253                    sess.dcx().emit_fatal(crate::errors::AutoDiffComponentUnavailable);
254                }
255                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
256            }
257        }
258    }
259
260    fn provide(&self, providers: &mut Providers) {
261        providers.global_backend_features =
262            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, false)
263    }
264
265    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
266        use std::fmt::Write;
267        match req.kind {
268            PrintKind::RelocationModels => {
269                writeln!(out, "Available relocation models:").unwrap();
270                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
271                    writeln!(out, "    {name}").unwrap();
272                }
273                writeln!(out).unwrap();
274            }
275            PrintKind::CodeModels => {
276                writeln!(out, "Available code models:").unwrap();
277                for name in &["tiny", "small", "kernel", "medium", "large"] {
278                    writeln!(out, "    {name}").unwrap();
279                }
280                writeln!(out).unwrap();
281            }
282            PrintKind::TlsModels => {
283                writeln!(out, "Available TLS models:").unwrap();
284                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
285                    writeln!(out, "    {name}").unwrap();
286                }
287                writeln!(out).unwrap();
288            }
289            PrintKind::StackProtectorStrategies => {
290                writeln!(
291                    out,
292                    r#"Available stack protector strategies:
293    all
294        Generate stack canaries in all functions.
295
296    strong
297        Generate stack canaries in a function if it either:
298        - has a local variable of `[T; N]` type, regardless of `T` and `N`
299        - takes the address of a local variable.
300
301          (Note that a local variable being borrowed is not equivalent to its
302          address being taken: e.g. some borrows may be removed by optimization,
303          while by-value argument passing may be implemented with reference to a
304          local stack variable in the ABI.)
305
306    basic
307        Generate stack canaries in functions with local variables of `[T; N]`
308        type, where `T` is byte-sized and `N` >= 8.
309
310    none
311        Do not generate stack canaries.
312"#
313                )
314                .unwrap();
315            }
316            _other => llvm_util::print(req, out, sess),
317        }
318    }
319
320    fn print_passes(&self) {
321        llvm_util::print_passes();
322    }
323
324    fn print_version(&self) {
325        llvm_util::print_version();
326    }
327
328    fn has_zstd(&self) -> bool {
329        llvm::LLVMRustLLVMHasZstdCompression()
330    }
331
332    fn target_config(&self, sess: &Session) -> TargetConfig {
333        target_config(sess)
334    }
335
336    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
337        Box::new(rustc_codegen_ssa::base::codegen_crate(
338            LlvmCodegenBackend(()),
339            tcx,
340            crate::llvm_util::target_cpu(tcx.sess).to_string(),
341        ))
342    }
343
344    fn join_codegen(
345        &self,
346        ongoing_codegen: Box<dyn Any>,
347        sess: &Session,
348        outputs: &OutputFilenames,
349    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
350        let (codegen_results, work_products) = ongoing_codegen
351            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
352            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
353            .join(sess);
354
355        if sess.opts.unstable_opts.llvm_time_trace {
356            sess.time("llvm_dump_timing_file", || {
357                let file_name = outputs.with_extension("llvm_timings.json");
358                llvm_util::time_trace_profiler_finish(&file_name);
359            });
360        }
361
362        (codegen_results, work_products)
363    }
364
365    fn link(
366        &self,
367        sess: &Session,
368        codegen_results: CodegenResults,
369        metadata: EncodedMetadata,
370        outputs: &OutputFilenames,
371    ) {
372        use rustc_codegen_ssa::back::link::link_binary;
373
374        use crate::back::archive::LlvmArchiveBuilderBuilder;
375
376        // Run the linker on any artifacts that resulted from the LLVM run.
377        // This should produce either a finished executable or library.
378        link_binary(
379            sess,
380            &LlvmArchiveBuilderBuilder,
381            codegen_results,
382            metadata,
383            outputs,
384            self.name(),
385        );
386    }
387}
388
389pub struct ModuleLlvm {
390    llcx: &'static mut llvm::Context,
391    llmod_raw: *const llvm::Module,
392
393    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
394    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
395    tm: ManuallyDrop<OwnedTargetMachine>,
396}
397
398unsafe impl Send for ModuleLlvm {}
399unsafe impl Sync for ModuleLlvm {}
400
401impl ModuleLlvm {
402    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
403        unsafe {
404            let llcx = llvm::LLVMContextCreate();
405            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
406            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
407            ModuleLlvm {
408                llmod_raw,
409                llcx,
410                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
411            }
412        }
413    }
414
415    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
416        unsafe {
417            let llcx = llvm::LLVMContextCreate();
418            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
419            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
420            ModuleLlvm {
421                llmod_raw,
422                llcx,
423                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
424            }
425        }
426    }
427
428    fn tm_from_cgcx(
429        cgcx: &CodegenContext<LlvmCodegenBackend>,
430        name: &str,
431        dcx: DiagCtxtHandle<'_>,
432    ) -> OwnedTargetMachine {
433        let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name);
434        match (cgcx.tm_factory)(tm_factory_config) {
435            Ok(m) => m,
436            Err(e) => {
437                dcx.emit_fatal(ParseTargetMachineConfig(e));
438            }
439        }
440    }
441
442    fn parse(
443        cgcx: &CodegenContext<LlvmCodegenBackend>,
444        name: &CStr,
445        buffer: &[u8],
446        dcx: DiagCtxtHandle<'_>,
447    ) -> Self {
448        unsafe {
449            let llcx = llvm::LLVMContextCreate();
450            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
451            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
452            let tm = ModuleLlvm::tm_from_cgcx(cgcx, name.to_str().unwrap(), dcx);
453
454            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
455        }
456    }
457
458    fn llmod(&self) -> &llvm::Module {
459        unsafe { &*self.llmod_raw }
460    }
461}
462
463impl Drop for ModuleLlvm {
464    fn drop(&mut self) {
465        unsafe {
466            ManuallyDrop::drop(&mut self.tm);
467            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
468        }
469    }
470}