1#![allow(internal_features)]
3#![allow(rustc::diagnostic_outside_of_impl)]
4#![allow(rustc::untranslatable_diagnostic)]
5#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
6#![doc(rust_logo)]
7#![feature(assert_matches)]
8#![feature(box_patterns)]
9#![feature(file_buffered)]
10#![feature(if_let_guard)]
11#![feature(negative_impls)]
12#![feature(rustdoc_internals)]
13#![feature(string_from_utf8_lossy_owned)]
14#![feature(trait_alias)]
15#![feature(try_blocks)]
16#![recursion_limit = "256"]
17use std::collections::BTreeSet;
24use std::io;
25use std::path::{Path, PathBuf};
26use std::sync::Arc;
27
28use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
29use rustc_data_structures::unord::UnordMap;
30use rustc_hir::CRATE_HIR_ID;
31use rustc_hir::attrs::{CfgEntry, NativeLibKind};
32use rustc_hir::def_id::CrateNum;
33use rustc_macros::{Decodable, Encodable, HashStable};
34use rustc_metadata::EncodedMetadata;
35use rustc_middle::dep_graph::WorkProduct;
36use rustc_middle::lint::LevelAndSource;
37use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
38use rustc_middle::middle::dependency_format::Dependencies;
39use rustc_middle::middle::exported_symbols::SymbolExportKind;
40use rustc_middle::ty::TyCtxt;
41use rustc_middle::util::Providers;
42use rustc_serialize::opaque::{FileEncoder, MemDecoder};
43use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
44use rustc_session::Session;
45use rustc_session::config::{CrateType, OutputFilenames, OutputType, RUST_CGU_EXT};
46use rustc_session::cstore::{self, CrateSource};
47use rustc_session::lint::builtin::LINKER_MESSAGES;
48use rustc_span::Symbol;
49
50pub mod assert_module_sources;
51pub mod back;
52pub mod base;
53pub mod codegen_attrs;
54pub mod common;
55pub mod debuginfo;
56pub mod errors;
57pub mod meth;
58pub mod mir;
59pub mod mono_item;
60pub mod size_of_val;
61pub mod target_features;
62pub mod traits;
63
64rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
65
66pub struct ModuleCodegen<M> {
67 pub name: String,
74 pub module_llvm: M,
75 pub kind: ModuleKind,
76 pub thin_lto_buffer: Option<Vec<u8>>,
78}
79
80impl<M> ModuleCodegen<M> {
81 pub fn new_regular(name: impl Into<String>, module: M) -> Self {
82 Self {
83 name: name.into(),
84 module_llvm: module,
85 kind: ModuleKind::Regular,
86 thin_lto_buffer: None,
87 }
88 }
89
90 pub fn new_allocator(name: impl Into<String>, module: M) -> Self {
91 Self {
92 name: name.into(),
93 module_llvm: module,
94 kind: ModuleKind::Allocator,
95 thin_lto_buffer: None,
96 }
97 }
98
99 pub fn into_compiled_module(
100 self,
101 emit_obj: bool,
102 emit_dwarf_obj: bool,
103 emit_bc: bool,
104 emit_asm: bool,
105 emit_ir: bool,
106 outputs: &OutputFilenames,
107 invocation_temp: Option<&str>,
108 ) -> CompiledModule {
109 let object = emit_obj
110 .then(|| outputs.temp_path_for_cgu(OutputType::Object, &self.name, invocation_temp));
111 let dwarf_object =
112 emit_dwarf_obj.then(|| outputs.temp_path_dwo_for_cgu(&self.name, invocation_temp));
113 let bytecode = emit_bc
114 .then(|| outputs.temp_path_for_cgu(OutputType::Bitcode, &self.name, invocation_temp));
115 let assembly = emit_asm
116 .then(|| outputs.temp_path_for_cgu(OutputType::Assembly, &self.name, invocation_temp));
117 let llvm_ir = emit_ir.then(|| {
118 outputs.temp_path_for_cgu(OutputType::LlvmAssembly, &self.name, invocation_temp)
119 });
120
121 CompiledModule {
122 name: self.name,
123 object,
124 dwarf_object,
125 bytecode,
126 assembly,
127 llvm_ir,
128 links_from_incr_cache: Vec::new(),
129 }
130 }
131}
132
133#[derive(Debug, Encodable, Decodable)]
134pub struct CompiledModule {
135 pub name: String,
136 pub object: Option<PathBuf>,
137 pub dwarf_object: Option<PathBuf>,
138 pub bytecode: Option<PathBuf>,
139 pub assembly: Option<PathBuf>, pub llvm_ir: Option<PathBuf>, pub links_from_incr_cache: Vec<PathBuf>,
142}
143
144impl CompiledModule {
145 pub fn for_each_output(&self, mut emit: impl FnMut(&Path, OutputType)) {
147 if let Some(path) = self.object.as_deref() {
148 emit(path, OutputType::Object);
149 }
150 if let Some(path) = self.bytecode.as_deref() {
151 emit(path, OutputType::Bitcode);
152 }
153 if let Some(path) = self.llvm_ir.as_deref() {
154 emit(path, OutputType::LlvmAssembly);
155 }
156 if let Some(path) = self.assembly.as_deref() {
157 emit(path, OutputType::Assembly);
158 }
159 }
160}
161
162pub(crate) struct CachedModuleCodegen {
163 pub name: String,
164 pub source: WorkProduct,
165}
166
167#[derive(Copy, Clone, Debug, PartialEq, Encodable, Decodable)]
168pub enum ModuleKind {
169 Regular,
170 Allocator,
171}
172
173bitflags::bitflags! {
174 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
175 pub struct MemFlags: u8 {
176 const VOLATILE = 1 << 0;
177 const NONTEMPORAL = 1 << 1;
178 const UNALIGNED = 1 << 2;
179 }
180}
181
182#[derive(Clone, Debug, Encodable, Decodable, HashStable)]
183pub struct NativeLib {
184 pub kind: NativeLibKind,
185 pub name: Symbol,
186 pub filename: Option<Symbol>,
187 pub cfg: Option<CfgEntry>,
188 pub verbatim: bool,
189 pub dll_imports: Vec<cstore::DllImport>,
190}
191
192impl From<&cstore::NativeLib> for NativeLib {
193 fn from(lib: &cstore::NativeLib) -> Self {
194 NativeLib {
195 kind: lib.kind,
196 filename: lib.filename,
197 name: lib.name,
198 cfg: lib.cfg.clone(),
199 verbatim: lib.verbatim.unwrap_or(false),
200 dll_imports: lib.dll_imports.clone(),
201 }
202 }
203}
204
205#[derive(Debug, Encodable, Decodable)]
214pub struct CrateInfo {
215 pub target_cpu: String,
216 pub target_features: Vec<String>,
217 pub crate_types: Vec<CrateType>,
218 pub exported_symbols: UnordMap<CrateType, Vec<(String, SymbolExportKind)>>,
219 pub linked_symbols: FxIndexMap<CrateType, Vec<(String, SymbolExportKind)>>,
220 pub local_crate_name: Symbol,
221 pub compiler_builtins: Option<CrateNum>,
222 pub profiler_runtime: Option<CrateNum>,
223 pub is_no_builtins: FxHashSet<CrateNum>,
224 pub native_libraries: FxIndexMap<CrateNum, Vec<NativeLib>>,
225 pub crate_name: UnordMap<CrateNum, Symbol>,
226 pub used_libraries: Vec<NativeLib>,
227 pub used_crate_source: UnordMap<CrateNum, Arc<CrateSource>>,
228 pub used_crates: Vec<CrateNum>,
229 pub dependency_formats: Arc<Dependencies>,
230 pub windows_subsystem: Option<String>,
231 pub natvis_debugger_visualizers: BTreeSet<DebuggerVisualizerFile>,
232 pub lint_levels: CodegenLintLevels,
233 pub metadata_symbol: String,
234}
235
236pub struct TargetConfig {
240 pub target_features: Vec<Symbol>,
242 pub unstable_target_features: Vec<Symbol>,
244 pub has_reliable_f16: bool,
246 pub has_reliable_f16_math: bool,
248 pub has_reliable_f128: bool,
250 pub has_reliable_f128_math: bool,
252}
253
254#[derive(Encodable, Decodable)]
255pub struct CodegenResults {
256 pub modules: Vec<CompiledModule>,
257 pub allocator_module: Option<CompiledModule>,
258 pub crate_info: CrateInfo,
259}
260
261pub enum CodegenErrors {
262 WrongFileType,
263 EmptyVersionNumber,
264 EncodingVersionMismatch { version_array: String, rlink_version: u32 },
265 RustcVersionMismatch { rustc_version: String },
266 CorruptFile,
267}
268
269pub fn provide(providers: &mut Providers) {
270 crate::back::symbol_export::provide(providers);
271 crate::base::provide(providers);
272 crate::target_features::provide(providers);
273 crate::codegen_attrs::provide(providers);
274 providers.queries.global_backend_features = |_tcx: TyCtxt<'_>, ()| vec![];
275}
276
277pub fn looks_like_rust_object_file(filename: &str) -> bool {
280 let path = Path::new(filename);
281 let ext = path.extension().and_then(|s| s.to_str());
282 if ext != Some(OutputType::Object.extension()) {
283 return false;
285 }
286
287 let ext2 = path.file_stem().and_then(|s| Path::new(s).extension()).and_then(|s| s.to_str());
289
290 ext2 == Some(RUST_CGU_EXT)
292}
293
294const RLINK_VERSION: u32 = 1;
295const RLINK_MAGIC: &[u8] = b"rustlink";
296
297impl CodegenResults {
298 pub fn serialize_rlink(
299 sess: &Session,
300 rlink_file: &Path,
301 codegen_results: &CodegenResults,
302 metadata: &EncodedMetadata,
303 outputs: &OutputFilenames,
304 ) -> Result<usize, io::Error> {
305 let mut encoder = FileEncoder::new(rlink_file)?;
306 encoder.emit_raw_bytes(RLINK_MAGIC);
307 encoder.emit_raw_bytes(&RLINK_VERSION.to_be_bytes());
310 encoder.emit_str(sess.cfg_version);
311 Encodable::encode(codegen_results, &mut encoder);
312 Encodable::encode(metadata, &mut encoder);
313 Encodable::encode(outputs, &mut encoder);
314 encoder.finish().map_err(|(_path, err)| err)
315 }
316
317 pub fn deserialize_rlink(
318 sess: &Session,
319 data: Vec<u8>,
320 ) -> Result<(Self, EncodedMetadata, OutputFilenames), CodegenErrors> {
321 if !data.starts_with(RLINK_MAGIC) {
324 return Err(CodegenErrors::WrongFileType);
325 }
326 let data = &data[RLINK_MAGIC.len()..];
327 if data.len() < 4 {
328 return Err(CodegenErrors::EmptyVersionNumber);
329 }
330
331 let mut version_array: [u8; 4] = Default::default();
332 version_array.copy_from_slice(&data[..4]);
333 if u32::from_be_bytes(version_array) != RLINK_VERSION {
334 return Err(CodegenErrors::EncodingVersionMismatch {
335 version_array: String::from_utf8_lossy(&version_array).to_string(),
336 rlink_version: RLINK_VERSION,
337 });
338 }
339
340 let Ok(mut decoder) = MemDecoder::new(&data[4..], 0) else {
341 return Err(CodegenErrors::CorruptFile);
342 };
343 let rustc_version = decoder.read_str();
344 if rustc_version != sess.cfg_version {
345 return Err(CodegenErrors::RustcVersionMismatch {
346 rustc_version: rustc_version.to_string(),
347 });
348 }
349
350 let codegen_results = CodegenResults::decode(&mut decoder);
351 let metadata = EncodedMetadata::decode(&mut decoder);
352 let outputs = OutputFilenames::decode(&mut decoder);
353 Ok((codegen_results, metadata, outputs))
354 }
355}
356
357#[derive(Copy, Clone, Debug, Encodable, Decodable)]
363pub struct CodegenLintLevels {
364 linker_messages: LevelAndSource,
365}
366
367impl CodegenLintLevels {
368 pub fn from_tcx(tcx: TyCtxt<'_>) -> Self {
369 Self { linker_messages: tcx.lint_level_at_node(LINKER_MESSAGES, CRATE_HIR_ID) }
370 }
371}