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(hash_raw_entry)]
9 #![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;
21 use back::write::{create_informational_target_machine, create_target_machine};
23 pub use llvm_util::target_features;
24 use rustc_ast::expand::allocator::AllocatorKind;
25 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
26 use rustc_codegen_ssa::back::write::{
27 CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
29 use rustc_codegen_ssa::traits::*;
30 use rustc_codegen_ssa::ModuleCodegen;
31 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
32 use rustc_data_structures::fx::FxHashMap;
33 use rustc_errors::{ErrorGuaranteed, FatalError, Handler};
34 use rustc_metadata::EncodedMetadata;
35 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
36 use rustc_middle::ty::query::Providers;
37 use rustc_middle::ty::TyCtxt;
38 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
39 use rustc_session::Session;
40 use rustc_span::symbol::Symbol;
67 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
68 #[path = "llvm/mod.rs"]
71 pub use super::llvm_::*;
82 pub struct LlvmCodegenBackend(());
84 struct TimeTraceProfiler {
88 impl TimeTraceProfiler {
89 fn new(enabled: bool) -> Self {
91 unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
93 TimeTraceProfiler { enabled }
97 impl Drop for TimeTraceProfiler {
100 unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
105 impl ExtraBackendMethods for LlvmCodegenBackend {
106 fn codegen_allocator<'tcx>(
111 has_alloc_error_handler: bool,
113 let mut module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
115 allocator::codegen(tcx, &mut module_llvm, module_name, kind, has_alloc_error_handler);
119 fn compile_codegen_unit(
123 ) -> (ModuleCodegen<ModuleLlvm>, u64) {
124 base::compile_codegen_unit(tcx, cgu_name)
126 fn target_machine_factory(
130 target_features: &[String],
131 ) -> TargetMachineFactoryFn<Self> {
132 back::write::target_machine_factory(sess, optlvl, target_features)
134 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
135 llvm_util::target_cpu(sess)
137 fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
138 llvm_util::tune_cpu(sess)
141 fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
147 std::thread::spawn(move || {
148 let _profiler = TimeTraceProfiler::new(time_trace);
153 fn spawn_named_thread<F, T>(
157 ) -> std::io::Result<std::thread::JoinHandle<T>>
163 std::thread::Builder::new().name(name).spawn(move || {
164 let _profiler = TimeTraceProfiler::new(time_trace);
170 impl WriteBackendMethods for LlvmCodegenBackend {
171 type Module = ModuleLlvm;
172 type ModuleBuffer = back::lto::ModuleBuffer;
173 type Context = llvm::Context;
174 type TargetMachine = &'static mut llvm::TargetMachine;
175 type ThinData = back::lto::ThinData;
176 type ThinBuffer = back::lto::ThinBuffer;
177 fn print_pass_timings(&self) {
179 llvm::LLVMRustPrintPassTimings();
183 cgcx: &CodegenContext<Self>,
184 diag_handler: &Handler,
185 modules: Vec<ModuleCodegen<Self::Module>>,
186 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
187 back::write::link(cgcx, diag_handler, modules)
190 cgcx: &CodegenContext<Self>,
191 modules: Vec<FatLTOInput<Self>>,
192 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
193 ) -> Result<LtoModuleCodegen<Self>, FatalError> {
194 back::lto::run_fat(cgcx, modules, cached_modules)
197 cgcx: &CodegenContext<Self>,
198 modules: Vec<(String, Self::ThinBuffer)>,
199 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
200 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
201 back::lto::run_thin(cgcx, modules, cached_modules)
204 cgcx: &CodegenContext<Self>,
205 diag_handler: &Handler,
206 module: &ModuleCodegen<Self::Module>,
207 config: &ModuleConfig,
208 ) -> Result<(), FatalError> {
209 back::write::optimize(cgcx, diag_handler, module, config)
212 cgcx: &CodegenContext<Self>,
213 module: &mut ModuleCodegen<Self::Module>,
214 ) -> Result<(), FatalError> {
215 let diag_handler = cgcx.create_diag_handler();
216 back::lto::run_pass_manager(cgcx, &diag_handler, module, false)
218 unsafe fn optimize_thin(
219 cgcx: &CodegenContext<Self>,
220 thin: ThinModule<Self>,
221 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
222 back::lto::optimize_thin_module(thin, cgcx)
225 cgcx: &CodegenContext<Self>,
226 diag_handler: &Handler,
227 module: ModuleCodegen<Self::Module>,
228 config: &ModuleConfig,
229 ) -> Result<CompiledModule, FatalError> {
230 back::write::codegen(cgcx, diag_handler, module, config)
232 fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
233 back::lto::prepare_thin(module)
235 fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
236 (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
240 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
241 unsafe impl Sync for LlvmCodegenBackend {}
243 impl LlvmCodegenBackend {
244 pub fn new() -> Box<dyn CodegenBackend> {
245 Box::new(LlvmCodegenBackend(()))
249 impl CodegenBackend for LlvmCodegenBackend {
250 fn init(&self, sess: &Session) {
251 llvm_util::init(sess); // Make sure llvm is inited
254 fn provide(&self, providers: &mut Providers) {
255 providers.global_backend_features =
256 |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true)
259 fn print(&self, req: PrintRequest, sess: &Session) {
261 PrintRequest::RelocationModels => {
262 println!("Available relocation models:");
273 println!(" {}", name);
277 PrintRequest::CodeModels => {
278 println!("Available code models:");
279 for name in &["tiny", "small", "kernel", "medium", "large"] {
280 println!(" {}", name);
284 PrintRequest::TlsModels => {
285 println!("Available TLS models:");
286 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
287 println!(" {}", name);
291 PrintRequest::StackProtectorStrategies => {
293 r#"Available stack protector strategies:
295 Generate stack canaries in all functions.
298 Generate stack canaries in a function if it either:
299 - has a local variable of `[T; N]` type, regardless of `T` and `N`
300 - takes the address of a local variable.
302 (Note that a local variable being borrowed is not equivalent to its
303 address being taken: e.g. some borrows may be removed by optimization,
304 while by-value argument passing may be implemented with reference to a
305 local stack variable in the ABI.)
308 Generate stack canaries in functions with local variables of `[T; N]`
309 type, where `T` is byte-sized and `N` >= 8.
312 Do not generate stack canaries.
316 req => llvm_util::print(req, sess),
320 fn print_passes(&self) {
321 llvm_util::print_passes();
324 fn print_version(&self) {
325 llvm_util::print_version();
328 fn target_features(&self, sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
329 target_features(sess, allow_unstable)
332 fn codegen_crate<'tcx>(
335 metadata: EncodedMetadata,
336 need_metadata_module: bool,
338 Box::new(rustc_codegen_ssa::base::codegen_crate(
339 LlvmCodegenBackend(()),
341 crate::llvm_util::target_cpu(tcx.sess).to_string(),
343 need_metadata_module,
349 ongoing_codegen: Box<dyn Any>,
351 outputs: &OutputFilenames,
352 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
353 let (codegen_results, work_products) = ongoing_codegen
354 .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
355 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
358 sess.time("llvm_dump_timing_file", || {
359 if sess.opts.unstable_opts.llvm_time_trace {
360 let file_name = outputs.with_extension("llvm_timings.json");
361 llvm_util::time_trace_profiler_finish(&file_name);
365 Ok((codegen_results, work_products))
371 codegen_results: CodegenResults,
372 outputs: &OutputFilenames,
373 ) -> Result<(), ErrorGuaranteed> {
374 use crate::back::archive::LlvmArchiveBuilderBuilder;
375 use rustc_codegen_ssa::back::link::link_binary;
377 // Run the linker on any artifacts that resulted from the LLVM run.
378 // This should produce either a finished executable or library.
379 link_binary(sess, &LlvmArchiveBuilderBuilder, &codegen_results, outputs)
383 pub struct ModuleLlvm {
384 llcx: &'static mut llvm::Context,
385 llmod_raw: *const llvm::Module,
386 tm: &'static mut llvm::TargetMachine,
389 unsafe impl Send for ModuleLlvm {}
390 unsafe impl Sync for ModuleLlvm {}
393 fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
395 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
396 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
397 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
401 fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
403 let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
404 let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
405 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
410 cgcx: &CodegenContext<LlvmCodegenBackend>,
414 ) -> Result<Self, FatalError> {
416 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
417 let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
418 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
419 let tm = match (cgcx.tm_factory)(tm_factory_config) {
422 handler.struct_err(&e).emit();
423 return Err(FatalError);
427 Ok(ModuleLlvm { llmod_raw, llcx, tm })
431 fn llmod(&self) -> &llvm::Module {
432 unsafe { &*self.llmod_raw }
436 impl Drop for ModuleLlvm {
439 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
440 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));