]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/lib.rs
rustc: Start a custom cabi module for wasm32
[rust.git] / src / librustc_trans / 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 #![deny(warnings)]
21
22 #![feature(box_patterns)]
23 #![feature(box_syntax)]
24 #![feature(custom_attribute)]
25 #![feature(fs_read_write)]
26 #![allow(unused_attributes)]
27 #![feature(i128_type)]
28 #![feature(i128)]
29 #![feature(inclusive_range)]
30 #![feature(inclusive_range_syntax)]
31 #![feature(libc)]
32 #![feature(quote)]
33 #![feature(rustc_diagnostic_macros)]
34 #![feature(slice_patterns)]
35 #![feature(conservative_impl_trait)]
36 #![feature(optin_builtin_traits)]
37
38 use rustc::dep_graph::WorkProduct;
39 use syntax_pos::symbol::Symbol;
40
41 #[macro_use]
42 extern crate bitflags;
43 extern crate flate2;
44 extern crate libc;
45 #[macro_use] extern crate rustc;
46 extern crate jobserver;
47 extern crate num_cpus;
48 extern crate rustc_mir;
49 extern crate rustc_allocator;
50 extern crate rustc_apfloat;
51 extern crate rustc_back;
52 extern crate rustc_const_math;
53 #[macro_use] extern crate rustc_data_structures;
54 extern crate rustc_demangle;
55 extern crate rustc_incremental;
56 extern crate rustc_llvm as llvm;
57 extern crate rustc_platform_intrinsics as intrinsics;
58 extern crate rustc_trans_utils;
59
60 #[macro_use] extern crate log;
61 #[macro_use] extern crate syntax;
62 extern crate syntax_pos;
63 extern crate rustc_errors as errors;
64 extern crate serialize;
65 extern crate cc; // Used to locate MSVC
66 extern crate tempdir;
67
68 use back::bytecode::RLIB_BYTECODE_EXTENSION;
69
70 pub use llvm_util::target_features;
71
72 use std::any::Any;
73 use std::path::PathBuf;
74 use std::sync::mpsc;
75 use rustc_data_structures::sync::Lrc;
76
77 use rustc::dep_graph::DepGraph;
78 use rustc::hir::def_id::CrateNum;
79 use rustc::middle::cstore::MetadataLoader;
80 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
81 use rustc::session::{Session, CompileIncomplete};
82 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
83 use rustc::ty::{self, TyCtxt};
84 use rustc::util::nodemap::{FxHashSet, FxHashMap};
85 use rustc_mir::monomorphize;
86 use rustc_trans_utils::trans_crate::TransCrate;
87
88 mod diagnostics;
89
90 mod back {
91     pub use rustc_trans_utils::symbol_names;
92     mod archive;
93     pub mod bytecode;
94     mod command;
95     pub mod linker;
96     pub mod link;
97     mod lto;
98     pub mod symbol_export;
99     pub mod write;
100     mod rpath;
101 }
102
103 mod abi;
104 mod allocator;
105 mod asm;
106 mod attributes;
107 mod base;
108 mod builder;
109 mod cabi_aarch64;
110 mod cabi_arm;
111 mod cabi_asmjs;
112 mod cabi_hexagon;
113 mod cabi_mips;
114 mod cabi_mips64;
115 mod cabi_msp430;
116 mod cabi_nvptx;
117 mod cabi_nvptx64;
118 mod cabi_powerpc;
119 mod cabi_powerpc64;
120 mod cabi_s390x;
121 mod cabi_sparc;
122 mod cabi_sparc64;
123 mod cabi_x86;
124 mod cabi_x86_64;
125 mod cabi_x86_win64;
126 mod cabi_wasm32;
127 mod callee;
128 mod common;
129 mod consts;
130 mod context;
131 mod debuginfo;
132 mod declare;
133 mod glue;
134 mod intrinsic;
135 mod llvm_util;
136 mod metadata;
137 mod meth;
138 mod mir;
139 mod time_graph;
140 mod trans_item;
141 mod type_;
142 mod type_of;
143 mod value;
144
145 pub struct LlvmTransCrate(());
146
147 impl !Send for LlvmTransCrate {} // Llvm is on a per-thread basis
148 impl !Sync for LlvmTransCrate {}
149
150 impl LlvmTransCrate {
151     pub fn new() -> Box<TransCrate> {
152         box LlvmTransCrate(())
153     }
154 }
155
156 impl TransCrate for LlvmTransCrate {
157     fn init(&self, sess: &Session) {
158         llvm_util::init(sess); // Make sure llvm is inited
159     }
160
161     fn print(&self, req: PrintRequest, sess: &Session) {
162         match req {
163             PrintRequest::RelocationModels => {
164                 println!("Available relocation models:");
165                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
166                     println!("    {}", name);
167                 }
168                 println!("");
169             }
170             PrintRequest::CodeModels => {
171                 println!("Available code models:");
172                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
173                     println!("    {}", name);
174                 }
175                 println!("");
176             }
177             PrintRequest::TlsModels => {
178                 println!("Available TLS models:");
179                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
180                     println!("    {}", name);
181                 }
182                 println!("");
183             }
184             req => llvm_util::print(req, sess),
185         }
186     }
187
188     fn print_passes(&self) {
189         llvm_util::print_passes();
190     }
191
192     fn print_version(&self) {
193         llvm_util::print_version();
194     }
195
196     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
197         &DIAGNOSTICS
198     }
199
200     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
201         target_features(sess)
202     }
203
204     fn metadata_loader(&self) -> Box<MetadataLoader> {
205         box metadata::LlvmMetadataLoader
206     }
207
208     fn provide(&self, providers: &mut ty::maps::Providers) {
209         back::symbol_names::provide(providers);
210         back::symbol_export::provide(providers);
211         base::provide(providers);
212         attributes::provide(providers);
213     }
214
215     fn provide_extern(&self, providers: &mut ty::maps::Providers) {
216         back::symbol_export::provide_extern(providers);
217     }
218
219     fn trans_crate<'a, 'tcx>(
220         &self,
221         tcx: TyCtxt<'a, 'tcx, 'tcx>,
222         rx: mpsc::Receiver<Box<Any + Send>>
223     ) -> Box<Any> {
224         box base::trans_crate(tcx, rx)
225     }
226
227     fn join_trans_and_link(
228         &self,
229         trans: Box<Any>,
230         sess: &Session,
231         dep_graph: &DepGraph,
232         outputs: &OutputFilenames,
233     ) -> Result<(), CompileIncomplete>{
234         use rustc::util::common::time;
235         let trans = trans.downcast::<::back::write::OngoingCrateTranslation>()
236             .expect("Expected LlvmTransCrate's OngoingCrateTranslation, found Box<Any>")
237             .join(sess, dep_graph);
238         if sess.opts.debugging_opts.incremental_info {
239             back::write::dump_incremental_data(&trans);
240         }
241
242         time(sess,
243              "serialize work products",
244              move || rustc_incremental::save_work_products(sess, &dep_graph));
245
246         sess.compile_status()?;
247
248         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
249                                                    i == OutputType::Metadata) {
250             return Ok(());
251         }
252
253         // Run the linker on any artifacts that resulted from the LLVM run.
254         // This should produce either a finished executable or library.
255         time(sess, "linking", || {
256             back::link::link_binary(sess, &trans, outputs, &trans.crate_name.as_str());
257         });
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, trans.link.crate_hash);
262
263         Ok(())
264     }
265 }
266
267 /// This is the entrypoint for a hot plugged rustc_trans
268 #[no_mangle]
269 pub fn __rustc_codegen_backend() -> Box<TransCrate> {
270     LlvmTransCrate::new()
271 }
272
273 struct ModuleTranslation {
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     name: String,
280     llmod_id: String,
281     source: ModuleSource,
282     kind: ModuleKind,
283 }
284
285 #[derive(Copy, Clone, Debug, PartialEq)]
286 enum ModuleKind {
287     Regular,
288     Metadata,
289     Allocator,
290 }
291
292 impl ModuleTranslation {
293     fn llvm(&self) -> Option<&ModuleLlvm> {
294         match self.source {
295             ModuleSource::Translated(ref llvm) => Some(llvm),
296             ModuleSource::Preexisting(_) => None,
297         }
298     }
299
300     fn into_compiled_module(self,
301                                 emit_obj: bool,
302                                 emit_bc: bool,
303                                 emit_bc_compressed: bool,
304                                 outputs: &OutputFilenames) -> CompiledModule {
305         let pre_existing = match self.source {
306             ModuleSource::Preexisting(_) => true,
307             ModuleSource::Translated(_) => false,
308         };
309         let object = if emit_obj {
310             Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
311         } else {
312             None
313         };
314         let bytecode = if emit_bc {
315             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
316         } else {
317             None
318         };
319         let bytecode_compressed = if emit_bc_compressed {
320             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
321                     .with_extension(RLIB_BYTECODE_EXTENSION))
322         } else {
323             None
324         };
325
326         CompiledModule {
327             llmod_id: self.llmod_id,
328             name: self.name.clone(),
329             kind: self.kind,
330             pre_existing,
331             object,
332             bytecode,
333             bytecode_compressed,
334         }
335     }
336 }
337
338 #[derive(Debug)]
339 struct CompiledModule {
340     name: String,
341     llmod_id: String,
342     kind: ModuleKind,
343     pre_existing: bool,
344     object: Option<PathBuf>,
345     bytecode: Option<PathBuf>,
346     bytecode_compressed: Option<PathBuf>,
347 }
348
349 enum ModuleSource {
350     /// Copy the `.o` files or whatever from the incr. comp. directory.
351     Preexisting(WorkProduct),
352
353     /// Rebuild from this LLVM module.
354     Translated(ModuleLlvm),
355 }
356
357 #[derive(Debug)]
358 struct ModuleLlvm {
359     llcx: llvm::ContextRef,
360     llmod: llvm::ModuleRef,
361     tm: llvm::TargetMachineRef,
362 }
363
364 unsafe impl Send for ModuleLlvm { }
365 unsafe impl Sync for ModuleLlvm { }
366
367 impl Drop for ModuleLlvm {
368     fn drop(&mut self) {
369         unsafe {
370             llvm::LLVMDisposeModule(self.llmod);
371             llvm::LLVMContextDispose(self.llcx);
372             llvm::LLVMRustDisposeTargetMachine(self.tm);
373         }
374     }
375 }
376
377 struct CrateTranslation {
378     crate_name: Symbol,
379     modules: Vec<CompiledModule>,
380     allocator_module: Option<CompiledModule>,
381     metadata_module: CompiledModule,
382     link: rustc::middle::cstore::LinkMeta,
383     metadata: rustc::middle::cstore::EncodedMetadata,
384     windows_subsystem: Option<String>,
385     linker_info: back::linker::LinkerInfo,
386     crate_info: CrateInfo,
387 }
388
389 // Misc info we load from metadata to persist beyond the tcx
390 struct CrateInfo {
391     panic_runtime: Option<CrateNum>,
392     compiler_builtins: Option<CrateNum>,
393     profiler_runtime: Option<CrateNum>,
394     sanitizer_runtime: Option<CrateNum>,
395     is_no_builtins: FxHashSet<CrateNum>,
396     native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
397     crate_name: FxHashMap<CrateNum, String>,
398     used_libraries: Lrc<Vec<NativeLibrary>>,
399     link_args: Lrc<Vec<String>>,
400     used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
401     used_crates_static: Vec<(CrateNum, LibSource)>,
402     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
403 }
404
405 __build_diagnostic_array! { librustc_trans, DIAGNOSTICS }