]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Rollup merge of #74272 - davidtwco:issue-73626-multiline-mixed-comments, r=Mark-Simul...
[rust.git] / src / librustc_codegen_llvm / lib.rs
1 //! The Rust compiler.
2 //!
3 //! # Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
8 #![feature(bool_to_option)]
9 #![feature(const_cstr_unchecked)]
10 #![feature(crate_visibility_modifier)]
11 #![feature(extern_types)]
12 #![feature(in_band_lifetimes)]
13 #![feature(nll)]
14 #![feature(or_patterns)]
15 #![feature(trusted_len)]
16 #![recursion_limit = "256"]
17
18 use back::write::{create_informational_target_machine, create_target_machine};
19
20 pub use llvm_util::target_features;
21 use rustc_ast::expand::allocator::AllocatorKind;
22 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
23 use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, ModuleConfig};
24 use rustc_codegen_ssa::traits::*;
25 use rustc_codegen_ssa::ModuleCodegen;
26 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
27 use rustc_errors::{ErrorReported, FatalError, Handler};
28 use rustc_middle::dep_graph::{DepGraph, WorkProduct};
29 use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
30 use rustc_middle::ty::{self, TyCtxt};
31 use rustc_serialize::json;
32 use rustc_session::config::{self, OptLevel, OutputFilenames, PrintRequest};
33 use rustc_session::Session;
34 use rustc_span::symbol::Symbol;
35
36 use std::any::Any;
37 use std::ffi::CStr;
38 use std::fs;
39 use std::sync::Arc;
40
41 mod back {
42     pub mod archive;
43     pub mod lto;
44     mod profiling;
45     pub mod write;
46 }
47
48 mod abi;
49 mod allocator;
50 mod asm;
51 mod attributes;
52 mod base;
53 mod builder;
54 mod callee;
55 mod common;
56 mod consts;
57 mod context;
58 mod coverageinfo;
59 mod debuginfo;
60 mod declare;
61 mod intrinsic;
62
63 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
64 #[path = "llvm/mod.rs"]
65 mod llvm_;
66 pub mod llvm {
67     pub use super::llvm_::*;
68 }
69
70 mod llvm_util;
71 mod metadata;
72 mod mono_item;
73 mod type_;
74 mod type_of;
75 mod va_arg;
76 mod value;
77
78 #[derive(Clone)]
79 pub struct LlvmCodegenBackend(());
80
81 impl ExtraBackendMethods for LlvmCodegenBackend {
82     fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
83         ModuleLlvm::new_metadata(tcx, mod_name)
84     }
85
86     fn write_compressed_metadata<'tcx>(
87         &self,
88         tcx: TyCtxt<'tcx>,
89         metadata: &EncodedMetadata,
90         llvm_module: &mut ModuleLlvm,
91     ) {
92         base::write_compressed_metadata(tcx, metadata, llvm_module)
93     }
94     fn codegen_allocator<'tcx>(
95         &self,
96         tcx: TyCtxt<'tcx>,
97         mods: &mut ModuleLlvm,
98         kind: AllocatorKind,
99     ) {
100         unsafe { allocator::codegen(tcx, mods, kind) }
101     }
102     fn compile_codegen_unit(
103         &self,
104         tcx: TyCtxt<'_>,
105         cgu_name: Symbol,
106     ) -> (ModuleCodegen<ModuleLlvm>, u64) {
107         base::compile_codegen_unit(tcx, cgu_name)
108     }
109     fn target_machine_factory(
110         &self,
111         sess: &Session,
112         optlvl: OptLevel,
113     ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
114         back::write::target_machine_factory(sess, optlvl)
115     }
116     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
117         llvm_util::target_cpu(sess)
118     }
119 }
120
121 impl WriteBackendMethods for LlvmCodegenBackend {
122     type Module = ModuleLlvm;
123     type ModuleBuffer = back::lto::ModuleBuffer;
124     type Context = llvm::Context;
125     type TargetMachine = &'static mut llvm::TargetMachine;
126     type ThinData = back::lto::ThinData;
127     type ThinBuffer = back::lto::ThinBuffer;
128     fn print_pass_timings(&self) {
129         unsafe {
130             llvm::LLVMRustPrintPassTimings();
131         }
132     }
133     fn run_fat_lto(
134         cgcx: &CodegenContext<Self>,
135         modules: Vec<FatLTOInput<Self>>,
136         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
137     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
138         back::lto::run_fat(cgcx, modules, cached_modules)
139     }
140     fn run_thin_lto(
141         cgcx: &CodegenContext<Self>,
142         modules: Vec<(String, Self::ThinBuffer)>,
143         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
144     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
145         back::lto::run_thin(cgcx, modules, cached_modules)
146     }
147     unsafe fn optimize(
148         cgcx: &CodegenContext<Self>,
149         diag_handler: &Handler,
150         module: &ModuleCodegen<Self::Module>,
151         config: &ModuleConfig,
152     ) -> Result<(), FatalError> {
153         back::write::optimize(cgcx, diag_handler, module, config)
154     }
155     unsafe fn optimize_thin(
156         cgcx: &CodegenContext<Self>,
157         thin: &mut ThinModule<Self>,
158     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
159         back::lto::optimize_thin_module(thin, cgcx)
160     }
161     unsafe fn codegen(
162         cgcx: &CodegenContext<Self>,
163         diag_handler: &Handler,
164         module: ModuleCodegen<Self::Module>,
165         config: &ModuleConfig,
166     ) -> Result<CompiledModule, FatalError> {
167         back::write::codegen(cgcx, diag_handler, module, config)
168     }
169     fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
170         back::lto::prepare_thin(module)
171     }
172     fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
173         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
174     }
175     fn run_lto_pass_manager(
176         cgcx: &CodegenContext<Self>,
177         module: &ModuleCodegen<Self::Module>,
178         config: &ModuleConfig,
179         thin: bool,
180     ) {
181         back::lto::run_pass_manager(cgcx, module, config, thin)
182     }
183 }
184
185 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
186 unsafe impl Sync for LlvmCodegenBackend {}
187
188 impl LlvmCodegenBackend {
189     pub fn new() -> Box<dyn CodegenBackend> {
190         Box::new(LlvmCodegenBackend(()))
191     }
192 }
193
194 impl CodegenBackend for LlvmCodegenBackend {
195     fn init(&self, sess: &Session) {
196         llvm_util::init(sess); // Make sure llvm is inited
197     }
198
199     fn print(&self, req: PrintRequest, sess: &Session) {
200         match req {
201             PrintRequest::RelocationModels => {
202                 println!("Available relocation models:");
203                 for name in
204                     &["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
205                 {
206                     println!("    {}", name);
207                 }
208                 println!();
209             }
210             PrintRequest::CodeModels => {
211                 println!("Available code models:");
212                 for name in &["tiny", "small", "kernel", "medium", "large"] {
213                     println!("    {}", name);
214                 }
215                 println!();
216             }
217             PrintRequest::TlsModels => {
218                 println!("Available TLS models:");
219                 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
220                     println!("    {}", name);
221                 }
222                 println!();
223             }
224             req => llvm_util::print(req, sess),
225         }
226     }
227
228     fn print_passes(&self) {
229         llvm_util::print_passes();
230     }
231
232     fn print_version(&self) {
233         llvm_util::print_version();
234     }
235
236     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
237         target_features(sess)
238     }
239
240     fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
241         Box::new(metadata::LlvmMetadataLoader)
242     }
243
244     fn provide(&self, providers: &mut ty::query::Providers) {
245         attributes::provide(providers);
246     }
247
248     fn provide_extern(&self, providers: &mut ty::query::Providers) {
249         attributes::provide_extern(providers);
250     }
251
252     fn codegen_crate<'tcx>(
253         &self,
254         tcx: TyCtxt<'tcx>,
255         metadata: EncodedMetadata,
256         need_metadata_module: bool,
257     ) -> Box<dyn Any> {
258         Box::new(rustc_codegen_ssa::base::codegen_crate(
259             LlvmCodegenBackend(()),
260             tcx,
261             metadata,
262             need_metadata_module,
263         ))
264     }
265
266     fn join_codegen(
267         &self,
268         ongoing_codegen: Box<dyn Any>,
269         sess: &Session,
270         dep_graph: &DepGraph,
271     ) -> Result<Box<dyn Any>, ErrorReported> {
272         let (codegen_results, work_products) = ongoing_codegen
273             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
274             .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
275             .join(sess);
276         if sess.opts.debugging_opts.incremental_info {
277             rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
278         }
279
280         sess.time("serialize_work_products", move || {
281             rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
282         });
283
284         sess.compile_status()?;
285
286         Ok(Box::new(codegen_results))
287     }
288
289     fn link(
290         &self,
291         sess: &Session,
292         codegen_results: Box<dyn Any>,
293         outputs: &OutputFilenames,
294     ) -> Result<(), ErrorReported> {
295         let codegen_results = codegen_results
296             .downcast::<CodegenResults>()
297             .expect("Expected CodegenResults, found Box<Any>");
298
299         if sess.opts.debugging_opts.no_link {
300             // FIXME: use a binary format to encode the `.rlink` file
301             let rlink_data = json::encode(&codegen_results).map_err(|err| {
302                 sess.fatal(&format!("failed to encode rlink: {}", err));
303             })?;
304             let rlink_file = outputs.with_extension(config::RLINK_EXT);
305             fs::write(&rlink_file, rlink_data).map_err(|err| {
306                 sess.fatal(&format!("failed to write file {}: {}", rlink_file.display(), err));
307             })?;
308             return Ok(());
309         }
310
311         // Run the linker on any artifacts that resulted from the LLVM run.
312         // This should produce either a finished executable or library.
313         sess.time("link_crate", || {
314             use crate::back::archive::LlvmArchiveBuilder;
315             use rustc_codegen_ssa::back::link::link_binary;
316
317             let target_cpu = crate::llvm_util::target_cpu(sess);
318             link_binary::<LlvmArchiveBuilder<'_>>(
319                 sess,
320                 &codegen_results,
321                 outputs,
322                 &codegen_results.crate_name.as_str(),
323                 target_cpu,
324             );
325         });
326
327         // Now that we won't touch anything in the incremental compilation directory
328         // any more, we can finalize it (which involves renaming it)
329         rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
330
331         sess.time("llvm_dump_timing_file", || {
332             if sess.opts.debugging_opts.llvm_time_trace {
333                 llvm_util::time_trace_profiler_finish("llvm_timings.json");
334             }
335         });
336
337         Ok(())
338     }
339 }
340
341 pub struct ModuleLlvm {
342     llcx: &'static mut llvm::Context,
343     llmod_raw: *const llvm::Module,
344     tm: &'static mut llvm::TargetMachine,
345 }
346
347 unsafe impl Send for ModuleLlvm {}
348 unsafe impl Sync for ModuleLlvm {}
349
350 impl ModuleLlvm {
351     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
352         unsafe {
353             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
354             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
355             ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx) }
356         }
357     }
358
359     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
360         unsafe {
361             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
362             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
363             ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
364         }
365     }
366
367     fn parse(
368         cgcx: &CodegenContext<LlvmCodegenBackend>,
369         name: &CStr,
370         buffer: &[u8],
371         handler: &Handler,
372     ) -> Result<Self, FatalError> {
373         unsafe {
374             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
375             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
376             let tm = match (cgcx.tm_factory.0)() {
377                 Ok(m) => m,
378                 Err(e) => {
379                     handler.struct_err(&e).emit();
380                     return Err(FatalError);
381                 }
382             };
383
384             Ok(ModuleLlvm { llmod_raw, llcx, tm })
385         }
386     }
387
388     fn llmod(&self) -> &llvm::Module {
389         unsafe { &*self.llmod_raw }
390     }
391 }
392
393 impl Drop for ModuleLlvm {
394     fn drop(&mut self) {
395         unsafe {
396             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
397             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
398         }
399     }
400 }