]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_gcc/src/lib.rs
Merge commit '1411a98352ba6bee8ba3b0131c9243e5db1e6a2e' into sync_cg_clif-2021-12-31
[rust.git] / compiler / rustc_codegen_gcc / 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         Box::new(res)
95     }
96
97     fn join_codegen(&self, ongoing_codegen: Box<dyn Any>, sess: &Session, _outputs: &OutputFilenames) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
98         let (codegen_results, work_products) = ongoing_codegen
99             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<GccCodegenBackend>>()
100             .expect("Expected GccCodegenBackend's OngoingCodegen, found Box<Any>")
101             .join(sess);
102
103         Ok((codegen_results, work_products))
104     }
105
106     fn link(&self, sess: &Session, codegen_results: CodegenResults, outputs: &OutputFilenames) -> Result<(), ErrorReported> {
107         use rustc_codegen_ssa::back::link::link_binary;
108
109         link_binary::<crate::archive::ArArchiveBuilder<'_>>(
110             sess,
111             &codegen_results,
112             outputs,
113         )
114     }
115
116     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
117         target_features(sess)
118     }
119 }
120
121 impl ExtraBackendMethods for GccCodegenBackend {
122     fn new_metadata<'tcx>(&self, _tcx: TyCtxt<'tcx>, _mod_name: &str) -> Self::Module {
123         GccContext {
124             context: Context::default(),
125         }
126     }
127
128     fn codegen_allocator<'tcx>(&self, tcx: TyCtxt<'tcx>, mods: &mut Self::Module, module_name: &str, kind: AllocatorKind, has_alloc_error_handler: bool) {
129         unsafe { allocator::codegen(tcx, mods, module_name, kind, has_alloc_error_handler) }
130     }
131
132     fn compile_codegen_unit<'tcx>(&self, tcx: TyCtxt<'tcx>, cgu_name: Symbol) -> (ModuleCodegen<Self::Module>, u64) {
133         base::compile_codegen_unit(tcx, cgu_name)
134     }
135
136     fn target_machine_factory(&self, _sess: &Session, _opt_level: OptLevel) -> TargetMachineFactoryFn<Self> {
137         // TODO(antoyo): set opt level.
138         Arc::new(|_| {
139             Ok(())
140         })
141     }
142
143     fn target_cpu<'b>(&self, _sess: &'b Session) -> &'b str {
144         unimplemented!();
145     }
146
147     fn tune_cpu<'b>(&self, _sess: &'b Session) -> Option<&'b str> {
148         None
149         // TODO(antoyo)
150     }
151 }
152
153 pub struct ModuleBuffer;
154
155 impl ModuleBufferMethods for ModuleBuffer {
156     fn data(&self) -> &[u8] {
157         unimplemented!();
158     }
159 }
160
161 pub struct ThinBuffer;
162
163 impl ThinBufferMethods for ThinBuffer {
164     fn data(&self) -> &[u8] {
165         unimplemented!();
166     }
167 }
168
169 pub struct GccContext {
170     context: Context<'static>,
171 }
172
173 unsafe impl Send for GccContext {}
174 // FIXME(antoyo): that shouldn't be Sync. Parallel compilation is currently disabled with "-Zno-parallel-llvm". Try to disable it here.
175 unsafe impl Sync for GccContext {}
176
177 impl WriteBackendMethods for GccCodegenBackend {
178     type Module = GccContext;
179     type TargetMachine = ();
180     type ModuleBuffer = ModuleBuffer;
181     type Context = ();
182     type ThinData = ();
183     type ThinBuffer = ThinBuffer;
184
185     fn run_fat_lto(_cgcx: &CodegenContext<Self>, mut modules: Vec<FatLTOInput<Self>>, _cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>) -> Result<LtoModuleCodegen<Self>, FatalError> {
186         // TODO(antoyo): implement LTO by sending -flto to libgccjit and adding the appropriate gcc linker plugins.
187         // NOTE: implemented elsewhere.
188         // TODO: what is implemented elsewhere ^ ?
189         let module =
190             match modules.remove(0) {
191                 FatLTOInput::InMemory(module) => module,
192                 FatLTOInput::Serialized { .. } => {
193                     unimplemented!();
194                 }
195             };
196         Ok(LtoModuleCodegen::Fat { module: Some(module), _serialized_bitcode: vec![] })
197     }
198
199     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> {
200         unimplemented!();
201     }
202
203     fn print_pass_timings(&self) {
204         unimplemented!();
205     }
206
207     unsafe fn optimize(_cgcx: &CodegenContext<Self>, _diag_handler: &Handler, module: &ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<(), FatalError> {
208         module.module_llvm.context.set_optimization_level(to_gcc_opt_level(config.opt_level));
209         Ok(())
210     }
211
212     unsafe fn optimize_thin(_cgcx: &CodegenContext<Self>, _thin: &mut ThinModule<Self>) -> Result<ModuleCodegen<Self::Module>, FatalError> {
213         unimplemented!();
214     }
215
216     unsafe fn codegen(cgcx: &CodegenContext<Self>, diag_handler: &Handler, module: ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<CompiledModule, FatalError> {
217         back::write::codegen(cgcx, diag_handler, module, config)
218     }
219
220     fn prepare_thin(_module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
221         unimplemented!();
222     }
223
224     fn serialize_module(_module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
225         unimplemented!();
226     }
227
228     fn run_lto_pass_manager(_cgcx: &CodegenContext<Self>, _module: &ModuleCodegen<Self::Module>, _config: &ModuleConfig, _thin: bool) -> Result<(), FatalError> {
229         // TODO(antoyo)
230         Ok(())
231     }
232
233     fn run_link(cgcx: &CodegenContext<Self>, diag_handler: &Handler, modules: Vec<ModuleCodegen<Self::Module>>) -> Result<ModuleCodegen<Self::Module>, FatalError> {
234         back::write::link(cgcx, diag_handler, modules)
235     }
236 }
237
238 /// This is the entrypoint for a hot plugged rustc_codegen_gccjit
239 #[no_mangle]
240 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
241     Box::new(GccCodegenBackend)
242 }
243
244 fn to_gcc_opt_level(optlevel: Option<OptLevel>) -> OptimizationLevel {
245     match optlevel {
246         None => OptimizationLevel::None,
247         Some(level) => {
248             match level {
249                 OptLevel::No => OptimizationLevel::None,
250                 OptLevel::Less => OptimizationLevel::Limited,
251                 OptLevel::Default => OptimizationLevel::Standard,
252                 OptLevel::Aggressive => OptimizationLevel::Aggressive,
253                 OptLevel::Size | OptLevel::SizeMin => OptimizationLevel::Limited,
254             }
255         },
256     }
257 }
258
259 fn handle_native(name: &str) -> &str {
260     if name != "native" {
261         return name;
262     }
263
264     unimplemented!();
265 }
266
267 pub fn target_cpu(sess: &Session) -> &str {
268     let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu);
269     handle_native(name)
270 }
271
272 pub fn target_features(sess: &Session) -> Vec<Symbol> {
273     supported_target_features(sess)
274         .iter()
275         .filter_map(
276             |&(feature, gate)| {
277                 if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None }
278             },
279         )
280         .filter(|_feature| {
281             // TODO(antoyo): implement a way to get enabled feature in libgccjit.
282             false
283         })
284         .map(|feature| Symbol::intern(feature))
285         .collect()
286 }