]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Merge commit 'dbee13661efa269cb4cd57bb4c6b99a19732b484' into sync_cg_clif-2020-12-27
[rust.git] / src / lib.rs
1 #![feature(
2     rustc_private,
3     decl_macro,
4     type_alias_impl_trait,
5     associated_type_bounds,
6     never_type,
7     try_blocks,
8     hash_drain_filter,
9     str_split_once
10 )]
11 #![warn(rust_2018_idioms)]
12 #![warn(unused_lifetimes)]
13 #![warn(unreachable_pub)]
14
15 #[cfg(feature = "jit")]
16 extern crate libc;
17 extern crate snap;
18 #[macro_use]
19 extern crate rustc_middle;
20 extern crate rustc_ast;
21 extern crate rustc_codegen_ssa;
22 extern crate rustc_data_structures;
23 extern crate rustc_errors;
24 extern crate rustc_fs_util;
25 extern crate rustc_hir;
26 extern crate rustc_incremental;
27 extern crate rustc_index;
28 extern crate rustc_session;
29 extern crate rustc_span;
30 extern crate rustc_symbol_mangling;
31 extern crate rustc_target;
32
33 // This prevents duplicating functions and statics that are already part of the host rustc process.
34 #[allow(unused_extern_crates)]
35 extern crate rustc_driver;
36
37 use std::any::Any;
38 use std::str::FromStr;
39
40 use rustc_codegen_ssa::traits::CodegenBackend;
41 use rustc_codegen_ssa::CodegenResults;
42 use rustc_errors::ErrorReported;
43 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
44 use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoader};
45 use rustc_middle::ty::query::Providers;
46 use rustc_session::config::OutputFilenames;
47 use rustc_session::Session;
48
49 use cranelift_codegen::settings::{self, Configurable};
50
51 use crate::constant::ConstantCx;
52 use crate::prelude::*;
53
54 mod abi;
55 mod allocator;
56 mod analyze;
57 mod archive;
58 mod atomic_shim;
59 mod backend;
60 mod base;
61 mod cast;
62 mod codegen_i128;
63 mod common;
64 mod constant;
65 mod debuginfo;
66 mod discriminant;
67 mod driver;
68 mod inline_asm;
69 mod intrinsics;
70 mod linkage;
71 mod main_shim;
72 mod metadata;
73 mod num;
74 mod optimize;
75 mod pointer;
76 mod pretty_clif;
77 mod toolchain;
78 mod trap;
79 mod unsize;
80 mod value_and_place;
81 mod vtable;
82
83 mod prelude {
84     pub(crate) use std::convert::{TryFrom, TryInto};
85
86     pub(crate) use rustc_ast::ast::{FloatTy, IntTy, UintTy};
87     pub(crate) use rustc_span::Span;
88
89     pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
90     pub(crate) use rustc_middle::bug;
91     pub(crate) use rustc_middle::mir::{self, *};
92     pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
93     pub(crate) use rustc_middle::ty::{
94         self, FnSig, Instance, InstanceDef, ParamEnv, Ty, TyCtxt, TypeAndMut, TypeFoldable,
95     };
96     pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};
97
98     pub(crate) use rustc_data_structures::fx::FxHashMap;
99
100     pub(crate) use rustc_index::vec::Idx;
101
102     pub(crate) use cranelift_codegen::entity::EntitySet;
103     pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
104     pub(crate) use cranelift_codegen::ir::function::Function;
105     pub(crate) use cranelift_codegen::ir::types;
106     pub(crate) use cranelift_codegen::ir::{
107         AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc,
108         StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value,
109     };
110     pub(crate) use cranelift_codegen::isa::{self, CallConv};
111     pub(crate) use cranelift_codegen::Context;
112     pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
113     pub(crate) use cranelift_module::{self, DataContext, DataId, FuncId, Linkage, Module};
114
115     pub(crate) use crate::abi::*;
116     pub(crate) use crate::base::{codegen_operand, codegen_place};
117     pub(crate) use crate::cast::*;
118     pub(crate) use crate::common::*;
119     pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
120     pub(crate) use crate::pointer::Pointer;
121     pub(crate) use crate::trap::*;
122     pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
123 }
124
125 struct PrintOnPanic<F: Fn() -> String>(F);
126 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
127     fn drop(&mut self) {
128         if ::std::thread::panicking() {
129             println!("{}", (self.0)());
130         }
131     }
132 }
133
134 struct CodegenCx<'tcx, M: Module> {
135     tcx: TyCtxt<'tcx>,
136     module: M,
137     global_asm: String,
138     constants_cx: ConstantCx,
139     cached_context: Context,
140     vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
141     debug_context: Option<DebugContext<'tcx>>,
142     unwind_context: UnwindContext<'tcx>,
143 }
144
145 impl<'tcx, M: Module> CodegenCx<'tcx, M> {
146     fn new(tcx: TyCtxt<'tcx>, module: M, debug_info: bool, pic_eh_frame: bool) -> Self {
147         let unwind_context = UnwindContext::new(tcx, module.isa(), pic_eh_frame);
148         let debug_context = if debug_info {
149             Some(DebugContext::new(tcx, module.isa()))
150         } else {
151             None
152         };
153         CodegenCx {
154             tcx,
155             module,
156             global_asm: String::new(),
157             constants_cx: ConstantCx::default(),
158             cached_context: Context::new(),
159             vtables: FxHashMap::default(),
160             debug_context,
161             unwind_context,
162         }
163     }
164
165     fn finalize(mut self) -> (M, String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
166         self.constants_cx.finalize(self.tcx, &mut self.module);
167         (
168             self.module,
169             self.global_asm,
170             self.debug_context,
171             self.unwind_context,
172         )
173     }
174 }
175
176 #[derive(Copy, Clone, Debug)]
177 pub enum CodegenMode {
178     Aot,
179     Jit,
180     JitLazy,
181 }
182
183 impl Default for CodegenMode {
184     fn default() -> Self {
185         CodegenMode::Aot
186     }
187 }
188
189 impl FromStr for CodegenMode {
190     type Err = String;
191
192     fn from_str(s: &str) -> Result<Self, Self::Err> {
193         match s {
194             "aot" => Ok(CodegenMode::Aot),
195             "jit" => Ok(CodegenMode::Jit),
196             "jit-lazy" => Ok(CodegenMode::JitLazy),
197             _ => Err(format!("Unknown codegen mode `{}`", s)),
198         }
199     }
200 }
201
202 #[derive(Copy, Clone, Debug, Default)]
203 pub struct BackendConfig {
204     pub codegen_mode: CodegenMode,
205 }
206
207 impl BackendConfig {
208     fn from_opts(opts: &[String]) -> Result<Self, String> {
209         let mut config = BackendConfig::default();
210         for opt in opts {
211             if let Some((name, value)) = opt.split_once('=') {
212                 match name {
213                     "mode" => config.codegen_mode = value.parse()?,
214                     _ => return Err(format!("Unknown option `{}`", name)),
215                 }
216             } else {
217                 return Err(format!("Invalid option `{}`", opt));
218             }
219         }
220         Ok(config)
221     }
222 }
223
224 pub struct CraneliftCodegenBackend {
225     pub config: Option<BackendConfig>,
226 }
227
228 impl CodegenBackend for CraneliftCodegenBackend {
229     fn init(&self, sess: &Session) {
230         if sess.lto() != rustc_session::config::Lto::No && sess.opts.cg.embed_bitcode {
231             sess.warn("LTO is not supported. You may get a linker error.");
232         }
233     }
234
235     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
236         Box::new(crate::metadata::CraneliftMetadataLoader)
237     }
238
239     fn provide(&self, _providers: &mut Providers) {}
240     fn provide_extern(&self, _providers: &mut Providers) {}
241
242     fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
243         vec![]
244     }
245
246     fn codegen_crate<'tcx>(
247         &self,
248         tcx: TyCtxt<'tcx>,
249         metadata: EncodedMetadata,
250         need_metadata_module: bool,
251     ) -> Box<dyn Any> {
252         let config = if let Some(config) = self.config {
253             config
254         } else {
255             BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
256                 .unwrap_or_else(|err| tcx.sess.fatal(&err))
257         };
258         let res = driver::codegen_crate(tcx, metadata, need_metadata_module, config);
259
260         rustc_symbol_mangling::test::report_symbol_names(tcx);
261
262         res
263     }
264
265     fn join_codegen(
266         &self,
267         ongoing_codegen: Box<dyn Any>,
268         _sess: &Session,
269     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
270         Ok(*ongoing_codegen
271             .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
272             .unwrap())
273     }
274
275     fn link(
276         &self,
277         sess: &Session,
278         codegen_results: CodegenResults,
279         outputs: &OutputFilenames,
280     ) -> Result<(), ErrorReported> {
281         use rustc_codegen_ssa::back::link::link_binary;
282
283         let _timer = sess.prof.generic_activity("link_crate");
284
285         sess.time("linking", || {
286             let target_cpu = crate::target_triple(sess).to_string();
287             link_binary::<crate::archive::ArArchiveBuilder<'_>>(
288                 sess,
289                 &codegen_results,
290                 outputs,
291                 &codegen_results.crate_name.as_str(),
292                 &target_cpu,
293             );
294         });
295
296         Ok(())
297     }
298 }
299
300 fn target_triple(sess: &Session) -> target_lexicon::Triple {
301     sess.target.llvm_target.parse().unwrap()
302 }
303
304 fn build_isa(sess: &Session) -> Box<dyn isa::TargetIsa + 'static> {
305     use target_lexicon::BinaryFormat;
306
307     let target_triple = crate::target_triple(sess);
308
309     let mut flags_builder = settings::builder();
310     flags_builder.enable("is_pic").unwrap();
311     flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
312     flags_builder
313         .set(
314             "enable_verifier",
315             if cfg!(debug_assertions) {
316                 "true"
317             } else {
318                 "false"
319             },
320         )
321         .unwrap();
322
323     let tls_model = match target_triple.binary_format {
324         BinaryFormat::Elf => "elf_gd",
325         BinaryFormat::Macho => "macho",
326         BinaryFormat::Coff => "coff",
327         _ => "none",
328     };
329     flags_builder.set("tls_model", tls_model).unwrap();
330
331     flags_builder.set("enable_simd", "true").unwrap();
332
333     use rustc_session::config::OptLevel;
334     match sess.opts.optimize {
335         OptLevel::No => {
336             flags_builder.set("opt_level", "none").unwrap();
337         }
338         OptLevel::Less | OptLevel::Default => {}
339         OptLevel::Aggressive => {
340             flags_builder.set("opt_level", "speed_and_size").unwrap();
341         }
342         OptLevel::Size | OptLevel::SizeMin => {
343             sess.warn("Optimizing for size is not supported. Just ignoring the request");
344         }
345     }
346
347     let flags = settings::Flags::new(flags_builder);
348
349     let mut isa_builder = cranelift_codegen::isa::lookup(target_triple).unwrap();
350     // Don't use "haswell", as it implies `has_lzcnt`.macOS CI is still at Ivy Bridge EP, so `lzcnt`
351     // is interpreted as `bsr`.
352     isa_builder.enable("nehalem").unwrap();
353     isa_builder.finish(flags)
354 }
355
356 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
357 #[no_mangle]
358 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
359     Box::new(CraneliftCodegenBackend { config: None })
360 }