1 #![feature(rustc_private)]
2 // Note: please avoid adding other feature gates where possible
3 #![warn(rust_2018_idioms)]
4 #![warn(unused_lifetimes)]
5 #![warn(unreachable_pub)]
7 extern crate jobserver;
9 extern crate rustc_middle;
10 extern crate rustc_ast;
11 extern crate rustc_codegen_ssa;
12 extern crate rustc_data_structures;
13 extern crate rustc_errors;
14 extern crate rustc_fs_util;
15 extern crate rustc_hir;
16 extern crate rustc_incremental;
17 extern crate rustc_index;
18 extern crate rustc_interface;
19 extern crate rustc_metadata;
20 extern crate rustc_session;
21 extern crate rustc_span;
22 extern crate rustc_target;
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;
29 use std::cell::{Cell, RefCell};
32 use rustc_codegen_ssa::traits::CodegenBackend;
33 use rustc_codegen_ssa::CodegenResults;
34 use rustc_data_structures::profiling::SelfProfilerRef;
35 use rustc_errors::ErrorGuaranteed;
36 use rustc_metadata::EncodedMetadata;
37 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
38 use rustc_session::config::OutputFilenames;
39 use rustc_session::Session;
40 use rustc_span::Symbol;
42 use cranelift_codegen::isa::TargetIsa;
43 use cranelift_codegen::settings::{self, Configurable};
45 pub use crate::config::*;
46 use crate::prelude::*;
56 mod compiler_builtins;
57 mod concurrency_limiter;
60 // FIXME revert back to the external crate with Cranelift 0.93
81 pub(crate) use rustc_span::{FileNameDisplayPreference, Span};
83 pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
84 pub(crate) use rustc_middle::bug;
85 pub(crate) use rustc_middle::mir::{self, *};
86 pub(crate) use rustc_middle::ty::layout::{self, LayoutOf, TyAndLayout};
87 pub(crate) use rustc_middle::ty::{
88 self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
89 TypeFoldable, TypeVisitable, UintTy,
91 pub(crate) use rustc_target::abi::{Abi, Scalar, Size, VariantIdx};
93 pub(crate) use rustc_data_structures::fx::FxHashMap;
95 pub(crate) use rustc_index::vec::Idx;
97 pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
98 pub(crate) use cranelift_codegen::ir::function::Function;
99 pub(crate) use cranelift_codegen::ir::types;
100 pub(crate) use cranelift_codegen::ir::{
101 AbiParam, Block, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc, StackSlot,
102 StackSlotData, StackSlotKind, TrapCode, Type, Value,
104 pub(crate) use cranelift_codegen::isa::{self, CallConv};
105 pub(crate) use cranelift_codegen::Context;
106 pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
107 pub(crate) use cranelift_module::{self, DataContext, FuncId, Linkage, Module};
109 pub(crate) use crate::abi::*;
110 pub(crate) use crate::base::{codegen_operand, codegen_place};
111 pub(crate) use crate::cast::*;
112 pub(crate) use crate::common::*;
113 pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
114 pub(crate) use crate::pointer::Pointer;
115 pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
118 struct PrintOnPanic<F: Fn() -> String>(F);
119 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
121 if ::std::thread::panicking() {
122 println!("{}", (self.0)());
127 /// The codegen context holds any information shared between the codegen of individual functions
128 /// inside a single codegen unit with the exception of the Cranelift [`Module`](cranelift_module::Module).
130 profiler: SelfProfilerRef,
131 output_filenames: Arc<OutputFilenames>,
132 should_write_ir: bool,
134 inline_asm_index: Cell<usize>,
135 debug_context: Option<DebugContext>,
136 unwind_context: UnwindContext,
143 backend_config: BackendConfig,
148 assert_eq!(pointer_ty(tcx), isa.pointer_type());
151 UnwindContext::new(isa, matches!(backend_config.codegen_mode, CodegenMode::Aot));
152 let debug_context = if debug_info && !tcx.sess.target.options.is_like_windows {
153 Some(DebugContext::new(tcx, isa))
158 profiler: tcx.prof.clone(),
159 output_filenames: tcx.output_filenames(()).clone(),
160 should_write_ir: crate::pretty_clif::should_write_ir(tcx),
161 global_asm: String::new(),
162 inline_asm_index: Cell::new(0),
170 pub struct CraneliftCodegenBackend {
171 pub config: RefCell<Option<BackendConfig>>,
174 impl CodegenBackend for CraneliftCodegenBackend {
175 fn init(&self, sess: &Session) {
176 use rustc_session::config::Lto;
178 Lto::No | Lto::ThinLocal => {}
179 Lto::Thin | Lto::Fat => sess.warn("LTO is not supported. You may get a linker error."),
182 let mut config = self.config.borrow_mut();
183 if config.is_none() {
184 let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args)
185 .unwrap_or_else(|err| sess.fatal(&err));
186 *config = Some(new_config);
190 fn target_features(&self, _sess: &Session, _allow_unstable: bool) -> Vec<rustc_span::Symbol> {
194 fn print_version(&self) {
195 println!("Cranelift version: {}", cranelift_codegen::VERSION);
201 metadata: EncodedMetadata,
202 need_metadata_module: bool,
204 tcx.sess.abort_if_errors();
205 let config = self.config.borrow().clone().unwrap();
206 match config.codegen_mode {
207 CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module),
208 CodegenMode::Jit | CodegenMode::JitLazy => {
209 #[cfg(feature = "jit")]
210 driver::jit::run_jit(tcx, config);
212 #[cfg(not(feature = "jit"))]
213 tcx.sess.fatal("jit support was disabled when compiling rustc_codegen_cranelift");
220 ongoing_codegen: Box<dyn Any>,
222 _outputs: &OutputFilenames,
223 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
225 .downcast::<driver::aot::OngoingCodegen>()
227 .join(sess, self.config.borrow().as_ref().unwrap()))
233 codegen_results: CodegenResults,
234 outputs: &OutputFilenames,
235 ) -> Result<(), ErrorGuaranteed> {
236 use rustc_codegen_ssa::back::link::link_binary;
238 link_binary(sess, &crate::archive::ArArchiveBuilderBuilder, &codegen_results, outputs)
242 fn target_triple(sess: &Session) -> target_lexicon::Triple {
243 match sess.target.llvm_target.parse() {
244 Ok(triple) => triple,
245 Err(err) => sess.fatal(&format!("target not recognized: {}", err)),
249 fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Box<dyn isa::TargetIsa + 'static> {
250 use target_lexicon::BinaryFormat;
252 let target_triple = crate::target_triple(sess);
254 let mut flags_builder = settings::builder();
255 flags_builder.enable("is_pic").unwrap();
256 let enable_verifier = if backend_config.enable_verifier { "true" } else { "false" };
257 flags_builder.set("enable_verifier", enable_verifier).unwrap();
258 flags_builder.set("regalloc_checker", enable_verifier).unwrap();
260 let tls_model = match target_triple.binary_format {
261 BinaryFormat::Elf => "elf_gd",
262 BinaryFormat::Macho => "macho",
263 BinaryFormat::Coff => "coff",
266 flags_builder.set("tls_model", tls_model).unwrap();
268 flags_builder.set("enable_simd", "true").unwrap();
270 flags_builder.set("enable_llvm_abi_extensions", "true").unwrap();
272 use rustc_session::config::OptLevel;
273 match sess.opts.optimize {
275 flags_builder.set("opt_level", "none").unwrap();
277 OptLevel::Less | OptLevel::Default => {}
278 OptLevel::Size | OptLevel::SizeMin | OptLevel::Aggressive => {
279 flags_builder.set("opt_level", "speed_and_size").unwrap();
283 if let target_lexicon::Architecture::Aarch64(_) | target_lexicon::Architecture::X86_64 =
284 target_triple.architecture
286 // Windows depends on stack probes to grow the committed part of the stack
287 flags_builder.enable("enable_probestack").unwrap();
288 flags_builder.set("probestack_strategy", "inline").unwrap();
290 // __cranelift_probestack is not provided and inline stack probes are only supported on AArch64 and x86_64
291 flags_builder.set("enable_probestack", "false").unwrap();
294 let flags = settings::Flags::new(flags_builder);
296 let isa_builder = match sess.opts.cg.target_cpu.as_deref() {
298 let builder = cranelift_native::builder_with_options(true).unwrap();
303 cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
304 sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
306 if let Err(_) = builder.enable(value) {
307 sess.fatal("the specified target cpu isn't currently supported by Cranelift.");
313 cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
314 sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
316 if target_triple.architecture == target_lexicon::Architecture::X86_64 {
317 // Don't use "haswell" as the default, as it implies `has_lzcnt`.
318 // macOS CI is still at Ivy Bridge EP, so `lzcnt` is interpreted as `bsr`.
319 builder.enable("nehalem").unwrap();
325 match isa_builder.finish(flags) {
326 Ok(target_isa) => target_isa,
327 Err(err) => sess.fatal(&format!("failed to build TargetIsa: {}", err)),
331 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
333 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
334 Box::new(CraneliftCodegenBackend { config: RefCell::new(None) })