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)]
13 #![feature(iter_intersperse)]
14 #![recursion_limit = "256"]
15 #![allow(rustc::potential_query_instability)]
18 extern crate rustc_macros;
20 use back::write::{create_informational_target_machine, create_target_machine};
22 pub use llvm_util::target_features;
23 use rustc_ast::expand::allocator::AllocatorKind;
24 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
25 use rustc_codegen_ssa::back::write::{
26 CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
28 use rustc_codegen_ssa::traits::*;
29 use rustc_codegen_ssa::ModuleCodegen;
30 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
31 use rustc_data_structures::fx::FxHashMap;
32 use rustc_errors::{ErrorGuaranteed, FatalError, Handler};
33 use rustc_metadata::EncodedMetadata;
34 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
35 use rustc_middle::ty::query::Providers;
36 use rustc_middle::ty::TyCtxt;
37 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
38 use rustc_session::Session;
39 use rustc_span::symbol::Symbol;
66 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
67 #[path = "llvm/mod.rs"]
70 pub use super::llvm_::*;
81 pub struct LlvmCodegenBackend(());
83 struct TimeTraceProfiler {
87 impl TimeTraceProfiler {
88 fn new(enabled: bool) -> Self {
90 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
92 TimeTraceProfiler { enabled }
96 impl Drop for TimeTraceProfiler {
99 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
104 impl ExtraBackendMethods for LlvmCodegenBackend {
105 fn codegen_allocator<'tcx>(
110 has_alloc_error_handler: bool,
112 let mut module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
114 allocator::codegen(tcx, &mut module_llvm, module_name, kind, has_alloc_error_handler);
118 fn compile_codegen_unit(
122 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
123 base::compile_codegen_unit(tcx, cgu_name)
125 fn target_machine_factory(
129 target_features: &[String],
130 ) -> TargetMachineFactoryFn<Self> {
131 back::write::target_machine_factory(sess, optlvl, target_features)
133 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
134 llvm_util::target_cpu(sess)
136 fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
137 llvm_util::tune_cpu(sess)
140 fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
146 std::thread::spawn(move || {
147 let _profiler = TimeTraceProfiler::new(time_trace);
152 fn spawn_named_thread<F, T>(
156 ) -> std::io::Result<std::thread::JoinHandle<T>>
162 std::thread::Builder::new().name(name).spawn(move || {
163 let _profiler = TimeTraceProfiler::new(time_trace);
169 impl WriteBackendMethods for LlvmCodegenBackend {
170 type Module = ModuleLlvm;
171 type ModuleBuffer = back::lto::ModuleBuffer;
172 type Context = llvm::Context;
173 type TargetMachine = &'static mut llvm::TargetMachine;
174 type ThinData = back::lto::ThinData;
175 type ThinBuffer = back::lto::ThinBuffer;
176 fn print_pass_timings(&self) {
178 llvm::LLVMRustPrintPassTimings();
182 cgcx: &CodegenContext<Self>,
183 diag_handler: &Handler,
184 modules: Vec<ModuleCodegen<Self::Module>>,
185 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
186 back::write::link(cgcx, diag_handler, modules)
189 cgcx: &CodegenContext<Self>,
190 modules: Vec<FatLTOInput<Self>>,
191 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
192 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
193 back::lto::run_fat(cgcx, modules, cached_modules)
196 cgcx: &CodegenContext<Self>,
197 modules: Vec<(String, Self::ThinBuffer)>,
198 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
199 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
200 back::lto::run_thin(cgcx, modules, cached_modules)
203 cgcx: &CodegenContext<Self>,
204 diag_handler: &Handler,
205 module: &ModuleCodegen<Self::Module>,
206 config: &ModuleConfig,
207 ) -> Result<(), FatalError> {
208 back::write::optimize(cgcx, diag_handler, module, config)
211 cgcx: &CodegenContext<Self>,
212 module: &mut ModuleCodegen<Self::Module>,
213 ) -> Result<(), FatalError> {
214 let diag_handler = cgcx.create_diag_handler();
215 back::lto::run_pass_manager(cgcx, &diag_handler, module, false)
217 unsafe fn optimize_thin(
218 cgcx: &CodegenContext<Self>,
219 thin: ThinModule<Self>,
220 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
221 back::lto::optimize_thin_module(thin, cgcx)
224 cgcx: &CodegenContext<Self>,
225 diag_handler: &Handler,
226 module: ModuleCodegen<Self::Module>,
227 config: &ModuleConfig,
228 ) -> Result<CompiledModule, FatalError> {
229 back::write::codegen(cgcx, diag_handler, module, config)
231 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
232 back::lto::prepare_thin(module)
234 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
235 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
239 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
240 unsafe impl Sync for LlvmCodegenBackend {}
242 impl LlvmCodegenBackend {
243 pub fn new() -> Box<dyn CodegenBackend> {
244 Box::new(LlvmCodegenBackend(()))
248 impl CodegenBackend for LlvmCodegenBackend {
249 fn init(&self, sess: &Session) {
250 llvm_util::init(sess); // Make sure llvm is inited
253 fn provide(&self, providers: &mut Providers) {
254 providers.global_backend_features =
255 |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
258 fn print(&self, req: PrintRequest, sess: &Session) {
260 PrintRequest::RelocationModels => {
261 println!("Available relocation models:");
272 println!(" {}", name);
276 PrintRequest::CodeModels => {
277 println!("Available code models:");
278 for name in &["tiny", "small", "kernel", "medium", "large"] {
279 println!(" {}", name);
283 PrintRequest::TlsModels => {
284 println!("Available TLS models:");
285 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
286 println!(" {}", name);
290 PrintRequest::StackProtectorStrategies => {
292 r#"Available stack protector strategies:
294 Generate stack canaries in all functions.
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.
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.)
307 Generate stack canaries in functions with local variables of `[T; N]`
308 type, where `T` is byte-sized and `N` >= 8.
311 Do not generate stack canaries.
315 req => llvm_util::print(req, sess),
319 fn print_passes(&self) {
320 llvm_util::print_passes();
323 fn print_version(&self) {
324 llvm_util::print_version();
327 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
328 target_features(sess)
331 fn codegen_crate<'tcx>(
334 metadata: EncodedMetadata,
335 need_metadata_module: bool,
337 Box::new(rustc_codegen_ssa::base::codegen_crate(
338 LlvmCodegenBackend(()),
340 crate::llvm_util::target_cpu(tcx.sess).to_string(),
342 need_metadata_module,
348 ongoing_codegen: Box<dyn Any>,
350 outputs: &OutputFilenames,
351 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
352 let (codegen_results, work_products) = ongoing_codegen
353 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
354 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
357 sess.time("llvm_dump_timing_file", || {
358 if sess.opts.debugging_opts.llvm_time_trace {
359 let file_name = outputs.with_extension("llvm_timings.json");
360 llvm_util::time_trace_profiler_finish(&file_name);
364 Ok((codegen_results, work_products))
370 codegen_results: CodegenResults,
371 outputs: &OutputFilenames,
372 ) -> Result<(), ErrorGuaranteed> {
373 use crate::back::archive::LlvmArchiveBuilder;
374 use rustc_codegen_ssa::back::link::link_binary;
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::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs)
382 pub struct ModuleLlvm {
383 llcx: &'static mut llvm::Context,
384 llmod_raw: *const llvm::Module,
385 tm: &'static mut llvm::TargetMachine,
388 unsafe impl Send for ModuleLlvm {}
389 unsafe impl Sync for ModuleLlvm {}
392 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
394 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
395 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
396 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
400 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
402 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
403 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
404 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
409 cgcx: &CodegenContext<LlvmCodegenBackend>,
413 ) -> Result<Self, FatalError> {
415 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
416 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
417 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
418 let tm = match (cgcx.tm_factory)(tm_factory_config) {
421 handler.struct_err(&e).emit();
422 return Err(FatalError);
426 Ok(ModuleLlvm { llmod_raw, llcx, tm })
430 fn llmod(&self) -> &llvm::Module {
431 unsafe { &*self.llmod_raw }
435 impl Drop for ModuleLlvm {
438 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
439 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));