]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/lib.rs
Rollup merge of #86811 - soerenmeier:remove_remaining, r=yaahc
[rust.git] / compiler / rustc_codegen_cranelift / src / lib.rs
1 #![feature(rustc_private, decl_macro, never_type, hash_drain_filter, vec_into_raw_parts, once_cell)]
2 #![warn(rust_2018_idioms)]
3 #![warn(unused_lifetimes)]
4 #![warn(unreachable_pub)]
5
6 extern crate snap;
7 #[macro_use]
8 extern crate rustc_middle;
9 extern crate rustc_ast;
10 extern crate rustc_codegen_ssa;
11 extern crate rustc_data_structures;
12 extern crate rustc_errors;
13 extern crate rustc_fs_util;
14 extern crate rustc_hir;
15 extern crate rustc_incremental;
16 extern crate rustc_index;
17 extern crate rustc_interface;
18 extern crate rustc_metadata;
19 extern crate rustc_mir;
20 extern crate rustc_session;
21 extern crate rustc_span;
22 extern crate rustc_target;
23
24 // This prevents duplicating functions and statics that are already part of the host rustc process.
25 #[allow(unused_extern_crates)]
26 extern crate rustc_driver;
27
28 use std::any::Any;
29
30 use rustc_codegen_ssa::traits::CodegenBackend;
31 use rustc_codegen_ssa::CodegenResults;
32 use rustc_errors::ErrorReported;
33 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
34 use rustc_middle::middle::cstore::EncodedMetadata;
35 use rustc_session::config::OutputFilenames;
36 use rustc_session::Session;
37
38 use cranelift_codegen::isa::TargetIsa;
39 use cranelift_codegen::settings::{self, Configurable};
40
41 pub use crate::config::*;
42 use crate::prelude::*;
43
44 mod abi;
45 mod allocator;
46 mod analyze;
47 mod archive;
48 mod backend;
49 mod base;
50 mod cast;
51 mod codegen_i128;
52 mod common;
53 mod compiler_builtins;
54 mod config;
55 mod constant;
56 mod debuginfo;
57 mod discriminant;
58 mod driver;
59 mod inline_asm;
60 mod intrinsics;
61 mod linkage;
62 mod main_shim;
63 mod metadata;
64 mod num;
65 mod optimize;
66 mod pointer;
67 mod pretty_clif;
68 mod toolchain;
69 mod trap;
70 mod unsize;
71 mod value_and_place;
72 mod vtable;
73
74 mod prelude {
75     pub(crate) use std::convert::{TryFrom, TryInto};
76
77     pub(crate) use rustc_span::Span;
78
79     pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
80     pub(crate) use rustc_middle::bug;
81     pub(crate) use rustc_middle::mir::{self, *};
82     pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
83     pub(crate) use rustc_middle::ty::{
84         self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
85         TypeFoldable, UintTy,
86     };
87     pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};
88
89     pub(crate) use rustc_data_structures::fx::FxHashMap;
90
91     pub(crate) use rustc_index::vec::Idx;
92
93     pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
94     pub(crate) use cranelift_codegen::ir::function::Function;
95     pub(crate) use cranelift_codegen::ir::types;
96     pub(crate) use cranelift_codegen::ir::{
97         AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc,
98         StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value,
99     };
100     pub(crate) use cranelift_codegen::isa::{self, CallConv};
101     pub(crate) use cranelift_codegen::Context;
102     pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
103     pub(crate) use cranelift_module::{self, DataContext, FuncId, Linkage, Module};
104
105     pub(crate) use crate::abi::*;
106     pub(crate) use crate::base::{codegen_operand, codegen_place};
107     pub(crate) use crate::cast::*;
108     pub(crate) use crate::common::*;
109     pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
110     pub(crate) use crate::pointer::Pointer;
111     pub(crate) use crate::trap::*;
112     pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
113 }
114
115 struct PrintOnPanic<F: Fn() -> String>(F);
116 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
117     fn drop(&mut self) {
118         if ::std::thread::panicking() {
119             println!("{}", (self.0)());
120         }
121     }
122 }
123
124 /// The codegen context holds any information shared between the codegen of individual functions
125 /// inside a single codegen unit with the exception of the Cranelift [`Module`](cranelift_module::Module).
126 struct CodegenCx<'tcx> {
127     tcx: TyCtxt<'tcx>,
128     global_asm: String,
129     cached_context: Context,
130     debug_context: Option<DebugContext<'tcx>>,
131     unwind_context: UnwindContext,
132 }
133
134 impl<'tcx> CodegenCx<'tcx> {
135     fn new(
136         tcx: TyCtxt<'tcx>,
137         backend_config: BackendConfig,
138         isa: &dyn TargetIsa,
139         debug_info: bool,
140     ) -> Self {
141         assert_eq!(pointer_ty(tcx), isa.pointer_type());
142
143         let unwind_context =
144             UnwindContext::new(tcx, isa, matches!(backend_config.codegen_mode, CodegenMode::Aot));
145         let debug_context = if debug_info { Some(DebugContext::new(tcx, isa)) } else { None };
146         CodegenCx {
147             tcx,
148             global_asm: String::new(),
149             cached_context: Context::new(),
150             debug_context,
151             unwind_context,
152         }
153     }
154 }
155
156 pub struct CraneliftCodegenBackend {
157     pub config: Option<BackendConfig>,
158 }
159
160 impl CodegenBackend for CraneliftCodegenBackend {
161     fn init(&self, sess: &Session) {
162         use rustc_session::config::Lto;
163         match sess.lto() {
164             Lto::No | Lto::ThinLocal => {}
165             Lto::Thin | Lto::Fat => sess.warn("LTO is not supported. You may get a linker error."),
166         }
167     }
168
169     fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
170         vec![]
171     }
172
173     fn print_version(&self) {
174         println!("Cranelift version: {}", cranelift_codegen::VERSION);
175     }
176
177     fn codegen_crate(
178         &self,
179         tcx: TyCtxt<'_>,
180         metadata: EncodedMetadata,
181         need_metadata_module: bool,
182     ) -> Box<dyn Any> {
183         tcx.sess.abort_if_errors();
184         let config = if let Some(config) = self.config.clone() {
185             config
186         } else {
187             BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
188                 .unwrap_or_else(|err| tcx.sess.fatal(&err))
189         };
190         match config.codegen_mode {
191             CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module),
192             CodegenMode::Jit | CodegenMode::JitLazy => {
193                 #[cfg(feature = "jit")]
194                 let _: ! = driver::jit::run_jit(tcx, config);
195
196                 #[cfg(not(feature = "jit"))]
197                 tcx.sess.fatal("jit support was disabled when compiling rustc_codegen_cranelift");
198             }
199         }
200     }
201
202     fn join_codegen(
203         &self,
204         ongoing_codegen: Box<dyn Any>,
205         _sess: &Session,
206     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
207         Ok(*ongoing_codegen
208             .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
209             .unwrap())
210     }
211
212     fn link(
213         &self,
214         sess: &Session,
215         codegen_results: CodegenResults,
216         outputs: &OutputFilenames,
217     ) -> Result<(), ErrorReported> {
218         use rustc_codegen_ssa::back::link::link_binary;
219
220         link_binary::<crate::archive::ArArchiveBuilder<'_>>(
221             sess,
222             &codegen_results,
223             outputs,
224         );
225
226         Ok(())
227     }
228 }
229
230 fn target_triple(sess: &Session) -> target_lexicon::Triple {
231     sess.target.llvm_target.parse().unwrap()
232 }
233
234 fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Box<dyn isa::TargetIsa + 'static> {
235     use target_lexicon::BinaryFormat;
236
237     let target_triple = crate::target_triple(sess);
238
239     let mut flags_builder = settings::builder();
240     flags_builder.enable("is_pic").unwrap();
241     flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
242     let enable_verifier = if backend_config.enable_verifier { "true" } else { "false" };
243     flags_builder.set("enable_verifier", enable_verifier).unwrap();
244
245     let tls_model = match target_triple.binary_format {
246         BinaryFormat::Elf => "elf_gd",
247         BinaryFormat::Macho => "macho",
248         BinaryFormat::Coff => "coff",
249         _ => "none",
250     };
251     flags_builder.set("tls_model", tls_model).unwrap();
252
253     flags_builder.set("enable_simd", "true").unwrap();
254
255     flags_builder.set("enable_llvm_abi_extensions", "true").unwrap();
256
257     flags_builder.set("regalloc", &backend_config.regalloc).unwrap();
258
259     use rustc_session::config::OptLevel;
260     match sess.opts.optimize {
261         OptLevel::No => {
262             flags_builder.set("opt_level", "none").unwrap();
263         }
264         OptLevel::Less | OptLevel::Default => {}
265         OptLevel::Size | OptLevel::SizeMin | OptLevel::Aggressive => {
266             flags_builder.set("opt_level", "speed_and_size").unwrap();
267         }
268     }
269
270     let flags = settings::Flags::new(flags_builder);
271
272     let variant = cranelift_codegen::isa::BackendVariant::MachInst;
273
274     let isa_builder = match sess.opts.cg.target_cpu.as_deref() {
275         Some("native") => {
276             let builder = cranelift_native::builder_with_options(variant, true).unwrap();
277             builder
278         }
279         Some(value) => {
280             let mut builder =
281                 cranelift_codegen::isa::lookup_variant(target_triple, variant).unwrap();
282             if let Err(_) = builder.enable(value) {
283                 sess.fatal("The specified target cpu isn't currently supported by Cranelift.");
284             }
285             builder
286         }
287         None => {
288             let mut builder =
289                 cranelift_codegen::isa::lookup_variant(target_triple.clone(), variant).unwrap();
290             if target_triple.architecture == target_lexicon::Architecture::X86_64 {
291                 // Don't use "haswell" as the default, as it implies `has_lzcnt`.
292                 // macOS CI is still at Ivy Bridge EP, so `lzcnt` is interpreted as `bsr`.
293                 builder.enable("nehalem").unwrap();
294             }
295             builder
296         }
297     };
298
299     isa_builder.finish(flags)
300 }
301
302 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
303 #[no_mangle]
304 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
305     Box::new(CraneliftCodegenBackend { config: None })
306 }