]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_codegen_ssa/src/lib.rs
bump version to 1.79.0+dfsg1-1~bpo12+pve2
[rustc.git] / compiler / rustc_codegen_ssa / src / lib.rs
1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2 #![doc(rust_logo)]
3 #![feature(rustdoc_internals)]
4 #![allow(internal_features)]
5 #![feature(associated_type_bounds)]
6 #![feature(box_patterns)]
7 #![feature(if_let_guard)]
8 #![feature(let_chains)]
9 #![feature(negative_impls)]
10 #![feature(strict_provenance)]
11 #![feature(try_blocks)]
12
13 //! This crate contains codegen code that is used by all codegen backends (LLVM and others).
14 //! The backend-agnostic functions of this crate use functions defined in various traits that
15 //! have to be implemented by each backend.
16
17 #[macro_use]
18 extern crate rustc_macros;
19 #[macro_use]
20 extern crate tracing;
21 #[macro_use]
22 extern crate rustc_middle;
23
24 use rustc_ast as ast;
25 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
26 use rustc_data_structures::sync::Lrc;
27 use rustc_hir::def_id::CrateNum;
28 use rustc_middle::dep_graph::WorkProduct;
29 use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
30 use rustc_middle::middle::dependency_format::Dependencies;
31 use rustc_middle::middle::exported_symbols::SymbolExportKind;
32 use rustc_middle::util::Providers;
33 use rustc_serialize::opaque::{FileEncoder, MemDecoder};
34 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
35 use rustc_session::config::{CrateType, OutputFilenames, OutputType, RUST_CGU_EXT};
36 use rustc_session::cstore::{self, CrateSource};
37 use rustc_session::utils::NativeLibKind;
38 use rustc_session::Session;
39 use rustc_span::symbol::Symbol;
40 use std::collections::BTreeSet;
41 use std::io;
42 use std::path::{Path, PathBuf};
43
44 pub mod assert_module_sources;
45 pub mod back;
46 pub mod base;
47 pub mod codegen_attrs;
48 pub mod common;
49 pub mod debuginfo;
50 pub mod errors;
51 pub mod meth;
52 pub mod mir;
53 pub mod mono_item;
54 pub mod size_of_val;
55 pub mod target_features;
56 pub mod traits;
57
58 rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
59
60 pub struct ModuleCodegen<M> {
61 /// The name of the module. When the crate may be saved between
62 /// compilations, incremental compilation requires that name be
63 /// unique amongst **all** crates. Therefore, it should contain
64 /// something unique to this crate (e.g., a module path) as well
65 /// as the crate name and disambiguator.
66 /// We currently generate these names via CodegenUnit::build_cgu_name().
67 pub name: String,
68 pub module_llvm: M,
69 pub kind: ModuleKind,
70 }
71
72 impl<M> ModuleCodegen<M> {
73 pub fn into_compiled_module(
74 self,
75 emit_obj: bool,
76 emit_dwarf_obj: bool,
77 emit_bc: bool,
78 outputs: &OutputFilenames,
79 ) -> CompiledModule {
80 let object = emit_obj.then(|| outputs.temp_path(OutputType::Object, Some(&self.name)));
81 let dwarf_object = emit_dwarf_obj.then(|| outputs.temp_path_dwo(Some(&self.name)));
82 let bytecode = emit_bc.then(|| outputs.temp_path(OutputType::Bitcode, Some(&self.name)));
83
84 CompiledModule { name: self.name.clone(), kind: self.kind, object, dwarf_object, bytecode }
85 }
86 }
87
88 #[derive(Debug, Encodable, Decodable)]
89 pub struct CompiledModule {
90 pub name: String,
91 pub kind: ModuleKind,
92 pub object: Option<PathBuf>,
93 pub dwarf_object: Option<PathBuf>,
94 pub bytecode: Option<PathBuf>,
95 }
96
97 pub struct CachedModuleCodegen {
98 pub name: String,
99 pub source: WorkProduct,
100 }
101
102 #[derive(Copy, Clone, Debug, PartialEq, Encodable, Decodable)]
103 pub enum ModuleKind {
104 Regular,
105 Metadata,
106 Allocator,
107 }
108
109 bitflags::bitflags! {
110 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
111 pub struct MemFlags: u8 {
112 const VOLATILE = 1 << 0;
113 const NONTEMPORAL = 1 << 1;
114 const UNALIGNED = 1 << 2;
115 }
116 }
117
118 #[derive(Clone, Debug, Encodable, Decodable, HashStable)]
119 pub struct NativeLib {
120 pub kind: NativeLibKind,
121 pub name: Symbol,
122 pub filename: Option<Symbol>,
123 pub cfg: Option<ast::MetaItem>,
124 pub verbatim: bool,
125 pub dll_imports: Vec<cstore::DllImport>,
126 }
127
128 impl From<&cstore::NativeLib> for NativeLib {
129 fn from(lib: &cstore::NativeLib) -> Self {
130 NativeLib {
131 kind: lib.kind,
132 filename: lib.filename,
133 name: lib.name,
134 cfg: lib.cfg.clone(),
135 verbatim: lib.verbatim.unwrap_or(false),
136 dll_imports: lib.dll_imports.clone(),
137 }
138 }
139 }
140
141 /// Misc info we load from metadata to persist beyond the tcx.
142 ///
143 /// Note: though `CrateNum` is only meaningful within the same tcx, information within `CrateInfo`
144 /// is self-contained. `CrateNum` can be viewed as a unique identifier within a `CrateInfo`, where
145 /// `used_crate_source` contains all `CrateSource` of the dependents, and maintains a mapping from
146 /// identifiers (`CrateNum`) to `CrateSource`. The other fields map `CrateNum` to the crate's own
147 /// additional properties, so that effectively we can retrieve each dependent crate's `CrateSource`
148 /// and the corresponding properties without referencing information outside of a `CrateInfo`.
149 #[derive(Debug, Encodable, Decodable)]
150 pub struct CrateInfo {
151 pub target_cpu: String,
152 pub crate_types: Vec<CrateType>,
153 pub exported_symbols: FxHashMap<CrateType, Vec<String>>,
154 pub linked_symbols: FxHashMap<CrateType, Vec<(String, SymbolExportKind)>>,
155 pub local_crate_name: Symbol,
156 pub compiler_builtins: Option<CrateNum>,
157 pub profiler_runtime: Option<CrateNum>,
158 pub is_no_builtins: FxHashSet<CrateNum>,
159 pub native_libraries: FxHashMap<CrateNum, Vec<NativeLib>>,
160 pub crate_name: FxHashMap<CrateNum, Symbol>,
161 pub used_libraries: Vec<NativeLib>,
162 pub used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
163 pub used_crates: Vec<CrateNum>,
164 pub dependency_formats: Lrc<Dependencies>,
165 pub windows_subsystem: Option<String>,
166 pub natvis_debugger_visualizers: BTreeSet<DebuggerVisualizerFile>,
167 }
168
169 #[derive(Encodable, Decodable)]
170 pub struct CodegenResults {
171 pub modules: Vec<CompiledModule>,
172 pub allocator_module: Option<CompiledModule>,
173 pub metadata_module: Option<CompiledModule>,
174 pub metadata: rustc_metadata::EncodedMetadata,
175 pub crate_info: CrateInfo,
176 }
177
178 pub enum CodegenErrors {
179 WrongFileType,
180 EmptyVersionNumber,
181 EncodingVersionMismatch { version_array: String, rlink_version: u32 },
182 RustcVersionMismatch { rustc_version: String },
183 }
184
185 pub fn provide(providers: &mut Providers) {
186 crate::back::symbol_export::provide(providers);
187 crate::base::provide(providers);
188 crate::target_features::provide(providers);
189 crate::codegen_attrs::provide(providers);
190 }
191
192 /// Checks if the given filename ends with the `.rcgu.o` extension that `rustc`
193 /// uses for the object files it generates.
194 pub fn looks_like_rust_object_file(filename: &str) -> bool {
195 let path = Path::new(filename);
196 let ext = path.extension().and_then(|s| s.to_str());
197 if ext != Some(OutputType::Object.extension()) {
198 // The file name does not end with ".o", so it can't be an object file.
199 return false;
200 }
201
202 // Strip the ".o" at the end
203 let ext2 = path.file_stem().and_then(|s| Path::new(s).extension()).and_then(|s| s.to_str());
204
205 // Check if the "inner" extension
206 ext2 == Some(RUST_CGU_EXT)
207 }
208
209 const RLINK_VERSION: u32 = 1;
210 const RLINK_MAGIC: &[u8] = b"rustlink";
211
212 impl CodegenResults {
213 pub fn serialize_rlink(
214 sess: &Session,
215 rlink_file: &Path,
216 codegen_results: &CodegenResults,
217 outputs: &OutputFilenames,
218 ) -> Result<usize, io::Error> {
219 let mut encoder = FileEncoder::new(rlink_file)?;
220 encoder.emit_raw_bytes(RLINK_MAGIC);
221 // `emit_raw_bytes` is used to make sure that the version representation does not depend on
222 // Encoder's inner representation of `u32`.
223 encoder.emit_raw_bytes(&RLINK_VERSION.to_be_bytes());
224 encoder.emit_str(sess.cfg_version);
225 Encodable::encode(codegen_results, &mut encoder);
226 Encodable::encode(outputs, &mut encoder);
227 encoder.finish().map_err(|(_path, err)| err)
228 }
229
230 pub fn deserialize_rlink(
231 sess: &Session,
232 data: Vec<u8>,
233 ) -> Result<(Self, OutputFilenames), CodegenErrors> {
234 // The Decodable machinery is not used here because it panics if the input data is invalid
235 // and because its internal representation may change.
236 if !data.starts_with(RLINK_MAGIC) {
237 return Err(CodegenErrors::WrongFileType);
238 }
239 let data = &data[RLINK_MAGIC.len()..];
240 if data.len() < 4 {
241 return Err(CodegenErrors::EmptyVersionNumber);
242 }
243
244 let mut version_array: [u8; 4] = Default::default();
245 version_array.copy_from_slice(&data[..4]);
246 if u32::from_be_bytes(version_array) != RLINK_VERSION {
247 return Err(CodegenErrors::EncodingVersionMismatch {
248 version_array: String::from_utf8_lossy(&version_array).to_string(),
249 rlink_version: RLINK_VERSION,
250 });
251 }
252
253 let mut decoder = MemDecoder::new(&data[4..], 0);
254 let rustc_version = decoder.read_str();
255 if rustc_version != sess.cfg_version {
256 return Err(CodegenErrors::RustcVersionMismatch {
257 rustc_version: rustc_version.to_string(),
258 });
259 }
260
261 let codegen_results = CodegenResults::decode(&mut decoder);
262 let outputs = OutputFilenames::decode(&mut decoder);
263 Ok((codegen_results, outputs))
264 }
265 }