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