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