1#![cfg_attr(bootstrap, feature(slice_as_array))]
9#![feature(assert_matches)]
10#![feature(extern_types)]
11#![feature(file_buffered)]
12#![feature(if_let_guard)]
13#![feature(impl_trait_in_assoc_type)]
14#![feature(iter_intersperse)]
15#![feature(macro_derive)]
16#![feature(trim_prefix_suffix)]
17#![feature(try_blocks)]
18use 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); #[cfg(feature = "llvm_enzyme")]
245 {
246 use rustc_session::config::AutoDiff;
247
248 use crate::back::lto::enable_autodiff_settings;
249 if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
250 drop(llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot));
251 enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
252 }
253 }
254 }
255
256 fn provide(&self, providers: &mut Providers) {
257 providers.global_backend_features =
258 |tcx, ()| llvm_util::global_llvm_features(tcx.sess, false)
259 }
260
261 fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
262 use std::fmt::Write;
263 match req.kind {
264 PrintKind::RelocationModels => {
265 writeln!(out, "Available relocation models:").unwrap();
266 for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
267 writeln!(out, " {name}").unwrap();
268 }
269 writeln!(out).unwrap();
270 }
271 PrintKind::CodeModels => {
272 writeln!(out, "Available code models:").unwrap();
273 for name in &["tiny", "small", "kernel", "medium", "large"] {
274 writeln!(out, " {name}").unwrap();
275 }
276 writeln!(out).unwrap();
277 }
278 PrintKind::TlsModels => {
279 writeln!(out, "Available TLS models:").unwrap();
280 for name in TlsModel::ALL.iter().map(TlsModel::desc) {
281 writeln!(out, " {name}").unwrap();
282 }
283 writeln!(out).unwrap();
284 }
285 PrintKind::StackProtectorStrategies => {
286 writeln!(
287 out,
288 r#"Available stack protector strategies:
289 all
290 Generate stack canaries in all functions.
291
292 strong
293 Generate stack canaries in a function if it either:
294 - has a local variable of `[T; N]` type, regardless of `T` and `N`
295 - takes the address of a local variable.
296
297 (Note that a local variable being borrowed is not equivalent to its
298 address being taken: e.g. some borrows may be removed by optimization,
299 while by-value argument passing may be implemented with reference to a
300 local stack variable in the ABI.)
301
302 basic
303 Generate stack canaries in functions with local variables of `[T; N]`
304 type, where `T` is byte-sized and `N` >= 8.
305
306 none
307 Do not generate stack canaries.
308"#
309 )
310 .unwrap();
311 }
312 _other => llvm_util::print(req, out, sess),
313 }
314 }
315
316 fn print_passes(&self) {
317 llvm_util::print_passes();
318 }
319
320 fn print_version(&self) {
321 llvm_util::print_version();
322 }
323
324 fn has_zstd(&self) -> bool {
325 llvm::LLVMRustLLVMHasZstdCompression()
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 link_binary(
375 sess,
376 &LlvmArchiveBuilderBuilder,
377 codegen_results,
378 metadata,
379 outputs,
380 self.name(),
381 );
382 }
383}
384
385pub struct ModuleLlvm {
386 llcx: &'static mut llvm::Context,
387 llmod_raw: *const llvm::Module,
388
389 tm: ManuallyDrop<OwnedTargetMachine>,
392}
393
394unsafe impl Send for ModuleLlvm {}
395unsafe impl Sync for ModuleLlvm {}
396
397impl ModuleLlvm {
398 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
399 unsafe {
400 let llcx = llvm::LLVMContextCreate();
401 llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
402 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
403 ModuleLlvm {
404 llmod_raw,
405 llcx,
406 tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
407 }
408 }
409 }
410
411 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
412 unsafe {
413 let llcx = llvm::LLVMContextCreate();
414 llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
415 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
416 ModuleLlvm {
417 llmod_raw,
418 llcx,
419 tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
420 }
421 }
422 }
423
424 fn tm_from_cgcx(
425 cgcx: &CodegenContext<LlvmCodegenBackend>,
426 name: &str,
427 dcx: DiagCtxtHandle<'_>,
428 ) -> OwnedTargetMachine {
429 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name);
430 match (cgcx.tm_factory)(tm_factory_config) {
431 Ok(m) => m,
432 Err(e) => {
433 dcx.emit_fatal(ParseTargetMachineConfig(e));
434 }
435 }
436 }
437
438 fn parse(
439 cgcx: &CodegenContext<LlvmCodegenBackend>,
440 name: &CStr,
441 buffer: &[u8],
442 dcx: DiagCtxtHandle<'_>,
443 ) -> Self {
444 unsafe {
445 let llcx = llvm::LLVMContextCreate();
446 llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
447 let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
448 let tm = ModuleLlvm::tm_from_cgcx(cgcx, name.to_str().unwrap(), dcx);
449
450 ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
451 }
452 }
453
454 fn llmod(&self) -> &llvm::Module {
455 unsafe { &*self.llmod_raw }
456 }
457}
458
459impl Drop for ModuleLlvm {
460 fn drop(&mut self) {
461 unsafe {
462 ManuallyDrop::drop(&mut self.tm);
463 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
464 }
465 }
466}