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#![allow(internal_features)]
9#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10#![doc(rust_logo)]
11#![feature(assert_matches)]
12#![feature(extern_types)]
13#![feature(file_buffered)]
14#![feature(if_let_guard)]
15#![feature(impl_trait_in_assoc_type)]
16#![feature(iter_intersperse)]
17#![feature(rustdoc_internals)]
18#![feature(slice_as_array)]
19#![feature(try_blocks)]
20// tidy-alphabetical-end
21
22use std::any::Any;
23use std::ffi::CStr;
24use std::mem::ManuallyDrop;
25
26use back::owned_target_machine::OwnedTargetMachine;
27use back::write::{create_informational_target_machine, create_target_machine};
28use context::SimpleCx;
29use errors::ParseTargetMachineConfig;
30use llvm_util::target_config;
31use rustc_ast::expand::allocator::AllocatorKind;
32use rustc_ast::expand::autodiff_attrs::AutoDiffItem;
33use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule};
34use rustc_codegen_ssa::back::write::{
35    CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
36};
37use rustc_codegen_ssa::traits::*;
38use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen, TargetConfig};
39use rustc_data_structures::fx::FxIndexMap;
40use rustc_errors::{DiagCtxtHandle, FatalError};
41use rustc_metadata::EncodedMetadata;
42use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
43use rustc_middle::ty::TyCtxt;
44use rustc_middle::util::Providers;
45use rustc_session::Session;
46use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
47use rustc_span::Symbol;
48
49mod back {
50    pub(crate) mod archive;
51    pub(crate) mod lto;
52    pub(crate) mod owned_target_machine;
53    mod profiling;
54    pub(crate) mod write;
55}
56
57mod abi;
58mod allocator;
59mod asm;
60mod attributes;
61mod base;
62mod builder;
63mod callee;
64mod common;
65mod consts;
66mod context;
67mod coverageinfo;
68mod debuginfo;
69mod declare;
70mod errors;
71mod intrinsic;
72mod llvm;
73mod llvm_util;
74mod mono_item;
75mod type_;
76mod type_of;
77mod va_arg;
78mod value;
79
80rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
81
82#[derive(Clone)]
83pub struct LlvmCodegenBackend(());
84
85struct TimeTraceProfiler {
86    enabled: bool,
87}
88
89impl TimeTraceProfiler {
90    fn new(enabled: bool) -> Self {
91        if enabled {
92            unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
93        }
94        TimeTraceProfiler { enabled }
95    }
96}
97
98impl Drop for TimeTraceProfiler {
99    fn drop(&mut self) {
100        if self.enabled {
101            unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
102        }
103    }
104}
105
106impl ExtraBackendMethods for LlvmCodegenBackend {
107    fn codegen_allocator<'tcx>(
108        &self,
109        tcx: TyCtxt<'tcx>,
110        module_name: &str,
111        kind: AllocatorKind,
112        alloc_error_handler_kind: AllocatorKind,
113    ) -> ModuleLlvm {
114        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
115        let cx =
116            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
117        unsafe {
118            allocator::codegen(tcx, cx, module_name, kind, alloc_error_handler_kind);
119        }
120        module_llvm
121    }
122    fn compile_codegen_unit(
123        &self,
124        tcx: TyCtxt<'_>,
125        cgu_name: Symbol,
126    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
127        base::compile_codegen_unit(tcx, cgu_name)
128    }
129    fn target_machine_factory(
130        &self,
131        sess: &Session,
132        optlvl: OptLevel,
133        target_features: &[String],
134    ) -> TargetMachineFactoryFn<Self> {
135        back::write::target_machine_factory(sess, optlvl, target_features)
136    }
137
138    fn spawn_named_thread<F, T>(
139        time_trace: bool,
140        name: String,
141        f: F,
142    ) -> std::io::Result<std::thread::JoinHandle<T>>
143    where
144        F: FnOnce() -> T,
145        F: Send + 'static,
146        T: Send + 'static,
147    {
148        std::thread::Builder::new().name(name).spawn(move || {
149            let _profiler = TimeTraceProfiler::new(time_trace);
150            f()
151        })
152    }
153}
154
155impl WriteBackendMethods for LlvmCodegenBackend {
156    type Module = ModuleLlvm;
157    type ModuleBuffer = back::lto::ModuleBuffer;
158    type TargetMachine = OwnedTargetMachine;
159    type TargetMachineError = crate::errors::LlvmError<'static>;
160    type ThinData = back::lto::ThinData;
161    type ThinBuffer = back::lto::ThinBuffer;
162    fn print_pass_timings(&self) {
163        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
164        print!("{timings}");
165    }
166    fn print_statistics(&self) {
167        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
168        print!("{stats}");
169    }
170    fn run_link(
171        cgcx: &CodegenContext<Self>,
172        dcx: DiagCtxtHandle<'_>,
173        modules: Vec<ModuleCodegen<Self::Module>>,
174    ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
175        back::write::link(cgcx, dcx, modules)
176    }
177    fn run_and_optimize_fat_lto(
178        cgcx: &CodegenContext<Self>,
179        modules: Vec<FatLtoInput<Self>>,
180        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
181        diff_fncs: Vec<AutoDiffItem>,
182    ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
183        let mut module = back::lto::run_fat(cgcx, modules, cached_modules)?;
184
185        if !diff_fncs.is_empty() {
186            builder::autodiff::differentiate(&module, cgcx, diff_fncs)?;
187        }
188
189        let dcx = cgcx.create_dcx();
190        let dcx = dcx.handle();
191        back::lto::run_pass_manager(cgcx, dcx, &mut module, false)?;
192
193        Ok(module)
194    }
195    fn run_thin_lto(
196        cgcx: &CodegenContext<Self>,
197        modules: Vec<(String, Self::ThinBuffer)>,
198        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
199    ) -> Result<(Vec<ThinModule<Self>>, Vec<WorkProduct>), FatalError> {
200        back::lto::run_thin(cgcx, modules, cached_modules)
201    }
202    fn optimize(
203        cgcx: &CodegenContext<Self>,
204        dcx: DiagCtxtHandle<'_>,
205        module: &mut ModuleCodegen<Self::Module>,
206        config: &ModuleConfig,
207    ) -> Result<(), FatalError> {
208        back::write::optimize(cgcx, dcx, module, config)
209    }
210    fn optimize_thin(
211        cgcx: &CodegenContext<Self>,
212        thin: ThinModule<Self>,
213    ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
214        back::lto::optimize_thin_module(thin, cgcx)
215    }
216    fn codegen(
217        cgcx: &CodegenContext<Self>,
218        module: ModuleCodegen<Self::Module>,
219        config: &ModuleConfig,
220    ) -> Result<CompiledModule, FatalError> {
221        back::write::codegen(cgcx, module, config)
222    }
223    fn prepare_thin(
224        module: ModuleCodegen<Self::Module>,
225        emit_summary: bool,
226    ) -> (String, Self::ThinBuffer) {
227        back::lto::prepare_thin(module, emit_summary)
228    }
229    fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
230        (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
231    }
232}
233
234impl LlvmCodegenBackend {
235    pub fn new() -> Box<dyn CodegenBackend> {
236        Box::new(LlvmCodegenBackend(()))
237    }
238}
239
240impl CodegenBackend for LlvmCodegenBackend {
241    fn locale_resource(&self) -> &'static str {
242        crate::DEFAULT_LOCALE_RESOURCE
243    }
244
245    fn init(&self, sess: &Session) {
246        llvm_util::init(sess); // Make sure llvm is inited
247    }
248
249    fn provide(&self, providers: &mut Providers) {
250        providers.global_backend_features =
251            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true, false)
252    }
253
254    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
255        use std::fmt::Write;
256        match req.kind {
257            PrintKind::RelocationModels => {
258                writeln!(out, "Available relocation models:").unwrap();
259                for name in &[
260                    "static",
261                    "pic",
262                    "pie",
263                    "dynamic-no-pic",
264                    "ropi",
265                    "rwpi",
266                    "ropi-rwpi",
267                    "default",
268                ] {
269                    writeln!(out, "    {name}").unwrap();
270                }
271                writeln!(out).unwrap();
272            }
273            PrintKind::CodeModels => {
274                writeln!(out, "Available code models:").unwrap();
275                for name in &["tiny", "small", "kernel", "medium", "large"] {
276                    writeln!(out, "    {name}").unwrap();
277                }
278                writeln!(out).unwrap();
279            }
280            PrintKind::TlsModels => {
281                writeln!(out, "Available TLS models:").unwrap();
282                for name in
283                    &["global-dynamic", "local-dynamic", "initial-exec", "local-exec", "emulated"]
284                {
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 target_config(&self, sess: &Session) -> TargetConfig {
329        target_config(sess)
330    }
331
332    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
333        Box::new(rustc_codegen_ssa::base::codegen_crate(
334            LlvmCodegenBackend(()),
335            tcx,
336            crate::llvm_util::target_cpu(tcx.sess).to_string(),
337        ))
338    }
339
340    fn join_codegen(
341        &self,
342        ongoing_codegen: Box<dyn Any>,
343        sess: &Session,
344        outputs: &OutputFilenames,
345    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
346        let (codegen_results, work_products) = ongoing_codegen
347            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
348            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
349            .join(sess);
350
351        if sess.opts.unstable_opts.llvm_time_trace {
352            sess.time("llvm_dump_timing_file", || {
353                let file_name = outputs.with_extension("llvm_timings.json");
354                llvm_util::time_trace_profiler_finish(&file_name);
355            });
356        }
357
358        (codegen_results, work_products)
359    }
360
361    fn link(
362        &self,
363        sess: &Session,
364        codegen_results: CodegenResults,
365        metadata: EncodedMetadata,
366        outputs: &OutputFilenames,
367    ) {
368        use rustc_codegen_ssa::back::link::link_binary;
369
370        use crate::back::archive::LlvmArchiveBuilderBuilder;
371
372        // Run the linker on any artifacts that resulted from the LLVM run.
373        // This should produce either a finished executable or library.
374        link_binary(sess, &LlvmArchiveBuilderBuilder, codegen_results, metadata, outputs);
375    }
376}
377
378pub struct ModuleLlvm {
379    llcx: &'static mut llvm::Context,
380    llmod_raw: *const llvm::Module,
381
382    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
383    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
384    tm: ManuallyDrop<OwnedTargetMachine>,
385}
386
387unsafe impl Send for ModuleLlvm {}
388unsafe impl Sync for ModuleLlvm {}
389
390impl ModuleLlvm {
391    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
392        unsafe {
393            let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
394            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
395            ModuleLlvm {
396                llmod_raw,
397                llcx,
398                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
399            }
400        }
401    }
402
403    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
404        unsafe {
405            let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
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_informational_target_machine(tcx.sess, false)),
411            }
412        }
413    }
414
415    fn parse(
416        cgcx: &CodegenContext<LlvmCodegenBackend>,
417        name: &CStr,
418        buffer: &[u8],
419        dcx: DiagCtxtHandle<'_>,
420    ) -> Result<Self, FatalError> {
421        unsafe {
422            let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
423            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx)?;
424            let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
425            let tm = match (cgcx.tm_factory)(tm_factory_config) {
426                Ok(m) => m,
427                Err(e) => {
428                    return Err(dcx.emit_almost_fatal(ParseTargetMachineConfig(e)));
429                }
430            };
431
432            Ok(ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) })
433        }
434    }
435
436    fn llmod(&self) -> &llvm::Module {
437        unsafe { &*self.llmod_raw }
438    }
439}
440
441impl Drop for ModuleLlvm {
442    fn drop(&mut self) {
443        unsafe {
444            ManuallyDrop::drop(&mut self.tm);
445            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
446        }
447    }
448}