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(let_chains)]
10 #![feature(extern_types)]
11 #![feature(once_cell)]
12 #![feature(iter_intersperse)]
13 #![recursion_limit = "256"]
14 #![allow(rustc::potential_query_instability)]
17 extern crate rustc_macros;
19 use back::write::{create_informational_target_machine, create_target_machine};
21 pub use llvm_util::target_features;
22 use rustc_ast::expand::allocator::AllocatorKind;
23 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
24 use rustc_codegen_ssa::back::write::{
25 CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
27 use rustc_codegen_ssa::traits::*;
28 use rustc_codegen_ssa::ModuleCodegen;
29 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
30 use rustc_data_structures::fx::FxHashMap;
31 use rustc_errors::{ErrorGuaranteed, FatalError, Handler};
32 use rustc_metadata::EncodedMetadata;
33 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
34 use rustc_middle::ty::query::Providers;
35 use rustc_middle::ty::TyCtxt;
36 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
37 use rustc_session::Session;
38 use rustc_span::symbol::Symbol;
65 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
66 #[path = "llvm/mod.rs"]
69 pub use super::llvm_::*;
80 pub struct LlvmCodegenBackend(());
82 struct TimeTraceProfiler {
86 impl TimeTraceProfiler {
87 fn new(enabled: bool) -> Self {
89 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
91 TimeTraceProfiler { enabled }
95 impl Drop for TimeTraceProfiler {
98 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
103 impl ExtraBackendMethods for LlvmCodegenBackend {
104 fn codegen_allocator<'tcx>(
109 has_alloc_error_handler: bool,
111 let mut module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
113 allocator::codegen(tcx, &mut module_llvm, module_name, kind, has_alloc_error_handler);
117 fn compile_codegen_unit(
121 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
122 base::compile_codegen_unit(tcx, cgu_name)
124 fn target_machine_factory(
128 target_features: &[String],
129 ) -> TargetMachineFactoryFn<Self> {
130 back::write::target_machine_factory(sess, optlvl, target_features)
132 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
133 llvm_util::target_cpu(sess)
135 fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
136 llvm_util::tune_cpu(sess)
139 fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
145 std::thread::spawn(move || {
146 let _profiler = TimeTraceProfiler::new(time_trace);
151 fn spawn_named_thread<F, T>(
155 ) -> std::io::Result<std::thread::JoinHandle<T>>
161 std::thread::Builder::new().name(name).spawn(move || {
162 let _profiler = TimeTraceProfiler::new(time_trace);
168 impl WriteBackendMethods for LlvmCodegenBackend {
169 type Module = ModuleLlvm;
170 type ModuleBuffer = back::lto::ModuleBuffer;
171 type Context = llvm::Context;
172 type TargetMachine = &'static mut llvm::TargetMachine;
173 type ThinData = back::lto::ThinData;
174 type ThinBuffer = back::lto::ThinBuffer;
175 fn print_pass_timings(&self) {
177 llvm::LLVMRustPrintPassTimings();
181 cgcx: &CodegenContext<Self>,
182 diag_handler: &Handler,
183 modules: Vec<ModuleCodegen<Self::Module>>,
184 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
185 back::write::link(cgcx, diag_handler, modules)
188 cgcx: &CodegenContext<Self>,
189 modules: Vec<FatLTOInput<Self>>,
190 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
191 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
192 back::lto::run_fat(cgcx, modules, cached_modules)
195 cgcx: &CodegenContext<Self>,
196 modules: Vec<(String, Self::ThinBuffer)>,
197 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
198 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
199 back::lto::run_thin(cgcx, modules, cached_modules)
202 cgcx: &CodegenContext<Self>,
203 diag_handler: &Handler,
204 module: &ModuleCodegen<Self::Module>,
205 config: &ModuleConfig,
206 ) -> Result<(), FatalError> {
207 back::write::optimize(cgcx, diag_handler, module, config)
210 cgcx: &CodegenContext<Self>,
211 module: &mut ModuleCodegen<Self::Module>,
212 ) -> Result<(), FatalError> {
213 let diag_handler = cgcx.create_diag_handler();
214 back::lto::run_pass_manager(cgcx, &diag_handler, module, false)
216 unsafe fn optimize_thin(
217 cgcx: &CodegenContext<Self>,
218 thin: ThinModule<Self>,
219 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
220 back::lto::optimize_thin_module(thin, cgcx)
223 cgcx: &CodegenContext<Self>,
224 diag_handler: &Handler,
225 module: ModuleCodegen<Self::Module>,
226 config: &ModuleConfig,
227 ) -> Result<CompiledModule, FatalError> {
228 back::write::codegen(cgcx, diag_handler, module, config)
230 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
231 back::lto::prepare_thin(module)
233 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
234 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
238 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
239 unsafe impl Sync for LlvmCodegenBackend {}
241 impl LlvmCodegenBackend {
242 pub fn new() -> Box<dyn CodegenBackend> {
243 Box::new(LlvmCodegenBackend(()))
247 impl CodegenBackend for LlvmCodegenBackend {
248 fn init(&self, sess: &Session) {
249 llvm_util::init(sess); // Make sure llvm is inited
252 fn provide(&self, providers: &mut Providers) {
253 providers.global_backend_features =
254 |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
257 fn print(&self, req: PrintRequest, sess: &Session) {
259 PrintRequest::RelocationModels => {
260 println!("Available relocation models:");
271 println!(" {}", name);
275 PrintRequest::CodeModels => {
276 println!("Available code models:");
277 for name in &["tiny", "small", "kernel", "medium", "large"] {
278 println!(" {}", name);
282 PrintRequest::TlsModels => {
283 println!("Available TLS models:");
284 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
285 println!(" {}", name);
289 PrintRequest::StackProtectorStrategies => {
291 r#"Available stack protector strategies:
293 Generate stack canaries in all functions.
296 Generate stack canaries in a function if it either:
297 - has a local variable of `[T; N]` type, regardless of `T` and `N`
298 - takes the address of a local variable.
300 (Note that a local variable being borrowed is not equivalent to its
301 address being taken: e.g. some borrows may be removed by optimization,
302 while by-value argument passing may be implemented with reference to a
303 local stack variable in the ABI.)
306 Generate stack canaries in functions with local variables of `[T; N]`
307 type, where `T` is byte-sized and `N` >= 8.
310 Do not generate stack canaries.
314 req => llvm_util::print(req, sess),
318 fn print_passes(&self) {
319 llvm_util::print_passes();
322 fn print_version(&self) {
323 llvm_util::print_version();
326 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
327 target_features(sess)
330 fn codegen_crate<'tcx>(
333 metadata: EncodedMetadata,
334 need_metadata_module: bool,
336 Box::new(rustc_codegen_ssa::base::codegen_crate(
337 LlvmCodegenBackend(()),
339 crate::llvm_util::target_cpu(tcx.sess).to_string(),
341 need_metadata_module,
347 ongoing_codegen: Box<dyn Any>,
349 outputs: &OutputFilenames,
350 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
351 let (codegen_results, work_products) = ongoing_codegen
352 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
353 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
356 sess.time("llvm_dump_timing_file", || {
357 if sess.opts.debugging_opts.llvm_time_trace {
358 let file_name = outputs.with_extension("llvm_timings.json");
359 llvm_util::time_trace_profiler_finish(&file_name);
363 Ok((codegen_results, work_products))
369 codegen_results: CodegenResults,
370 outputs: &OutputFilenames,
371 ) -> Result<(), ErrorGuaranteed> {
372 use crate::back::archive::LlvmArchiveBuilder;
373 use rustc_codegen_ssa::back::link::link_binary;
375 // Run the linker on any artifacts that resulted from the LLVM run.
376 // This should produce either a finished executable or library.
377 link_binary::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs)
381 pub struct ModuleLlvm {
382 llcx: &'static mut llvm::Context,
383 llmod_raw: *const llvm::Module,
384 tm: &'static mut llvm::TargetMachine,
387 unsafe impl Send for ModuleLlvm {}
388 unsafe impl Sync for ModuleLlvm {}
391 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
393 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
394 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
395 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
399 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
401 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
402 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
403 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
408 cgcx: &CodegenContext<LlvmCodegenBackend>,
412 ) -> Result<Self, FatalError> {
414 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
415 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
416 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
417 let tm = match (cgcx.tm_factory)(tm_factory_config) {
420 handler.struct_err(&e).emit();
421 return Err(FatalError);
425 Ok(ModuleLlvm { llmod_raw, llcx, tm })
429 fn llmod(&self) -> &llvm::Module {
430 unsafe { &*self.llmod_raw }
434 impl Drop for ModuleLlvm {
437 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
438 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));