]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
CommonWriteMethods are not static any more
[rust.git] / src / librustc_codegen_llvm / lib.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The Rust compiler.
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19       html_root_url = "https://doc.rust-lang.org/nightly/")]
20
21 #![feature(box_patterns)]
22 #![feature(box_syntax)]
23 #![feature(crate_visibility_modifier)]
24 #![feature(custom_attribute)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![allow(unused_attributes)]
28 #![feature(libc)]
29 #![feature(nll)]
30 #![feature(quote)]
31 #![feature(range_contains)]
32 #![feature(rustc_diagnostic_macros)]
33 #![feature(slice_sort_by_cached_key)]
34 #![feature(optin_builtin_traits)]
35 #![feature(concat_idents)]
36 #![feature(link_args)]
37 #![feature(static_nobundle)]
38
39 use back::write::create_target_machine;
40 use rustc::dep_graph::WorkProduct;
41 use syntax_pos::symbol::Symbol;
42
43 #[macro_use] extern crate bitflags;
44 extern crate flate2;
45 extern crate libc;
46 #[macro_use] extern crate rustc;
47 extern crate jobserver;
48 extern crate num_cpus;
49 extern crate rustc_mir;
50 extern crate rustc_allocator;
51 extern crate rustc_apfloat;
52 extern crate rustc_target;
53 #[macro_use] extern crate rustc_data_structures;
54 extern crate rustc_demangle;
55 extern crate rustc_incremental;
56 extern crate rustc_llvm;
57 extern crate rustc_platform_intrinsics as intrinsics;
58 extern crate rustc_codegen_utils;
59 extern crate rustc_fs_util;
60
61 #[macro_use] extern crate log;
62 #[macro_use] extern crate syntax;
63 extern crate syntax_pos;
64 extern crate rustc_errors as errors;
65 extern crate serialize;
66 extern crate cc; // Used to locate MSVC
67 extern crate tempfile;
68 extern crate memmap;
69
70 use back::bytecode::RLIB_BYTECODE_EXTENSION;
71 use interfaces::{Backend, CommonWriteMethods};
72 use value::Value;
73 use type_::Type;
74
75 pub use llvm_util::target_features;
76 use std::any::Any;
77 use std::sync::mpsc;
78 use std::marker::PhantomData;
79 use libc::{c_uint, c_char};
80 use rustc_data_structures::sync::Lrc;
81
82 use rustc::dep_graph::DepGraph;
83 use rustc::hir::def_id::CrateNum;
84 use rustc::middle::cstore::MetadataLoader;
85 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
86 use rustc::middle::lang_items::LangItem;
87 use rustc::session::{Session, CompileIncomplete};
88 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
89 use rustc::ty::{self, TyCtxt};
90 use rustc::util::time_graph;
91 use rustc::util::nodemap::{FxHashSet, FxHashMap};
92 use rustc::util::profiling::ProfileCategory;
93 use rustc_mir::monomorphize;
94 use rustc_codegen_utils::{CompiledModule, ModuleKind};
95 use rustc_codegen_utils::codegen_backend::CodegenBackend;
96 use rustc_data_structures::svh::Svh;
97
98 mod diagnostics;
99
100 mod back {
101     mod archive;
102     pub mod bytecode;
103     pub mod link;
104     pub mod lto;
105     pub mod write;
106     mod rpath;
107     pub mod wasm;
108 }
109
110 mod interfaces;
111
112 mod abi;
113 mod allocator;
114 mod asm;
115 mod attributes;
116 mod base;
117 mod builder;
118 mod callee;
119 mod common;
120 mod consts;
121 mod context;
122 mod debuginfo;
123 mod declare;
124 mod glue;
125 mod intrinsic;
126
127 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
128 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
129
130 mod llvm_util;
131 mod metadata;
132 mod meth;
133 mod mir;
134 mod mono_item;
135 mod type_;
136 mod type_of;
137 mod value;
138
139 pub struct LlvmCodegenBackend(());
140
141 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
142 impl !Sync for LlvmCodegenBackend {}
143
144 impl LlvmCodegenBackend {
145     pub fn new() -> Box<dyn CodegenBackend> {
146         box LlvmCodegenBackend(())
147     }
148 }
149
150 impl CodegenBackend for LlvmCodegenBackend {
151     fn init(&self, sess: &Session) {
152         llvm_util::init(sess); // Make sure llvm is inited
153     }
154
155     fn print(&self, req: PrintRequest, sess: &Session) {
156         match req {
157             PrintRequest::RelocationModels => {
158                 println!("Available relocation models:");
159                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
160                     println!("    {}", name);
161                 }
162                 println!("");
163             }
164             PrintRequest::CodeModels => {
165                 println!("Available code models:");
166                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
167                     println!("    {}", name);
168                 }
169                 println!("");
170             }
171             PrintRequest::TlsModels => {
172                 println!("Available TLS models:");
173                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
174                     println!("    {}", name);
175                 }
176                 println!("");
177             }
178             req => llvm_util::print(req, sess),
179         }
180     }
181
182     fn print_passes(&self) {
183         llvm_util::print_passes();
184     }
185
186     fn print_version(&self) {
187         llvm_util::print_version();
188     }
189
190     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
191         &DIAGNOSTICS
192     }
193
194     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
195         target_features(sess)
196     }
197
198     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
199         box metadata::LlvmMetadataLoader
200     }
201
202     fn provide(&self, providers: &mut ty::query::Providers) {
203         rustc_codegen_utils::symbol_export::provide(providers);
204         rustc_codegen_utils::symbol_names::provide(providers);
205         base::provide_both(providers);
206         attributes::provide(providers);
207     }
208
209     fn provide_extern(&self, providers: &mut ty::query::Providers) {
210         rustc_codegen_utils::symbol_export::provide_extern(providers);
211         base::provide_both(providers);
212         attributes::provide_extern(providers);
213     }
214
215     fn codegen_crate<'a, 'tcx>(
216         &self,
217         tcx: TyCtxt<'a, 'tcx, 'tcx>,
218         rx: mpsc::Receiver<Box<dyn Any + Send>>
219     ) -> Box<dyn Any> {
220         box base::codegen_crate(tcx, rx)
221     }
222
223     fn join_codegen_and_link(
224         &self,
225         ongoing_codegen: Box<dyn Any>,
226         sess: &Session,
227         dep_graph: &DepGraph,
228         outputs: &OutputFilenames,
229     ) -> Result<(), CompileIncomplete>{
230         use rustc::util::common::time;
231         let (ongoing_codegen, work_products) =
232             ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
233                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
234                 .join(sess);
235         if sess.opts.debugging_opts.incremental_info {
236             back::write::dump_incremental_data(&ongoing_codegen);
237         }
238
239         time(sess,
240              "serialize work products",
241              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
242
243         sess.compile_status()?;
244
245         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
246                                                    i == OutputType::Metadata) {
247             return Ok(());
248         }
249
250         // Run the linker on any artifacts that resulted from the LLVM run.
251         // This should produce either a finished executable or library.
252         sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
253         time(sess, "linking", || {
254             back::link::link_binary(sess, &ongoing_codegen,
255                                     outputs, &ongoing_codegen.crate_name.as_str());
256         });
257         sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
258
259         // Now that we won't touch anything in the incremental compilation directory
260         // any more, we can finalize it (which involves renaming it)
261         rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
262
263         Ok(())
264     }
265 }
266
267 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
268 #[no_mangle]
269 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
270     LlvmCodegenBackend::new()
271 }
272
273 struct ModuleCodegen {
274     /// The name of the module. When the crate may be saved between
275     /// compilations, incremental compilation requires that name be
276     /// unique amongst **all** crates.  Therefore, it should contain
277     /// something unique to this crate (e.g., a module path) as well
278     /// as the crate name and disambiguator.
279     /// We currently generate these names via CodegenUnit::build_cgu_name().
280     name: String,
281     module_llvm: ModuleLlvm<'static>,
282     kind: ModuleKind,
283 }
284
285 struct CachedModuleCodegen {
286     name: String,
287     source: WorkProduct,
288 }
289
290 impl ModuleCodegen {
291     fn into_compiled_module(self,
292                             emit_obj: bool,
293                             emit_bc: bool,
294                             emit_bc_compressed: bool,
295                             outputs: &OutputFilenames) -> CompiledModule {
296         let object = if emit_obj {
297             Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
298         } else {
299             None
300         };
301         let bytecode = if emit_bc {
302             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
303         } else {
304             None
305         };
306         let bytecode_compressed = if emit_bc_compressed {
307             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
308                         .with_extension(RLIB_BYTECODE_EXTENSION))
309         } else {
310             None
311         };
312
313         CompiledModule {
314             name: self.name.clone(),
315             kind: self.kind,
316             object,
317             bytecode,
318             bytecode_compressed,
319         }
320     }
321 }
322
323 struct ModuleLlvm<'ll> {
324     llcx: &'static mut llvm::Context,
325     llmod_raw: *const llvm::Module,
326     tm: &'static mut llvm::TargetMachine,
327     phantom: PhantomData<&'ll ()>
328 }
329
330 impl<'ll> Backend for ModuleLlvm<'ll> {
331     type Value = &'ll Value;
332     type BasicBlock = &'ll llvm::BasicBlock;
333     type Type = &'ll Type;
334     type Context = &'ll llvm::Context;
335 }
336
337 unsafe impl Send for ModuleLlvm<'ll> { }
338 unsafe impl Sync for ModuleLlvm<'ll> { }
339
340 impl ModuleLlvm<'ll> {
341     fn new(sess: &Session, mod_name: &str) -> Self {
342         unsafe {
343             let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
344             let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
345
346             ModuleLlvm {
347                 llmod_raw,
348                 llcx,
349                 tm: create_target_machine(sess, false),
350                 phantom: PhantomData
351             }
352         }
353     }
354
355     fn llmod(&self) -> &llvm::Module {
356         unsafe {
357             &*self.llmod_raw
358         }
359     }
360 }
361
362 impl CommonWriteMethods for ModuleLlvm<'ll> {
363     fn val_ty(&self, v: &'ll Value) -> &'ll Type {
364         unsafe {
365             llvm::LLVMTypeOf(v)
366         }
367     }
368
369     fn c_bytes_in_context(&self, llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
370         unsafe {
371             let ptr = bytes.as_ptr() as *const c_char;
372             return llvm::LLVMConstStringInContext(
373                 llcx,
374                 ptr,
375                 bytes.len() as c_uint,
376                 llvm::True);
377         }
378     }
379
380     fn c_struct_in_context(
381         &self,
382         llcx: &'a llvm::Context,
383         elts: &[&'a Value],
384         packed: bool,
385     ) -> &'a Value {
386         unsafe {
387             llvm::LLVMConstStructInContext(llcx,
388                                            elts.as_ptr(), elts.len() as c_uint,
389                                            packed as llvm::Bool)
390         }
391     }
392 }
393
394 impl Drop for ModuleLlvm<'ll> {
395     fn drop(&mut self) {
396         unsafe {
397             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
398             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
399         }
400     }
401 }
402
403 struct CodegenResults {
404     crate_name: Symbol,
405     modules: Vec<CompiledModule>,
406     allocator_module: Option<CompiledModule>,
407     metadata_module: CompiledModule,
408     crate_hash: Svh,
409     metadata: rustc::middle::cstore::EncodedMetadata,
410     windows_subsystem: Option<String>,
411     linker_info: rustc_codegen_utils::linker::LinkerInfo,
412     crate_info: CrateInfo,
413 }
414
415 /// Misc info we load from metadata to persist beyond the tcx
416 struct CrateInfo {
417     panic_runtime: Option<CrateNum>,
418     compiler_builtins: Option<CrateNum>,
419     profiler_runtime: Option<CrateNum>,
420     sanitizer_runtime: Option<CrateNum>,
421     is_no_builtins: FxHashSet<CrateNum>,
422     native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
423     crate_name: FxHashMap<CrateNum, String>,
424     used_libraries: Lrc<Vec<NativeLibrary>>,
425     link_args: Lrc<Vec<String>>,
426     used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
427     used_crates_static: Vec<(CrateNum, LibSource)>,
428     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
429     wasm_imports: FxHashMap<String, String>,
430     lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
431     missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
432 }
433
434 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }