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