]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Rollup merge of #90796 - Amanieu:remove_reg_thumb, r=joshtriplett
[rust.git] / src / lib.rs
1 /*
2  * TODO(antoyo): support #[inline] attributes.
3  * TODO(antoyo): support LTO.
4  *
5  * TODO(antoyo): remove the patches.
6  */
7
8 #![feature(rustc_private, decl_macro, associated_type_bounds, never_type, trusted_len)]
9 #![allow(broken_intra_doc_links)]
10 #![recursion_limit="256"]
11 #![warn(rust_2018_idioms)]
12 #![warn(unused_lifetimes)]
13
14 extern crate rustc_ast;
15 extern crate rustc_codegen_ssa;
16 extern crate rustc_data_structures;
17 extern crate rustc_errors;
18 extern crate rustc_hir;
19 extern crate rustc_metadata;
20 extern crate rustc_middle;
21 extern crate rustc_session;
22 extern crate rustc_span;
23 extern crate rustc_symbol_mangling;
24 extern crate rustc_target;
25
26 // This prevents duplicating functions and statics that are already part of the host rustc process.
27 #[allow(unused_extern_crates)]
28 extern crate rustc_driver;
29
30 mod abi;
31 mod allocator;
32 mod archive;
33 mod asm;
34 mod back;
35 mod base;
36 mod builder;
37 mod callee;
38 mod common;
39 mod consts;
40 mod context;
41 mod coverageinfo;
42 mod debuginfo;
43 mod declare;
44 mod intrinsic;
45 mod mono_item;
46 mod type_;
47 mod type_of;
48
49 use std::any::Any;
50 use std::sync::Arc;
51
52 use gccjit::{Context, OptimizationLevel};
53 use rustc_ast::expand::allocator::AllocatorKind;
54 use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen};
55 use rustc_codegen_ssa::base::codegen_crate;
56 use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryFn};
57 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
58 use rustc_codegen_ssa::target_features::supported_target_features;
59 use rustc_codegen_ssa::traits::{CodegenBackend, ExtraBackendMethods, ModuleBufferMethods, ThinBufferMethods, WriteBackendMethods};
60 use rustc_data_structures::fx::FxHashMap;
61 use rustc_errors::{ErrorReported, Handler};
62 use rustc_metadata::EncodedMetadata;
63 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
64 use rustc_middle::ty::TyCtxt;
65 use rustc_session::config::{Lto, OptLevel, OutputFilenames};
66 use rustc_session::Session;
67 use rustc_span::Symbol;
68 use rustc_span::fatal_error::FatalError;
69
70 pub struct PrintOnPanic<F: Fn() -> String>(pub F);
71
72 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
73     fn drop(&mut self) {
74         if ::std::thread::panicking() {
75             println!("{}", (self.0)());
76         }
77     }
78 }
79
80 #[derive(Clone)]
81 pub struct GccCodegenBackend;
82
83 impl CodegenBackend for GccCodegenBackend {
84     fn init(&self, sess: &Session) {
85         if sess.lto() != Lto::No {
86             sess.warn("LTO is not supported. You may get a linker error.");
87         }
88     }
89
90     fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>, metadata: EncodedMetadata, need_metadata_module: bool) -> Box<dyn Any> {
91         let target_cpu = target_cpu(tcx.sess);
92         let res = codegen_crate(self.clone(), tcx, target_cpu.to_string(), metadata, need_metadata_module);
93
94         rustc_symbol_mangling::test::report_symbol_names(tcx);
95
96         Box::new(res)
97     }
98
99     fn join_codegen(&self, ongoing_codegen: Box<dyn Any>, sess: &Session) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
100         let (codegen_results, work_products) = ongoing_codegen
101             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<GccCodegenBackend>>()
102             .expect("Expected GccCodegenBackend's OngoingCodegen, found Box<Any>")
103             .join(sess);
104
105         Ok((codegen_results, work_products))
106     }
107
108     fn link(&self, sess: &Session, codegen_results: CodegenResults, outputs: &OutputFilenames) -> Result<(), ErrorReported> {
109         use rustc_codegen_ssa::back::link::link_binary;
110
111         link_binary::<crate::archive::ArArchiveBuilder<'_>>(
112             sess,
113             &codegen_results,
114             outputs,
115         )
116     }
117
118     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
119         target_features(sess)
120     }
121 }
122
123 impl ExtraBackendMethods for GccCodegenBackend {
124     fn new_metadata<'tcx>(&self, _tcx: TyCtxt<'tcx>, _mod_name: &str) -> Self::Module {
125         GccContext {
126             context: Context::default(),
127         }
128     }
129
130     fn codegen_allocator<'tcx>(&self, tcx: TyCtxt<'tcx>, mods: &mut Self::Module, module_name: &str, kind: AllocatorKind, has_alloc_error_handler: bool) {
131         unsafe { allocator::codegen(tcx, mods, module_name, kind, has_alloc_error_handler) }
132     }
133
134     fn compile_codegen_unit<'tcx>(&self, tcx: TyCtxt<'tcx>, cgu_name: Symbol) -> (ModuleCodegen<Self::Module>, u64) {
135         base::compile_codegen_unit(tcx, cgu_name)
136     }
137
138     fn target_machine_factory(&self, _sess: &Session, _opt_level: OptLevel) -> TargetMachineFactoryFn<Self> {
139         // TODO(antoyo): set opt level.
140         Arc::new(|_| {
141             Ok(())
142         })
143     }
144
145     fn target_cpu<'b>(&self, _sess: &'b Session) -> &'b str {
146         unimplemented!();
147     }
148
149     fn tune_cpu<'b>(&self, _sess: &'b Session) -> Option<&'b str> {
150         None
151         // TODO(antoyo)
152     }
153 }
154
155 pub struct ModuleBuffer;
156
157 impl ModuleBufferMethods for ModuleBuffer {
158     fn data(&self) -> &[u8] {
159         unimplemented!();
160     }
161 }
162
163 pub struct ThinBuffer;
164
165 impl ThinBufferMethods for ThinBuffer {
166     fn data(&self) -> &[u8] {
167         unimplemented!();
168     }
169 }
170
171 pub struct GccContext {
172     context: Context<'static>,
173 }
174
175 unsafe impl Send for GccContext {}
176 // FIXME(antoyo): that shouldn't be Sync. Parallel compilation is currently disabled with "-Zno-parallel-llvm". Try to disable it here.
177 unsafe impl Sync for GccContext {}
178
179 impl WriteBackendMethods for GccCodegenBackend {
180     type Module = GccContext;
181     type TargetMachine = ();
182     type ModuleBuffer = ModuleBuffer;
183     type Context = ();
184     type ThinData = ();
185     type ThinBuffer = ThinBuffer;
186
187     fn run_fat_lto(_cgcx: &CodegenContext<Self>, mut modules: Vec<FatLTOInput<Self>>, _cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>) -> Result<LtoModuleCodegen<Self>, FatalError> {
188         // TODO(antoyo): implement LTO by sending -flto to libgccjit and adding the appropriate gcc linker plugins.
189         // NOTE: implemented elsewhere.
190         // TODO: what is implemented elsewhere ^ ?
191         let module =
192             match modules.remove(0) {
193                 FatLTOInput::InMemory(module) => module,
194                 FatLTOInput::Serialized { .. } => {
195                     unimplemented!();
196                 }
197             };
198         Ok(LtoModuleCodegen::Fat { module: Some(module), _serialized_bitcode: vec![] })
199     }
200
201     fn run_thin_lto(_cgcx: &CodegenContext<Self>, _modules: Vec<(String, Self::ThinBuffer)>, _cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
202         unimplemented!();
203     }
204
205     fn print_pass_timings(&self) {
206         unimplemented!();
207     }
208
209     unsafe fn optimize(_cgcx: &CodegenContext<Self>, _diag_handler: &Handler, module: &ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<(), FatalError> {
210         module.module_llvm.context.set_optimization_level(to_gcc_opt_level(config.opt_level));
211         Ok(())
212     }
213
214     unsafe fn optimize_thin(_cgcx: &CodegenContext<Self>, _thin: &mut ThinModule<Self>) -> Result<ModuleCodegen<Self::Module>, FatalError> {
215         unimplemented!();
216     }
217
218     unsafe fn codegen(cgcx: &CodegenContext<Self>, diag_handler: &Handler, module: ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<CompiledModule, FatalError> {
219         back::write::codegen(cgcx, diag_handler, module, config)
220     }
221
222     fn prepare_thin(_module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
223         unimplemented!();
224     }
225
226     fn serialize_module(_module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
227         unimplemented!();
228     }
229
230     fn run_lto_pass_manager(_cgcx: &CodegenContext<Self>, _module: &ModuleCodegen<Self::Module>, _config: &ModuleConfig, _thin: bool) -> Result<(), FatalError> {
231         // TODO(antoyo)
232         Ok(())
233     }
234
235     fn run_link(cgcx: &CodegenContext<Self>, diag_handler: &Handler, modules: Vec<ModuleCodegen<Self::Module>>) -> Result<ModuleCodegen<Self::Module>, FatalError> {
236         back::write::link(cgcx, diag_handler, modules)
237     }
238 }
239
240 /// This is the entrypoint for a hot plugged rustc_codegen_gccjit
241 #[no_mangle]
242 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
243     Box::new(GccCodegenBackend)
244 }
245
246 fn to_gcc_opt_level(optlevel: Option<OptLevel>) -> OptimizationLevel {
247     match optlevel {
248         None => OptimizationLevel::None,
249         Some(level) => {
250             match level {
251                 OptLevel::No => OptimizationLevel::None,
252                 OptLevel::Less => OptimizationLevel::Limited,
253                 OptLevel::Default => OptimizationLevel::Standard,
254                 OptLevel::Aggressive => OptimizationLevel::Aggressive,
255                 OptLevel::Size | OptLevel::SizeMin => OptimizationLevel::Limited,
256             }
257         },
258     }
259 }
260
261 fn handle_native(name: &str) -> &str {
262     if name != "native" {
263         return name;
264     }
265
266     unimplemented!();
267 }
268
269 pub fn target_cpu(sess: &Session) -> &str {
270     let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu);
271     handle_native(name)
272 }
273
274 pub fn target_features(sess: &Session) -> Vec<Symbol> {
275     supported_target_features(sess)
276         .iter()
277         .filter_map(
278             |&(feature, gate)| {
279                 if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None }
280             },
281         )
282         .filter(|_feature| {
283             // TODO(antoyo): implement a way to get enabled feature in libgccjit.
284             false
285         })
286         .map(|feature| Symbol::intern(feature))
287         .collect()
288 }