5 associated_type_bounds,
11 #![warn(rust_2018_idioms)]
12 #![warn(unused_lifetimes)]
13 #![warn(unreachable_pub)]
15 #[cfg(feature = "jit")]
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;
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;
38 use std::str::FromStr;
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;
49 use cranelift_codegen::settings::{self, Configurable};
51 use crate::constant::ConstantCx;
52 use crate::prelude::*;
84 pub(crate) use std::convert::{TryFrom, TryInto};
86 pub(crate) use rustc_span::Span;
88 pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
89 pub(crate) use rustc_middle::bug;
90 pub(crate) use rustc_middle::mir::{self, *};
91 pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
92 pub(crate) use rustc_middle::ty::{
93 self, FloatTy, FnSig, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut, TypeFoldable, UintTy,
95 pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};
97 pub(crate) use rustc_data_structures::fx::FxHashMap;
99 pub(crate) use rustc_index::vec::Idx;
101 pub(crate) use cranelift_codegen::entity::EntitySet;
102 pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
103 pub(crate) use cranelift_codegen::ir::function::Function;
104 pub(crate) use cranelift_codegen::ir::types;
105 pub(crate) use cranelift_codegen::ir::{
106 AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc,
107 StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value,
109 pub(crate) use cranelift_codegen::isa::{self, CallConv};
110 pub(crate) use cranelift_codegen::Context;
111 pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
112 pub(crate) use cranelift_module::{self, DataContext, DataId, FuncId, Linkage, Module};
114 pub(crate) use crate::abi::*;
115 pub(crate) use crate::base::{codegen_operand, codegen_place};
116 pub(crate) use crate::cast::*;
117 pub(crate) use crate::common::*;
118 pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
119 pub(crate) use crate::pointer::Pointer;
120 pub(crate) use crate::trap::*;
121 pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
124 struct PrintOnPanic<F: Fn() -> String>(F);
125 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
127 if ::std::thread::panicking() {
128 println!("{}", (self.0)());
133 struct CodegenCx<'tcx, M: Module> {
137 constants_cx: ConstantCx,
138 cached_context: Context,
139 vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
140 debug_context: Option<DebugContext<'tcx>>,
141 unwind_context: UnwindContext<'tcx>,
144 impl<'tcx, M: Module> CodegenCx<'tcx, M> {
145 fn new(tcx: TyCtxt<'tcx>, module: M, debug_info: bool, pic_eh_frame: bool) -> Self {
146 let unwind_context = UnwindContext::new(tcx, module.isa(), pic_eh_frame);
147 let debug_context = if debug_info {
148 Some(DebugContext::new(tcx, module.isa()))
155 global_asm: String::new(),
156 constants_cx: ConstantCx::default(),
157 cached_context: Context::new(),
158 vtables: FxHashMap::default(),
164 fn finalize(mut self) -> (M, String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
165 self.constants_cx.finalize(self.tcx, &mut self.module);
175 #[derive(Copy, Clone, Debug)]
176 pub enum CodegenMode {
182 impl Default for CodegenMode {
183 fn default() -> Self {
188 impl FromStr for CodegenMode {
191 fn from_str(s: &str) -> Result<Self, Self::Err> {
193 "aot" => Ok(CodegenMode::Aot),
194 "jit" => Ok(CodegenMode::Jit),
195 "jit-lazy" => Ok(CodegenMode::JitLazy),
196 _ => Err(format!("Unknown codegen mode `{}`", s)),
201 #[derive(Copy, Clone, Debug, Default)]
202 pub struct BackendConfig {
203 pub codegen_mode: CodegenMode,
207 fn from_opts(opts: &[String]) -> Result<Self, String> {
208 let mut config = BackendConfig::default();
210 if let Some((name, value)) = opt.split_once('=') {
212 "mode" => config.codegen_mode = value.parse()?,
213 _ => return Err(format!("Unknown option `{}`", name)),
216 return Err(format!("Invalid option `{}`", opt));
223 pub struct CraneliftCodegenBackend {
224 pub config: Option<BackendConfig>,
227 impl CodegenBackend for CraneliftCodegenBackend {
228 fn init(&self, sess: &Session) {
229 if sess.lto() != rustc_session::config::Lto::No && sess.opts.cg.embed_bitcode {
230 sess.warn("LTO is not supported. You may get a linker error.");
234 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
235 Box::new(crate::metadata::CraneliftMetadataLoader)
238 fn provide(&self, _providers: &mut Providers) {}
239 fn provide_extern(&self, _providers: &mut Providers) {}
241 fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
245 fn codegen_crate<'tcx>(
248 metadata: EncodedMetadata,
249 need_metadata_module: bool,
251 let config = if let Some(config) = self.config {
254 BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
255 .unwrap_or_else(|err| tcx.sess.fatal(&err))
257 let res = driver::codegen_crate(tcx, metadata, need_metadata_module, config);
259 rustc_symbol_mangling::test::report_symbol_names(tcx);
266 ongoing_codegen: Box<dyn Any>,
268 ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
270 .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
277 codegen_results: CodegenResults,
278 outputs: &OutputFilenames,
279 ) -> Result<(), ErrorReported> {
280 use rustc_codegen_ssa::back::link::link_binary;
282 let _timer = sess.prof.generic_activity("link_crate");
284 sess.time("linking", || {
285 let target_cpu = crate::target_triple(sess).to_string();
286 link_binary::<crate::archive::ArArchiveBuilder<'_>>(
290 &codegen_results.crate_name.as_str(),
299 fn target_triple(sess: &Session) -> target_lexicon::Triple {
300 sess.target.llvm_target.parse().unwrap()
303 fn build_isa(sess: &Session) -> Box<dyn isa::TargetIsa + 'static> {
304 use target_lexicon::BinaryFormat;
306 let target_triple = crate::target_triple(sess);
308 let mut flags_builder = settings::builder();
309 flags_builder.enable("is_pic").unwrap();
310 flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
314 if cfg!(debug_assertions) {
322 let tls_model = match target_triple.binary_format {
323 BinaryFormat::Elf => "elf_gd",
324 BinaryFormat::Macho => "macho",
325 BinaryFormat::Coff => "coff",
328 flags_builder.set("tls_model", tls_model).unwrap();
330 flags_builder.set("enable_simd", "true").unwrap();
332 use rustc_session::config::OptLevel;
333 match sess.opts.optimize {
335 flags_builder.set("opt_level", "none").unwrap();
337 OptLevel::Less | OptLevel::Default => {}
338 OptLevel::Aggressive => {
339 flags_builder.set("opt_level", "speed_and_size").unwrap();
341 OptLevel::Size | OptLevel::SizeMin => {
342 sess.warn("Optimizing for size is not supported. Just ignoring the request");
346 let flags = settings::Flags::new(flags_builder);
348 let mut isa_builder = cranelift_codegen::isa::lookup(target_triple).unwrap();
349 // Don't use "haswell", as it implies `has_lzcnt`.macOS CI is still at Ivy Bridge EP, so `lzcnt`
350 // is interpreted as `bsr`.
351 isa_builder.enable("nehalem").unwrap();
352 isa_builder.finish(flags)
355 /// This is the entrypoint for a hot plugged rustc_codegen_cranelift
357 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
358 Box::new(CraneliftCodegenBackend { config: None })