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