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