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;
79 pub(crate) use rustc_span::{FileNameDisplayPreference, Span};
81 pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
82 pub(crate) use rustc_middle::bug;
83 pub(crate) use rustc_middle::mir::{self, *};
84 pub(crate) use rustc_middle::ty::layout::{self, LayoutOf, TyAndLayout};
85 pub(crate) use rustc_middle::ty::{
86 self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
87 TypeFoldable, TypeVisitable, UintTy,
89 pub(crate) use rustc_target::abi::{Abi, Scalar, Size, VariantIdx};
91 pub(crate) use rustc_data_structures::fx::FxHashMap;
93 pub(crate) use rustc_index::vec::Idx;
95 pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
96 pub(crate) use cranelift_codegen::ir::function::Function;
97 pub(crate) use cranelift_codegen::ir::types;
98 pub(crate) use cranelift_codegen::ir::{
99 AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc,
100 StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value,
102 pub(crate) use cranelift_codegen::isa::{self, CallConv};
103 pub(crate) use cranelift_codegen::Context;
104 pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
105 pub(crate) use cranelift_module::{self, DataContext, FuncId, Linkage, Module};
107 pub(crate) use crate::abi::*;
108 pub(crate) use crate::base::{codegen_operand, codegen_place};
109 pub(crate) use crate::cast::*;
110 pub(crate) use crate::common::*;
111 pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
112 pub(crate) use crate::pointer::Pointer;
113 pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
116 struct PrintOnPanic<F: Fn() -> String>(F);
117 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
119 if ::std::thread::panicking() {
120 println!("{}", (self.0)());
125 /// The codegen context holds any information shared between the codegen of individual functions
126 /// inside a single codegen unit with the exception of the Cranelift [`Module`](cranelift_module::Module).
128 profiler: SelfProfilerRef,
129 output_filenames: Arc<OutputFilenames>,
130 should_write_ir: bool,
132 inline_asm_index: Cell<usize>,
133 debug_context: Option<DebugContext>,
134 unwind_context: UnwindContext,
141 backend_config: BackendConfig,
146 assert_eq!(pointer_ty(tcx), isa.pointer_type());
149 UnwindContext::new(isa, matches!(backend_config.codegen_mode, CodegenMode::Aot));
150 let debug_context = if debug_info && !tcx.sess.target.options.is_like_windows {
151 Some(DebugContext::new(tcx, isa))
156 profiler: tcx.prof.clone(),
157 output_filenames: tcx.output_filenames(()).clone(),
158 should_write_ir: crate::pretty_clif::should_write_ir(tcx),
159 global_asm: String::new(),
160 inline_asm_index: Cell::new(0),
168 pub struct CraneliftCodegenBackend {
169 pub config: RefCell<Option<BackendConfig>>,
172 impl CodegenBackend for CraneliftCodegenBackend {
173 fn init(&self, sess: &Session) {
174 use rustc_session::config::Lto;
176 Lto::No | Lto::ThinLocal => {}
177 Lto::Thin | Lto::Fat => sess.warn("LTO is not supported. You may get a linker error."),
180 let mut config = self.config.borrow_mut();
181 if config.is_none() {
182 let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args)
183 .unwrap_or_else(|err| sess.fatal(&err));
184 *config = Some(new_config);
188 fn target_features(&self, _sess: &Session, _allow_unstable: bool) -> Vec<rustc_span::Symbol> {
192 fn print_version(&self) {
193 println!("Cranelift version: {}", cranelift_codegen::VERSION);
199 metadata: EncodedMetadata,
200 need_metadata_module: bool,
202 tcx.sess.abort_if_errors();
203 let config = self.config.borrow().clone().unwrap();
204 match config.codegen_mode {
205 CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module),
206 CodegenMode::Jit | CodegenMode::JitLazy => {
207 #[cfg(feature = "jit")]
208 driver::jit::run_jit(tcx, config);
210 #[cfg(not(feature = "jit"))]
211 tcx.sess.fatal("jit support was disabled when compiling rustc_codegen_cranelift");
218 ongoing_codegen: Box<dyn Any>,
220 _outputs: &OutputFilenames,
221 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorGuaranteed> {
223 .downcast::<driver::aot::OngoingCodegen>()
225 .join(sess, self.config.borrow().as_ref().unwrap()))
231 codegen_results: CodegenResults,
232 outputs: &OutputFilenames,
233 ) -> Result<(), ErrorGuaranteed> {
234 use rustc_codegen_ssa::back::link::link_binary;
236 link_binary(sess, &crate::archive::ArArchiveBuilderBuilder, &codegen_results, outputs)
240 fn target_triple(sess: &Session) -> target_lexicon::Triple {
241 match sess.target.llvm_target.parse() {
242 Ok(triple) => triple,
243 Err(err) => sess.fatal(&format!("target not recognized: {}", err)),
247 fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Box<dyn isa::TargetIsa + 'static> {
248 use target_lexicon::BinaryFormat;
250 let target_triple = crate::target_triple(sess);
252 let mut flags_builder = settings::builder();
253 flags_builder.enable("is_pic").unwrap();
254 flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
255 let enable_verifier = if backend_config.enable_verifier { "true" } else { "false" };
256 flags_builder.set("enable_verifier", enable_verifier).unwrap();
257 flags_builder.set("regalloc_checker", enable_verifier).unwrap();
259 let tls_model = match target_triple.binary_format {
260 BinaryFormat::Elf => "elf_gd",
261 BinaryFormat::Macho => "macho",
262 BinaryFormat::Coff => "coff",
265 flags_builder.set("tls_model", tls_model).unwrap();
267 flags_builder.set("enable_simd", "true").unwrap();
269 flags_builder.set("enable_llvm_abi_extensions", "true").unwrap();
271 use rustc_session::config::OptLevel;
272 match sess.opts.optimize {
274 flags_builder.set("opt_level", "none").unwrap();
276 OptLevel::Less | OptLevel::Default => {}
277 OptLevel::Size | OptLevel::SizeMin | OptLevel::Aggressive => {
278 flags_builder.set("opt_level", "speed_and_size").unwrap();
282 let flags = settings::Flags::new(flags_builder);
284 let isa_builder = match sess.opts.cg.target_cpu.as_deref() {
286 let builder = cranelift_native::builder_with_options(true).unwrap();
291 cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
292 sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
294 if let Err(_) = builder.enable(value) {
295 sess.fatal("the specified target cpu isn't currently supported by Cranelift.");
301 cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
302 sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
304 if target_triple.architecture == target_lexicon::Architecture::X86_64 {
305 // Don't use "haswell" as the default, as it implies `has_lzcnt`.
306 // macOS CI is still at Ivy Bridge EP, so `lzcnt` is interpreted as `bsr`.
307 builder.enable("nehalem").unwrap();
313 match isa_builder.finish(flags) {
314 Ok(target_isa) => target_isa,
315 Err(err) => sess.fatal(&format!("failed to build TargetIsa: {}", err)),
319 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
321 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
322 Box::new(CraneliftCodegenBackend { config: RefCell::new(None) })