1 use crate::errors::{FailCreateFileEncoder, FailSeekFile, FailWriteFile};
2 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
3 use crate::rmeta::table::TableBuilder;
6 use rustc_ast::Attribute;
7 use rustc_data_structures::fingerprint::Fingerprint;
8 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
9 use rustc_data_structures::memmap::{Mmap, MmapMut};
10 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
11 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
12 use rustc_data_structures::temp_dir::MaybeTempDir;
14 use rustc_hir::def::DefKind;
15 use rustc_hir::def_id::{
16 CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
18 use rustc_hir::definitions::DefPathData;
19 use rustc_hir::intravisit::{self, Visitor};
20 use rustc_hir::lang_items::LangItem;
21 use rustc_middle::hir::nested_filter;
22 use rustc_middle::middle::dependency_format::Linkage;
23 use rustc_middle::middle::exported_symbols::{
24 metadata_symbol_name, ExportedSymbol, SymbolExportInfo,
26 use rustc_middle::mir::interpret;
27 use rustc_middle::traits::specialization_graph;
28 use rustc_middle::ty::codec::TyEncoder;
29 use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams};
30 use rustc_middle::ty::query::Providers;
31 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
32 use rustc_middle::util::common::to_readable_str;
33 use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder};
34 use rustc_session::config::{CrateType, OptLevel};
35 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
36 use rustc_span::hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind};
37 use rustc_span::symbol::{sym, Symbol};
39 self, DebuggerVisualizerFile, ExternalSource, FileName, SourceFile, Span, SyntaxContext,
41 use std::borrow::Borrow;
42 use std::collections::hash_map::Entry;
44 use std::io::{Read, Seek, Write};
46 use std::num::NonZeroUsize;
47 use std::path::{Path, PathBuf};
49 pub(super) struct EncodeContext<'a, 'tcx> {
50 opaque: opaque::FileEncoder,
52 feat: &'tcx rustc_feature::Features,
54 tables: TableBuilders,
56 lazy_state: LazyState,
57 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
58 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
60 interpret_allocs: FxIndexSet<interpret::AllocId>,
62 // This is used to speed up Span encoding.
63 // The `usize` is an index into the `MonotonicVec`
64 // that stores the `SourceFile`
65 source_file_cache: (Lrc<SourceFile>, usize),
66 // The indices (into the `SourceMap`'s `MonotonicVec`)
67 // of all of the `SourceFiles` that we need to serialize.
68 // When we serialize a `Span`, we insert the index of its
69 // `SourceFile` into the `FxIndexSet`.
70 // The order inside the `FxIndexSet` is used as on-disk
71 // order of `SourceFiles`, and encoded inside `Span`s.
72 required_source_files: Option<FxIndexSet<usize>>,
74 hygiene_ctxt: &'a HygieneEncodeContext,
75 symbol_table: FxHashMap<Symbol, usize>,
78 /// If the current crate is a proc-macro, returns early with `LazyArray::empty()`.
79 /// This is useful for skipping the encoding of things that aren't needed
80 /// for proc-macro crates.
81 macro_rules! empty_proc_macro {
83 if $self.is_proc_macro {
84 return LazyArray::empty();
89 macro_rules! encoder_methods {
90 ($($name:ident($ty:ty);)*) => {
91 $(fn $name(&mut self, value: $ty) {
92 self.opaque.$name(value)
97 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
118 emit_raw_bytes(&[u8]);
122 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
123 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
124 e.emit_lazy_distance(self.position);
128 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
129 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
130 e.emit_usize(self.num_elems);
131 if self.num_elems > 0 {
132 e.emit_lazy_distance(self.position)
137 impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
138 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
139 e.emit_usize(self.encoded_size);
140 e.emit_lazy_distance(self.position);
144 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
145 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
146 if *self != LOCAL_CRATE && s.is_proc_macro {
147 panic!("Attempted to encode non-local CrateNum {self:?} for proc-macro crate");
149 s.emit_u32(self.as_u32());
153 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
154 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
155 s.emit_u32(self.as_u32());
159 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
160 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
161 s.emit_u32(self.as_u32());
165 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
166 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
167 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s);
171 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
172 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
173 if self.krate == LOCAL_CRATE {
174 // We will only write details for local expansions. Non-local expansions will fetch
175 // data from the corresponding crate's metadata.
176 // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
177 // metadata from proc-macro crates.
178 s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
180 self.krate.encode(s);
181 self.local_id.encode(s);
185 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
186 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
187 let span = self.data();
189 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
190 // since we don't load proc-macro dependencies during serialization.
191 // This means that any hygiene information from macros used *within*
192 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
193 // definition) will be lost.
195 // This can show up in two ways:
197 // 1. Any hygiene information associated with identifier of
198 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
199 // Since proc-macros can only be invoked from a different crate,
200 // real code should never need to care about this.
202 // 2. Using `Span::def_site` or `Span::mixed_site` will not
203 // include any hygiene information associated with the definition
204 // site. This means that a proc-macro cannot emit a `$crate`
205 // identifier which resolves to one of its dependencies,
206 // which also should never come up in practice.
208 // Additionally, this affects `Span::parent`, and any other
209 // span inspection APIs that would otherwise allow traversing
210 // the `SyntaxContexts` associated with a span.
212 // None of these user-visible effects should result in any
213 // cross-crate inconsistencies (getting one behavior in the same
214 // crate, and a different behavior in another crate) due to the
215 // limited surface that proc-macros can expose.
217 // IMPORTANT: If this is ever changed, be sure to update
218 // `rustc_span::hygiene::raw_encode_expn_id` to handle
219 // encoding `ExpnData` for proc-macro crates.
221 SyntaxContext::root().encode(s);
227 return TAG_PARTIAL_SPAN.encode(s);
230 // The Span infrastructure should make sure that this invariant holds:
231 debug_assert!(span.lo <= span.hi);
233 if !s.source_file_cache.0.contains(span.lo) {
234 let source_map = s.tcx.sess.source_map();
235 let source_file_index = source_map.lookup_source_file_idx(span.lo);
236 s.source_file_cache =
237 (source_map.files()[source_file_index].clone(), source_file_index);
239 let (ref source_file, source_file_index) = s.source_file_cache;
240 debug_assert!(source_file.contains(span.lo));
242 if !source_file.contains(span.hi) {
243 // Unfortunately, macro expansion still sometimes generates Spans
244 // that malformed in this way.
245 return TAG_PARTIAL_SPAN.encode(s);
248 // There are two possible cases here:
249 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
250 // crate we are writing metadata for. When the metadata for *this* crate gets
251 // deserialized, the deserializer will need to know which crate it originally came
252 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
253 // be deserialized after the rest of the span data, which tells the deserializer
254 // which crate contains the source map information.
255 // 2. This span comes from our own crate. No special handling is needed - we just
256 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
257 // our own source map information.
259 // If we're a proc-macro crate, we always treat this as a local `Span`.
260 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
261 // if we're a proc-macro crate.
262 // This allows us to avoid loading the dependencies of proc-macro crates: all of
263 // the information we need to decode `Span`s is stored in the proc-macro crate.
264 let (tag, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
265 // To simplify deserialization, we 'rebase' this span onto the crate it originally came
266 // from (the crate that 'owns' the file it references. These rebased 'lo' and 'hi'
267 // values are relative to the source map information for the 'foreign' crate whose
268 // CrateNum we write into the metadata. This allows `imported_source_files` to binary
269 // search through the 'foreign' crate's source map information, using the
270 // deserialized 'lo' and 'hi' values directly.
272 // All of this logic ensures that the final result of deserialization is a 'normal'
273 // Span that can be used without any additional trouble.
274 let metadata_index = {
275 // Introduce a new scope so that we drop the 'lock()' temporary
276 match &*source_file.external_src.lock() {
277 ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
278 src => panic!("Unexpected external source {src:?}"),
282 (TAG_VALID_SPAN_FOREIGN, metadata_index)
284 // Record the fact that we need to encode the data for this `SourceFile`
286 s.required_source_files.as_mut().expect("Already encoded SourceMap!");
287 let (metadata_index, _) = source_files.insert_full(source_file_index);
288 let metadata_index: u32 =
289 metadata_index.try_into().expect("cannot export more than U32_MAX files");
291 (TAG_VALID_SPAN_LOCAL, metadata_index)
294 // Encode the start position relative to the file start, so we profit more from the
295 // variable-length integer encoding.
296 let lo = span.lo - source_file.start_pos;
298 // Encode length which is usually less than span.hi and profits more
299 // from the variable-length integer encoding that we use.
300 let len = span.hi - span.lo;
306 // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
307 metadata_index.encode(s);
309 if tag == TAG_VALID_SPAN_FOREIGN {
310 // This needs to be two lines to avoid holding the `s.source_file_cache`
311 // while calling `cnum.encode(s)`
312 let cnum = s.source_file_cache.0.cnum;
318 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Symbol {
319 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
320 // if symbol preinterned, emit tag and symbol index
321 if self.is_preinterned() {
322 s.opaque.emit_u8(SYMBOL_PREINTERNED);
323 s.opaque.emit_u32(self.as_u32());
325 // otherwise write it as string or as offset to it
326 match s.symbol_table.entry(*self) {
327 Entry::Vacant(o) => {
328 s.opaque.emit_u8(SYMBOL_STR);
329 let pos = s.opaque.position();
331 s.emit_str(self.as_str());
333 Entry::Occupied(o) => {
335 s.emit_u8(SYMBOL_OFFSET);
343 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
344 const CLEAR_CROSS_CRATE: bool = true;
346 type I = TyCtxt<'tcx>;
348 fn position(&self) -> usize {
349 self.opaque.position()
352 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
353 &mut self.type_shorthands
356 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
357 &mut self.predicate_shorthands
360 fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
361 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
367 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
368 // normally need extra variables to avoid errors about multiple mutable borrows.
369 macro_rules! record {
370 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
373 let lazy = $self.lazy(value);
374 $self.$tables.$table.set($def_id.index, lazy);
379 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
380 // normally need extra variables to avoid errors about multiple mutable borrows.
381 macro_rules! record_array {
382 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
385 let lazy = $self.lazy_array(value);
386 $self.$tables.$table.set($def_id.index, lazy);
391 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
392 fn emit_lazy_distance(&mut self, position: NonZeroUsize) {
393 let pos = position.get();
394 let distance = match self.lazy_state {
395 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
396 LazyState::NodeStart(start) => {
397 let start = start.get();
398 assert!(pos <= start);
401 LazyState::Previous(last_pos) => {
403 last_pos <= position,
404 "make sure that the calls to `lazy*` \
405 are in the same order as the metadata fields",
407 position.get() - last_pos.get()
410 self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap());
411 self.emit_usize(distance);
414 fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
416 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
418 let pos = NonZeroUsize::new(self.position()).unwrap();
420 assert_eq!(self.lazy_state, LazyState::NoNode);
421 self.lazy_state = LazyState::NodeStart(pos);
422 value.borrow().encode(self);
423 self.lazy_state = LazyState::NoNode;
425 assert!(pos.get() <= self.position());
427 LazyValue::from_position(pos)
430 fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
435 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
437 let pos = NonZeroUsize::new(self.position()).unwrap();
439 assert_eq!(self.lazy_state, LazyState::NoNode);
440 self.lazy_state = LazyState::NodeStart(pos);
441 let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
442 self.lazy_state = LazyState::NoNode;
444 assert!(pos.get() <= self.position());
446 LazyArray::from_position_and_num_elems(pos, len)
449 fn encode_info_for_items(&mut self) {
450 self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
452 // Proc-macro crates only export proc-macro items, which are looked
453 // up using `proc_macro_data`
454 if self.is_proc_macro {
458 self.tcx.hir().visit_all_item_likes_in_crate(self);
461 fn encode_def_path_table(&mut self) {
462 let table = self.tcx.def_path_table();
463 if self.is_proc_macro {
464 for def_index in std::iter::once(CRATE_DEF_INDEX)
465 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
467 let def_key = self.lazy(table.def_key(def_index));
468 let def_path_hash = table.def_path_hash(def_index);
469 self.tables.def_keys.set(def_index, def_key);
470 self.tables.def_path_hashes.set(def_index, def_path_hash);
473 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
474 let def_key = self.lazy(def_key);
475 self.tables.def_keys.set(def_index, def_key);
476 self.tables.def_path_hashes.set(def_index, *def_path_hash);
481 fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
482 self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
485 fn encode_source_map(&mut self) -> LazyTable<u32, LazyValue<rustc_span::SourceFile>> {
486 let source_map = self.tcx.sess.source_map();
487 let all_source_files = source_map.files();
489 // By replacing the `Option` with `None`, we ensure that we can't
490 // accidentally serialize any more `Span`s after the source map encoding
492 let required_source_files = self.required_source_files.take().unwrap();
494 let working_directory = &self.tcx.sess.opts.working_dir;
496 let mut adapted = TableBuilder::default();
498 // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
500 // The order in which we encode source files is important here: the on-disk format for
501 // `Span` contains the index of the corresponding `SourceFile`.
502 for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
503 let source_file = &all_source_files[source_file_index];
504 // Don't serialize imported `SourceFile`s, unless we're in a proc-macro crate.
505 assert!(!source_file.is_imported() || self.is_proc_macro);
507 // At export time we expand all source file paths to absolute paths because
508 // downstream compilation sessions can have a different compiler working
509 // directory, so relative paths from this or any other upstream crate
510 // won't be valid anymore.
512 // At this point we also erase the actual on-disk path and only keep
513 // the remapped version -- as is necessary for reproducible builds.
514 let mut source_file = match source_file.name {
515 FileName::Real(ref original_file_name) => {
516 let adapted_file_name = source_map
518 .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
520 if adapted_file_name != *original_file_name {
521 let mut adapted: SourceFile = (**source_file).clone();
522 adapted.name = FileName::Real(adapted_file_name);
523 adapted.name_hash = {
524 let mut hasher: StableHasher = StableHasher::new();
525 adapted.name.hash(&mut hasher);
526 hasher.finish::<u128>()
534 // expanded code, not from a file
535 _ => source_file.clone(),
538 // We're serializing this `SourceFile` into our crate metadata,
539 // so mark it as coming from this crate.
540 // This also ensures that we don't try to deserialize the
541 // `CrateNum` for a proc-macro dependency - since proc macro
542 // dependencies aren't loaded when we deserialize a proc-macro,
543 // trying to remap the `CrateNum` would fail.
544 if self.is_proc_macro {
545 Lrc::make_mut(&mut source_file).cnum = LOCAL_CRATE;
548 let on_disk_index: u32 =
549 on_disk_index.try_into().expect("cannot export more than U32_MAX files");
550 adapted.set(on_disk_index, self.lazy(source_file));
553 adapted.encode(&mut self.opaque)
556 fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
558 let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
561 ($label:literal, $f:expr) => {{
562 let orig_pos = self.position();
564 stats.push(($label, self.position() - orig_pos));
569 // We have already encoded some things. Get their combined size from the current position.
570 stats.push(("preamble", self.position()));
572 let (crate_deps, dylib_dependency_formats) =
573 stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
575 let lib_features = stat!("lib-features", || self.encode_lib_features());
577 let stability_implications =
578 stat!("stability-implications", || self.encode_stability_implications());
580 let (lang_items, lang_items_missing) = stat!("lang-items", || {
581 (self.encode_lang_items(), self.encode_lang_items_missing())
584 let diagnostic_items = stat!("diagnostic-items", || self.encode_diagnostic_items());
586 let native_libraries = stat!("native-libs", || self.encode_native_libraries());
588 let foreign_modules = stat!("foreign-modules", || self.encode_foreign_modules());
590 _ = stat!("def-path-table", || self.encode_def_path_table());
592 // Encode the def IDs of traits, for rustdoc and diagnostics.
593 let traits = stat!("traits", || self.encode_traits());
595 // Encode the def IDs of impls, for coherence checking.
596 let impls = stat!("impls", || self.encode_impls());
598 let incoherent_impls = stat!("incoherent-impls", || self.encode_incoherent_impls());
600 _ = stat!("mir", || self.encode_mir());
602 _ = stat!("items", || {
603 self.encode_def_ids();
604 self.encode_info_for_items();
607 let interpret_alloc_index = stat!("interpret-alloc-index", || {
608 let mut interpret_alloc_index = Vec::new();
610 trace!("beginning to encode alloc ids");
612 let new_n = self.interpret_allocs.len();
613 // if we have found new ids, serialize those, too
618 trace!("encoding {} further alloc ids", new_n - n);
619 for idx in n..new_n {
620 let id = self.interpret_allocs[idx];
621 let pos = self.position() as u32;
622 interpret_alloc_index.push(pos);
623 interpret::specialized_encode_alloc_id(self, tcx, id);
627 self.lazy_array(interpret_alloc_index)
630 // Encode the proc macro data. This affects `tables`, so we need to do this before we
631 // encode the tables. This overwrites def_keys, so it must happen after
632 // encode_def_path_table.
633 let proc_macro_data = stat!("proc-macro-data", || self.encode_proc_macros());
635 let tables = stat!("tables", || self.tables.encode(&mut self.opaque));
637 let debugger_visualizers =
638 stat!("debugger-visualizers", || self.encode_debugger_visualizers());
640 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
641 // this as late as possible to give the prefetching as much time as possible to complete.
642 let exported_symbols = stat!("exported-symbols", || {
643 self.encode_exported_symbols(&tcx.exported_symbols(LOCAL_CRATE))
646 // Encode the hygiene data.
647 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The
648 // process of encoding other items (e.g. `optimized_mir`) may cause us to load data from
649 // the incremental cache. If this causes us to deserialize a `Span`, then we may load
650 // additional `SyntaxContext`s into the global `HygieneData`. Therefore, we need to encode
651 // the hygiene data last to ensure that we encode any `SyntaxContext`s that might be used.
652 let (syntax_contexts, expn_data, expn_hashes) = stat!("hygiene", || self.encode_hygiene());
654 let def_path_hash_map = stat!("def-path-hash-map", || self.encode_def_path_hash_map());
656 // Encode source_map. This needs to be done last, because encoding `Span`s tells us which
657 // `SourceFiles` we actually need to encode.
658 let source_map = stat!("source-map", || self.encode_source_map());
660 let root = stat!("final", || {
661 let attrs = tcx.hir().krate_attrs();
662 self.lazy(CrateRoot {
663 name: tcx.crate_name(LOCAL_CRATE),
664 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
665 triple: tcx.sess.opts.target_triple.clone(),
666 hash: tcx.crate_hash(LOCAL_CRATE),
667 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
668 required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
669 panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
670 edition: tcx.sess.edition(),
671 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
672 has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
673 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
674 has_default_lib_allocator: tcx
676 .contains_name(&attrs, sym::default_lib_allocator),
678 debugger_visualizers,
679 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
680 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
681 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
682 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
683 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
684 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
685 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
688 dylib_dependency_formats,
690 stability_implications,
701 interpret_alloc_index,
710 let total_bytes = self.position();
712 let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
713 assert_eq!(total_bytes, computed_total_bytes);
715 if tcx.sess.opts.unstable_opts.meta_stats {
718 // Rewind and re-read all the metadata to count the zero bytes we wrote.
719 let pos_before_rewind = self.opaque.file().stream_position().unwrap();
720 let mut zero_bytes = 0;
721 self.opaque.file().rewind().unwrap();
722 let file = std::io::BufReader::new(self.opaque.file());
723 for e in file.bytes() {
728 assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
730 stats.sort_by_key(|&(_, usize)| usize);
732 let prefix = "meta-stats";
733 let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
735 eprintln!("{prefix} METADATA STATS");
736 eprintln!("{} {:<23}{:>10}", prefix, "Section", "Size");
737 eprintln!("{prefix} ----------------------------------------------------------------");
738 for (label, size) in stats {
740 "{} {:<23}{:>10} ({:4.1}%)",
743 to_readable_str(size),
747 eprintln!("{prefix} ----------------------------------------------------------------");
749 "{} {:<23}{:>10} (of which {:.1}% are zero bytes)",
752 to_readable_str(total_bytes),
755 eprintln!("{prefix}");
762 /// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and
763 /// useful in downstream crates. Local-only attributes are an obvious example, but some
764 /// rustdoc-specific attributes can equally be of use while documenting the current crate only.
766 /// Removing these superfluous attributes speeds up compilation by making the metadata smaller.
768 /// Note: the `is_def_id_public` parameter is used to cache whether the given `DefId` has a public
769 /// visibility: this is a piece of data that can be computed once per defid, and not once per
770 /// attribute. Some attributes would only be usable downstream if they are public.
772 fn should_encode_attr(
776 is_def_id_public: &mut Option<bool>,
778 if rustc_feature::is_builtin_only_local(attr.name_or_empty()) {
779 // Attributes marked local-only don't need to be encoded for downstream crates.
781 } else if attr.doc_str().is_some() {
782 // We keep all public doc comments because they might be "imported" into downstream crates
783 // if they use `#[doc(inline)]` to copy an item's documentation into their own.
784 *is_def_id_public.get_or_insert_with(|| tcx.effective_visibilities(()).is_exported(def_id))
785 } else if attr.has_name(sym::doc) {
786 // If this is a `doc` attribute, and it's marked `inline` (as in `#[doc(inline)]`), we can
787 // remove it. It won't be inlinable in downstream crates.
788 attr.meta_item_list().map(|l| l.iter().any(|l| !l.has_name(sym::inline))).unwrap_or(false)
794 fn should_encode_visibility(def_kind: DefKind) -> bool {
804 | DefKind::TraitAlias
808 | DefKind::Static(..)
811 | DefKind::AssocConst
814 | DefKind::ForeignMod
816 | DefKind::ImplTraitPlaceholder
818 | DefKind::Field => true,
820 | DefKind::ConstParam
821 | DefKind::LifetimeParam
823 | DefKind::InlineConst
827 | DefKind::ExternCrate => false,
831 fn should_encode_stability(def_kind: DefKind) -> bool {
840 | DefKind::AssocConst
842 | DefKind::ConstParam
843 | DefKind::Static(..)
846 | DefKind::ForeignMod
849 | DefKind::ImplTraitPlaceholder
854 | DefKind::TraitAlias
856 | DefKind::ForeignTy => true,
858 | DefKind::LifetimeParam
860 | DefKind::InlineConst
864 | DefKind::ExternCrate => false,
868 /// Whether we should encode MIR.
870 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
871 /// We want to avoid this work when not required. Therefore:
872 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
873 /// - we skip `optimized_mir` for check runs.
875 /// Return a pair, resp. for CTFE and for LLVM.
876 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
877 match tcx.def_kind(def_id) {
879 DefKind::Ctor(_, _) => {
880 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
881 || tcx.sess.opts.unstable_opts.always_encode_mir;
886 | DefKind::InlineConst
887 | DefKind::AssocConst
888 | DefKind::Static(..)
889 | DefKind::Const => (true, false),
890 // Full-fledged functions + closures
891 DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
892 let generics = tcx.generics_of(def_id);
893 let needs_inline = (generics.requires_monomorphization(tcx)
894 || tcx.codegen_fn_attrs(def_id).requests_inline())
895 && tcx.sess.opts.output_types.should_codegen();
896 // The function has a `const` modifier or is in a `#[const_trait]`.
897 let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id())
898 || tcx.is_const_default_method(def_id.to_def_id());
899 let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
900 (is_const_fn, needs_inline || always_encode_mir)
902 // Generators require optimized MIR to compute layout.
903 DefKind::Generator => (false, true),
904 // The others don't have MIR.
909 fn should_encode_variances(def_kind: DefKind) -> bool {
916 | DefKind::ImplTraitPlaceholder
919 | DefKind::AssocFn => true,
923 | DefKind::AssocConst
925 | DefKind::ConstParam
926 | DefKind::Static(..)
928 | DefKind::ForeignMod
932 | DefKind::TraitAlias
936 | DefKind::LifetimeParam
938 | DefKind::InlineConst
942 | DefKind::ExternCrate => false,
946 fn should_encode_generics(def_kind: DefKind) -> bool {
955 | DefKind::TraitAlias
959 | DefKind::Static(..)
962 | DefKind::AssocConst
964 | DefKind::InlineConst
966 | DefKind::ImplTraitPlaceholder
971 | DefKind::Generator => true,
973 | DefKind::ForeignMod
974 | DefKind::ConstParam
977 | DefKind::LifetimeParam
979 | DefKind::ExternCrate => false,
983 fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
993 | DefKind::Static(..)
999 | DefKind::AssocConst
1001 | DefKind::Generator
1002 | DefKind::ConstParam
1003 | DefKind::AnonConst
1004 | DefKind::InlineConst => true,
1006 DefKind::ImplTraitPlaceholder => {
1007 let parent_def_id = tcx.impl_trait_in_trait_parent(def_id.to_def_id());
1008 let assoc_item = tcx.associated_item(parent_def_id);
1009 match assoc_item.container {
1010 // Always encode an RPIT in an impl fn, since it always has a body
1011 ty::AssocItemContainer::ImplContainer => true,
1012 ty::AssocItemContainer::TraitContainer => {
1013 // Encode an RPIT for a trait only if the trait has a default body
1014 assoc_item.defaultness(tcx).has_value()
1019 DefKind::AssocTy => {
1020 let assoc_item = tcx.associated_item(def_id);
1021 match assoc_item.container {
1022 ty::AssocItemContainer::ImplContainer => true,
1023 ty::AssocItemContainer::TraitContainer => assoc_item.defaultness(tcx).has_value(),
1026 DefKind::TyParam => {
1027 let hir::Node::GenericParam(param) = tcx.hir().get_by_def_id(def_id) else { bug!() };
1028 let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() };
1033 | DefKind::TraitAlias
1035 | DefKind::ForeignMod
1036 | DefKind::Macro(..)
1038 | DefKind::LifetimeParam
1039 | DefKind::GlobalAsm
1040 | DefKind::ExternCrate => false,
1044 fn should_encode_const(def_kind: DefKind) -> bool {
1046 DefKind::Const | DefKind::AssocConst | DefKind::AnonConst => true,
1055 | DefKind::Static(..)
1058 | DefKind::ImplTraitPlaceholder
1059 | DefKind::ForeignTy
1063 | DefKind::Generator
1064 | DefKind::ConstParam
1065 | DefKind::InlineConst
1069 | DefKind::TraitAlias
1071 | DefKind::ForeignMod
1072 | DefKind::Macro(..)
1074 | DefKind::LifetimeParam
1075 | DefKind::GlobalAsm
1076 | DefKind::ExternCrate => false,
1080 fn should_encode_trait_impl_trait_tys(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1081 if tcx.def_kind(def_id) != DefKind::AssocFn {
1085 let Some(item) = tcx.opt_associated_item(def_id) else { return false; };
1086 if item.container != ty::AssocItemContainer::ImplContainer {
1090 let Some(trait_item_def_id) = item.trait_item_def_id else { return false; };
1092 // FIXME(RPITIT): This does a somewhat manual walk through the signature
1093 // of the trait fn to look for any RPITITs, but that's kinda doing a lot
1094 // of work. We can probably remove this when we refactor RPITITs to be
1095 // associated types.
1096 tcx.fn_sig(trait_item_def_id).skip_binder().output().walk().any(|arg| {
1097 if let ty::GenericArgKind::Type(ty) = arg.unpack()
1098 && let ty::Alias(ty::Projection, data) = ty.kind()
1099 && tcx.def_kind(data.def_id) == DefKind::ImplTraitPlaceholder
1108 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1109 fn encode_attrs(&mut self, def_id: LocalDefId) {
1111 let mut is_public: Option<bool> = None;
1115 .attrs(tcx.hir().local_def_id_to_hir_id(def_id))
1117 .filter(move |attr| should_encode_attr(tcx, attr, def_id, &mut is_public));
1119 record_array!(self.tables.attributes[def_id.to_def_id()] <- attrs.clone());
1120 if attrs.any(|attr| attr.may_have_doc_links()) {
1121 self.tables.may_have_doc_links.set(def_id.local_def_index, ());
1125 fn encode_def_ids(&mut self) {
1126 if self.is_proc_macro {
1130 for local_id in tcx.iter_local_def_id() {
1131 let def_id = local_id.to_def_id();
1132 let def_kind = tcx.opt_def_kind(local_id);
1133 let Some(def_kind) = def_kind else { continue };
1134 self.tables.opt_def_kind.set(def_id.index, def_kind);
1135 let def_span = tcx.def_span(local_id);
1136 record!(self.tables.def_span[def_id] <- def_span);
1137 self.encode_attrs(local_id);
1138 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1139 if let Some(ident_span) = tcx.def_ident_span(def_id) {
1140 record!(self.tables.def_ident_span[def_id] <- ident_span);
1142 if def_kind.has_codegen_attrs() {
1143 record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1145 if should_encode_visibility(def_kind) {
1147 self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);
1148 record!(self.tables.visibility[def_id] <- vis);
1150 if should_encode_stability(def_kind) {
1151 self.encode_stability(def_id);
1152 self.encode_const_stability(def_id);
1153 self.encode_default_body_stability(def_id);
1154 self.encode_deprecation(def_id);
1156 if should_encode_variances(def_kind) {
1157 let v = self.tcx.variances_of(def_id);
1158 record_array!(self.tables.variances_of[def_id] <- v);
1160 if should_encode_generics(def_kind) {
1161 let g = tcx.generics_of(def_id);
1162 record!(self.tables.generics_of[def_id] <- g);
1163 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1164 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1165 if !inferred_outlives.is_empty() {
1166 record_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1169 if should_encode_type(tcx, local_id, def_kind) {
1170 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1172 if let DefKind::TyParam = def_kind {
1173 let default = self.tcx.object_lifetime_default(def_id);
1174 record!(self.tables.object_lifetime_default[def_id] <- default);
1176 if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1177 record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id));
1179 if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1180 self.encode_info_for_adt(def_id);
1182 if should_encode_trait_impl_trait_tys(tcx, def_id)
1183 && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1185 record!(self.tables.trait_impl_trait_tys[def_id] <- table);
1188 let inherent_impls = tcx.crate_inherent_impls(());
1189 for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
1190 if implementations.is_empty() {
1193 record_array!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1194 assert!(def_id.is_local());
1200 #[instrument(level = "trace", skip(self))]
1201 fn encode_info_for_adt(&mut self, def_id: DefId) {
1203 let adt_def = tcx.adt_def(def_id);
1204 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1206 let params_in_repr = self.tcx.params_in_repr(def_id);
1207 record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1209 if adt_def.is_enum() {
1210 record_array!(self.tables.children[def_id] <- iter::from_generator(||
1211 for variant in tcx.adt_def(def_id).variants() {
1212 yield variant.def_id.index;
1213 // Encode constructors which take a separate slot in value namespace.
1214 if let Some(ctor_def_id) = variant.ctor_def_id() {
1215 yield ctor_def_id.index;
1221 // In some cases, along with the item itself, we also
1222 // encode some sub-items. Usually we want some info from the item
1223 // so it's easier to do that here then to wait until we would encounter
1224 // normally in the visitor walk.
1225 for variant in adt_def.variants().iter() {
1226 self.encode_enum_variant_info(variant);
1230 fn encode_enum_variant_info(&mut self, variant: &ty::VariantDef) {
1232 let def_id = variant.def_id;
1233 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1235 let data = VariantData {
1236 discr: variant.discr,
1237 ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1238 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1241 record!(self.tables.variant_data[def_id] <- data);
1242 self.tables.constness.set(def_id.index, hir::Constness::Const);
1243 record_array!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1244 assert!(f.did.is_local());
1247 if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1248 debug!("EncodeContext::encode_enum_variant_ctor({:?})", ctor_def_id);
1250 self.tables.constness.set(ctor_def_id.index, hir::Constness::Const);
1252 let fn_sig = tcx.fn_sig(ctor_def_id);
1253 record!(self.tables.fn_sig[ctor_def_id] <- fn_sig);
1254 // FIXME(eddyb) encode signature only for `ctor_def_id`.
1255 record!(self.tables.fn_sig[def_id] <- fn_sig);
1259 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1261 let def_id = local_def_id.to_def_id();
1262 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1264 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1265 // only ever get called for the crate root. We still want to encode
1266 // the crate root for consistency with other crates (some of the resolver
1267 // code uses it). However, we skip encoding anything relating to child
1268 // items - we encode information about proc-macros later on.
1269 if self.is_proc_macro {
1270 // Encode this here because we don't do it in encode_def_ids.
1271 record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1273 record_array!(self.tables.children[def_id] <- iter::from_generator(|| {
1274 for item_id in md.item_ids {
1275 match tcx.hir().item(*item_id).kind {
1276 // Foreign items are planted into their parent modules
1277 // from name resolution point of view.
1278 hir::ItemKind::ForeignMod { items, .. } => {
1279 for foreign_item in items {
1280 yield foreign_item.id.owner_id.def_id.local_def_index;
1283 // Only encode named non-reexport children, reexports are encoded
1284 // separately and unnamed items are not used by name resolution.
1285 hir::ItemKind::ExternCrate(..) => continue,
1286 hir::ItemKind::Struct(ref vdata, _) => {
1287 yield item_id.owner_id.def_id.local_def_index;
1288 // Encode constructors which take a separate slot in value namespace.
1289 if let Some(ctor_hir_id) = vdata.ctor_hir_id() {
1290 yield tcx.hir().local_def_id(ctor_hir_id).local_def_index;
1293 _ if tcx.def_key(item_id.owner_id.to_def_id()).get_opt_name().is_some() => {
1294 yield item_id.owner_id.def_id.local_def_index;
1301 if let Some(reexports) = tcx.module_reexports(local_def_id) {
1302 assert!(!reexports.is_empty());
1303 record_array!(self.tables.module_reexports[def_id] <- reexports);
1308 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1309 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1310 let bounds = self.tcx.explicit_item_bounds(def_id);
1311 if !bounds.is_empty() {
1312 record_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1316 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1317 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1320 let impl_defaultness = tcx.impl_defaultness(def_id.expect_local());
1321 self.tables.impl_defaultness.set(def_id.index, impl_defaultness);
1322 let trait_item = tcx.associated_item(def_id);
1323 self.tables.assoc_container.set(def_id.index, trait_item.container);
1325 match trait_item.kind {
1326 ty::AssocKind::Const => {}
1327 ty::AssocKind::Fn => {
1328 record_array!(self.tables.fn_arg_names[def_id] <- tcx.fn_arg_names(def_id));
1329 self.tables.asyncness.set(def_id.index, tcx.asyncness(def_id));
1330 self.tables.constness.set(def_id.index, hir::Constness::NotConst);
1332 ty::AssocKind::Type => {
1333 self.encode_explicit_item_bounds(def_id);
1336 if trait_item.kind == ty::AssocKind::Fn {
1337 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1341 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1342 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1345 let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local());
1346 self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
1347 let impl_item = self.tcx.associated_item(def_id);
1348 self.tables.assoc_container.set(def_id.index, impl_item.container);
1350 match impl_item.kind {
1351 ty::AssocKind::Fn => {
1352 let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() };
1353 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1354 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1355 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1356 let constness = if self.tcx.is_const_fn_raw(def_id) {
1357 hir::Constness::Const
1359 hir::Constness::NotConst
1361 self.tables.constness.set(def_id.index, constness);
1363 ty::AssocKind::Const | ty::AssocKind::Type => {}
1365 if let Some(trait_item_def_id) = impl_item.trait_item_def_id {
1366 self.tables.trait_item_def_id.set(def_id.index, trait_item_def_id.into());
1368 if impl_item.kind == ty::AssocKind::Fn {
1369 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1370 if tcx.is_intrinsic(def_id) {
1371 self.tables.is_intrinsic.set(def_id.index, ());
1376 fn encode_mir(&mut self) {
1377 if self.is_proc_macro {
1383 let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1384 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
1385 if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1387 for (def_id, encode_const, encode_opt) in keys_and_jobs {
1388 debug_assert!(encode_const || encode_opt);
1390 debug!("EntryBuilder::encode_mir({:?})", def_id);
1392 record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1395 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1397 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1398 let abstract_const = tcx.thir_abstract_const(def_id);
1399 if let Ok(Some(abstract_const)) = abstract_const {
1400 record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1403 if should_encode_const(tcx.def_kind(def_id)) {
1404 let qualifs = tcx.mir_const_qualif(def_id);
1405 record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1406 let body_id = tcx.hir().maybe_body_owned_by(def_id);
1407 if let Some(body_id) = body_id {
1408 let const_data = self.encode_rendered_const_for_body(body_id);
1409 record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1413 record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1416 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1417 let unused = tcx.unused_generic_params(instance);
1418 if !unused.all_used() {
1419 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1423 // Encode all the deduced parameter attributes for everything that has MIR, even for items
1424 // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1425 // save the query traffic.
1426 if tcx.sess.opts.output_types.should_codegen()
1427 && tcx.sess.opts.optimize != OptLevel::No
1428 && tcx.sess.opts.incremental.is_none()
1430 for &local_def_id in tcx.mir_keys(()) {
1431 if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1432 record_array!(self.tables.deduced_param_attrs[local_def_id.to_def_id()] <-
1433 self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1439 fn encode_stability(&mut self, def_id: DefId) {
1440 debug!("EncodeContext::encode_stability({:?})", def_id);
1442 // The query lookup can take a measurable amount of time in crates with many items. Check if
1443 // the stability attributes are even enabled before using their queries.
1444 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1445 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1446 record!(self.tables.lookup_stability[def_id] <- stab)
1451 fn encode_const_stability(&mut self, def_id: DefId) {
1452 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1454 // The query lookup can take a measurable amount of time in crates with many items. Check if
1455 // the stability attributes are even enabled before using their queries.
1456 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1457 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1458 record!(self.tables.lookup_const_stability[def_id] <- stab)
1463 fn encode_default_body_stability(&mut self, def_id: DefId) {
1464 debug!("EncodeContext::encode_default_body_stability({:?})", def_id);
1466 // The query lookup can take a measurable amount of time in crates with many items. Check if
1467 // the stability attributes are even enabled before using their queries.
1468 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1469 if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1470 record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1475 fn encode_deprecation(&mut self, def_id: DefId) {
1476 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1477 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1478 record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1482 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> String {
1483 let hir = self.tcx.hir();
1484 let body = hir.body(body_id);
1485 rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1486 s.print_expr(&body.value)
1490 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1493 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1496 hir::ItemKind::Fn(ref sig, .., body) => {
1497 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1498 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1499 self.tables.constness.set(def_id.index, sig.header.constness);
1501 hir::ItemKind::Macro(ref macro_def, _) => {
1502 if macro_def.macro_rules {
1503 self.tables.macro_rules.set(def_id.index, ());
1505 record!(self.tables.macro_definition[def_id] <- &*macro_def.body);
1507 hir::ItemKind::Mod(ref m) => {
1508 return self.encode_info_for_mod(item.owner_id.def_id, m);
1510 hir::ItemKind::OpaqueTy(ref opaque) => {
1511 self.encode_explicit_item_bounds(def_id);
1512 if matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias) {
1513 self.tables.is_type_alias_impl_trait.set(def_id.index, ());
1516 hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1517 self.tables.impl_defaultness.set(def_id.index, *defaultness);
1518 self.tables.constness.set(def_id.index, *constness);
1520 let trait_ref = self.tcx.impl_trait_ref(def_id).map(ty::EarlyBinder::skip_binder);
1521 if let Some(trait_ref) = trait_ref {
1522 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1523 if let Ok(mut an) = trait_def.ancestors(self.tcx, def_id) {
1524 if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
1525 self.tables.impl_parent.set(def_id.index, parent.into());
1529 // if this is an impl of `CoerceUnsized`, create its
1530 // "unsized info", else just store None
1531 if Some(trait_ref.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1532 let coerce_unsized_info =
1533 self.tcx.at(item.span).coerce_unsized_info(def_id);
1534 record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
1538 let polarity = self.tcx.impl_polarity(def_id);
1539 self.tables.impl_polarity.set(def_id.index, polarity);
1541 hir::ItemKind::Trait(..) => {
1542 let trait_def = self.tcx.trait_def(def_id);
1543 record!(self.tables.trait_def[def_id] <- trait_def);
1545 hir::ItemKind::TraitAlias(..) => {
1546 let trait_def = self.tcx.trait_def(def_id);
1547 record!(self.tables.trait_def[def_id] <- trait_def);
1549 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1550 bug!("cannot encode info for item {:?}", item)
1552 hir::ItemKind::Static(..)
1553 | hir::ItemKind::Const(..)
1554 | hir::ItemKind::Enum(..)
1555 | hir::ItemKind::Struct(..)
1556 | hir::ItemKind::Union(..)
1557 | hir::ItemKind::ForeignMod { .. }
1558 | hir::ItemKind::GlobalAsm(..)
1559 | hir::ItemKind::TyAlias(..) => {}
1561 // FIXME(eddyb) there should be a nicer way to do this.
1563 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1564 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1565 record_array!(self.tables.children[def_id] <-
1566 associated_item_def_ids.iter().map(|&def_id| {
1567 assert!(def_id.is_local());
1574 if let hir::ItemKind::Fn(..) = item.kind {
1575 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1576 if tcx.is_intrinsic(def_id) {
1577 self.tables.is_intrinsic.set(def_id.index, ());
1580 if let hir::ItemKind::Impl { .. } = item.kind {
1581 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1582 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1585 // In some cases, along with the item itself, we also
1586 // encode some sub-items. Usually we want some info from the item
1587 // so it's easier to do that here then to wait until we would encounter
1588 // normally in the visitor walk.
1590 hir::ItemKind::Impl { .. } => {
1591 for &trait_item_def_id in
1592 self.tcx.associated_item_def_ids(item.owner_id.to_def_id()).iter()
1594 self.encode_info_for_impl_item(trait_item_def_id);
1597 hir::ItemKind::Trait(..) => {
1599 self.tcx.associated_item_def_ids(item.owner_id.to_def_id()).iter()
1601 self.encode_info_for_trait_item(item_def_id);
1608 #[instrument(level = "debug", skip(self))]
1609 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1610 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1611 // including on the signature, which is inferred in `typeck.
1612 let typeck_result: &'tcx ty::TypeckResults<'tcx> = self.tcx.typeck(def_id);
1613 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1614 let ty = typeck_result.node_type(hir_id);
1616 ty::Generator(..) => {
1617 let data = self.tcx.generator_kind(def_id).unwrap();
1618 let generator_diagnostic_data = typeck_result.get_generator_diagnostic_data();
1619 record!(self.tables.generator_kind[def_id.to_def_id()] <- data);
1620 record!(self.tables.generator_diagnostic_data[def_id.to_def_id()] <- generator_diagnostic_data);
1623 ty::Closure(_, substs) => {
1624 let constness = self.tcx.constness(def_id.to_def_id());
1625 self.tables.constness.set(def_id.to_def_id().index, constness);
1626 record!(self.tables.fn_sig[def_id.to_def_id()] <- substs.as_closure().sig());
1629 _ => bug!("closure that is neither generator nor closure"),
1633 fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1634 empty_proc_macro!(self);
1635 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1636 self.lazy_array(used_libraries.iter())
1639 fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1640 empty_proc_macro!(self);
1641 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1642 self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1645 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1646 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1647 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1648 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1650 self.hygiene_ctxt.encode(
1651 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1652 |(this, syntax_contexts, _, _), index, ctxt_data| {
1653 syntax_contexts.set(index, this.lazy(ctxt_data));
1655 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1656 if let Some(index) = index.as_local() {
1657 expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1658 expn_hash_table.set(index.as_raw(), this.lazy(hash));
1664 syntax_contexts.encode(&mut self.opaque),
1665 expn_data_table.encode(&mut self.opaque),
1666 expn_hash_table.encode(&mut self.opaque),
1670 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1671 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1674 let hir = tcx.hir();
1676 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1677 let stability = tcx.lookup_stability(CRATE_DEF_ID);
1679 self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1680 let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1681 for (i, span) in spans.into_iter().enumerate() {
1682 let span = self.lazy(span);
1683 self.tables.proc_macro_quoted_spans.set(i, span);
1686 self.tables.opt_def_kind.set(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1687 record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1688 self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1689 let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|def_id| def_id.local_def_index);
1690 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
1691 if let Some(stability) = stability {
1692 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1694 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1696 // Normally, this information is encoded when we walk the items
1697 // defined in this crate. However, we skip doing that for proc-macro crates,
1698 // so we manually encode just the information that we need
1699 for &proc_macro in &tcx.resolutions(()).proc_macros {
1700 let id = proc_macro;
1701 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1702 let mut name = hir.name(proc_macro);
1703 let span = hir.span(proc_macro);
1704 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1705 // so downstream crates need access to them.
1706 let attrs = hir.attrs(proc_macro);
1707 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1709 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1711 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1712 // This unwrap chain should have been checked by the proc-macro harness.
1713 name = attr.meta_item_list().unwrap()[0]
1721 bug!("Unknown proc-macro type for item {:?}", id);
1724 let mut def_key = self.tcx.hir().def_key(id);
1725 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1727 let def_id = id.to_def_id();
1728 self.tables.opt_def_kind.set(def_id.index, DefKind::Macro(macro_kind));
1729 self.tables.proc_macro.set(def_id.index, macro_kind);
1730 self.encode_attrs(id);
1731 record!(self.tables.def_keys[def_id] <- def_key);
1732 record!(self.tables.def_ident_span[def_id] <- span);
1733 record!(self.tables.def_span[def_id] <- span);
1734 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1735 if let Some(stability) = stability {
1736 record!(self.tables.lookup_stability[def_id] <- stability);
1740 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1746 fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1747 empty_proc_macro!(self);
1748 self.lazy_array(self.tcx.debugger_visualizers(LOCAL_CRATE).iter())
1751 fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1752 empty_proc_macro!(self);
1759 let dep = CrateDep {
1760 name: self.tcx.crate_name(cnum),
1761 hash: self.tcx.crate_hash(cnum),
1762 host_hash: self.tcx.crate_host_hash(cnum),
1763 kind: self.tcx.dep_kind(cnum),
1764 extra_filename: self.tcx.extra_filename(cnum).clone(),
1768 .collect::<Vec<_>>();
1771 // Sanity-check the crate numbers
1772 let mut expected_cnum = 1;
1773 for &(n, _) in &deps {
1774 assert_eq!(n, CrateNum::new(expected_cnum));
1779 // We're just going to write a list of crate 'name-hash-version's, with
1780 // the assumption that they are numbered 1 to n.
1781 // FIXME (#2166): This is not nearly enough to support correct versioning
1782 // but is enough to get transitive crate dependencies working.
1783 self.lazy_array(deps.iter().map(|(_, dep)| dep))
1786 fn encode_lib_features(&mut self) -> LazyArray<(Symbol, Option<Symbol>)> {
1787 empty_proc_macro!(self);
1789 let lib_features = tcx.lib_features(());
1790 self.lazy_array(lib_features.to_vec())
1793 fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
1794 empty_proc_macro!(self);
1796 let implications = tcx.stability_implications(LOCAL_CRATE);
1797 self.lazy_array(implications.iter().map(|(k, v)| (*k, *v)))
1800 fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
1801 empty_proc_macro!(self);
1803 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1804 self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1807 fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
1808 empty_proc_macro!(self);
1809 let lang_items = self.tcx.lang_items().iter();
1810 self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
1811 def_id.as_local().map(|id| (id.local_def_index, lang_item))
1815 fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
1816 empty_proc_macro!(self);
1818 self.lazy_array(&tcx.lang_items().missing)
1821 fn encode_traits(&mut self) -> LazyArray<DefIndex> {
1822 empty_proc_macro!(self);
1823 self.lazy_array(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index))
1826 /// Encodes an index, mapping each trait to its (local) implementations.
1827 fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
1828 debug!("EncodeContext::encode_traits_and_impls()");
1829 empty_proc_macro!(self);
1831 let mut fx_hash_map: FxHashMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
1832 FxHashMap::default();
1834 for id in tcx.hir().items() {
1835 if matches!(tcx.def_kind(id.owner_id), DefKind::Impl) {
1836 if let Some(trait_ref) = tcx.impl_trait_ref(id.owner_id) {
1837 let trait_ref = trait_ref.subst_identity();
1839 let simplified_self_ty = fast_reject::simplify_type(
1841 trait_ref.self_ty(),
1842 TreatParams::AsInfer,
1846 .entry(trait_ref.def_id)
1848 .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
1853 let mut all_impls: Vec<_> = fx_hash_map.into_iter().collect();
1855 // Bring everything into deterministic order for hashing
1856 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1858 let all_impls: Vec<_> = all_impls
1860 .map(|(trait_def_id, mut impls)| {
1861 // Bring everything into deterministic order for hashing
1862 impls.sort_by_cached_key(|&(index, _)| {
1863 tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1867 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1868 impls: self.lazy_array(&impls),
1873 self.lazy_array(&all_impls)
1876 fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
1877 debug!("EncodeContext::encode_traits_and_impls()");
1878 empty_proc_macro!(self);
1880 let mut all_impls: Vec<_> = tcx.crate_inherent_impls(()).incoherent_impls.iter().collect();
1881 tcx.with_stable_hashing_context(|mut ctx| {
1882 all_impls.sort_by_cached_key(|&(&simp, _)| {
1883 let mut hasher = StableHasher::new();
1884 simp.hash_stable(&mut ctx, &mut hasher);
1885 hasher.finish::<Fingerprint>()
1888 let all_impls: Vec<_> = all_impls
1890 .map(|(&simp, impls)| {
1891 let mut impls: Vec<_> =
1892 impls.into_iter().map(|def_id| def_id.local_def_index).collect();
1893 impls.sort_by_cached_key(|&local_def_index| {
1894 tcx.hir().def_path_hash(LocalDefId { local_def_index })
1897 IncoherentImpls { self_ty: simp, impls: self.lazy_array(impls) }
1901 self.lazy_array(&all_impls)
1904 // Encodes all symbols exported from this crate into the metadata.
1906 // This pass is seeded off the reachability list calculated in the
1907 // middle::reachable module but filters out items that either don't have a
1908 // symbol associated with them (they weren't translated) or if they're an FFI
1909 // definition (as that's not defined in this crate).
1910 fn encode_exported_symbols(
1912 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
1913 ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
1914 empty_proc_macro!(self);
1915 // The metadata symbol name is special. It should not show up in
1916 // downstream crates.
1917 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1922 .filter(|&(exported_symbol, _)| match *exported_symbol {
1923 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1930 fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
1931 empty_proc_macro!(self);
1932 let formats = self.tcx.dependency_formats(());
1933 for (ty, arr) in formats.iter() {
1934 if *ty != CrateType::Dylib {
1937 return self.lazy_array(arr.iter().map(|slot| match *slot {
1938 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1940 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1941 Linkage::Static => Some(LinkagePreference::RequireStatic),
1947 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1950 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1953 hir::ForeignItemKind::Fn(_, ref names, _) => {
1954 self.tables.asyncness.set(def_id.index, hir::IsAsync::NotAsync);
1955 record_array!(self.tables.fn_arg_names[def_id] <- *names);
1956 let constness = if self.tcx.is_const_fn_raw(def_id) {
1957 hir::Constness::Const
1959 hir::Constness::NotConst
1961 self.tables.constness.set(def_id.index, constness);
1962 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1964 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => {}
1966 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1967 if tcx.is_intrinsic(def_id) {
1968 self.tables.is_intrinsic.set(def_id.index, ());
1974 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1975 impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1976 type NestedFilter = nested_filter::OnlyBodies;
1978 fn nested_visit_map(&mut self) -> Self::Map {
1981 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1982 intravisit::walk_expr(self, ex);
1983 self.encode_info_for_expr(ex);
1985 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1986 intravisit::walk_item(self, item);
1988 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1989 _ => self.encode_info_for_item(item.owner_id.to_def_id(), item),
1992 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1993 intravisit::walk_foreign_item(self, ni);
1994 self.encode_info_for_foreign_item(ni.owner_id.to_def_id(), ni);
1996 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1997 intravisit::walk_generics(self, generics);
1998 self.encode_info_for_generics(generics);
2002 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
2003 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
2004 for param in generics.params {
2006 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => {}
2007 hir::GenericParamKind::Const { ref default, .. } => {
2008 let def_id = param.def_id.to_def_id();
2009 if default.is_some() {
2010 record!(self.tables.const_param_default[def_id] <- self.tcx.const_param_default(def_id))
2017 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
2018 if let hir::ExprKind::Closure(closure) = expr.kind {
2019 self.encode_info_for_closure(closure.def_id);
2024 /// Used to prefetch queries which will be needed later by metadata encoding.
2025 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2026 fn prefetch_mir(tcx: TyCtxt<'_>) {
2027 if !tcx.sess.opts.output_types.should_codegen() {
2028 // We won't emit MIR, so don't prefetch it.
2032 par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2033 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2036 tcx.ensure().mir_for_ctfe(def_id);
2039 tcx.ensure().optimized_mir(def_id);
2041 if encode_opt || encode_const {
2042 tcx.ensure().promoted_mir(def_id);
2047 // NOTE(eddyb) The following comment was preserved for posterity, even
2048 // though it's no longer relevant as EBML (which uses nested & tagged
2049 // "documents") was replaced with a scheme that can't go out of bounds.
2051 // And here we run into yet another obscure archive bug: in which metadata
2052 // loaded from archives may have trailing garbage bytes. Awhile back one of
2053 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2054 // and opt) by having ebml generate an out-of-bounds panic when looking at
2057 // Upon investigation it turned out that the metadata file inside of an rlib
2058 // (and ar archive) was being corrupted. Some compilations would generate a
2059 // metadata file which would end in a few extra bytes, while other
2060 // compilations would not have these extra bytes appended to the end. These
2061 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2062 // being interpreted causing the out-of-bounds.
2064 // The root cause of why these extra bytes were appearing was never
2065 // discovered, and in the meantime the solution we're employing is to insert
2066 // the length of the metadata to the start of the metadata. Later on this
2067 // will allow us to slice the metadata to the precise length that we just
2068 // generated regardless of trailing bytes that end up in it.
2070 pub struct EncodedMetadata {
2071 // The declaration order matters because `mmap` should be dropped before `_temp_dir`.
2073 // We need to carry MaybeTempDir to avoid deleting the temporary
2074 // directory while accessing the Mmap.
2075 _temp_dir: Option<MaybeTempDir>,
2078 impl EncodedMetadata {
2080 pub fn from_path(path: PathBuf, temp_dir: Option<MaybeTempDir>) -> std::io::Result<Self> {
2081 let file = std::fs::File::open(&path)?;
2082 let file_metadata = file.metadata()?;
2083 if file_metadata.len() == 0 {
2084 return Ok(Self { mmap: None, _temp_dir: None });
2086 let mmap = unsafe { Some(Mmap::map(file)?) };
2087 Ok(Self { mmap, _temp_dir: temp_dir })
2091 pub fn raw_data(&self) -> &[u8] {
2092 self.mmap.as_deref().unwrap_or_default()
2096 impl<S: Encoder> Encodable<S> for EncodedMetadata {
2097 fn encode(&self, s: &mut S) {
2098 let slice = self.raw_data();
2103 impl<D: Decoder> Decodable<D> for EncodedMetadata {
2104 fn decode(d: &mut D) -> Self {
2105 let len = d.read_usize();
2106 let mmap = if len > 0 {
2107 let mut mmap = MmapMut::map_anon(len).unwrap();
2109 (&mut mmap[..]).write(&[d.read_u8()]).unwrap();
2111 mmap.flush().unwrap();
2112 Some(mmap.make_read_only().unwrap())
2117 Self { mmap, _temp_dir: None }
2121 pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path) {
2122 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2124 // Since encoding metadata is not in a query, and nothing is cached,
2125 // there's no need to do dep-graph tracking for any of it.
2126 tcx.dep_graph.assert_ignored();
2129 || encode_metadata_impl(tcx, path),
2131 if tcx.sess.threads() == 1 {
2134 // Prefetch some queries used by metadata encoding.
2135 // This is not necessary for correctness, but is only done for performance reasons.
2136 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2137 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2142 fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) {
2143 let mut encoder = opaque::FileEncoder::new(path)
2144 .unwrap_or_else(|err| tcx.sess.emit_fatal(FailCreateFileEncoder { err }));
2145 encoder.emit_raw_bytes(METADATA_HEADER);
2147 // Will be filled with the root position after encoding everything.
2148 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2150 let source_map_files = tcx.sess.source_map().files();
2151 let source_file_cache = (source_map_files[0].clone(), 0);
2152 let required_source_files = Some(FxIndexSet::default());
2153 drop(source_map_files);
2155 let hygiene_ctxt = HygieneEncodeContext::default();
2157 let mut ecx = EncodeContext {
2160 feat: tcx.features(),
2161 tables: Default::default(),
2162 lazy_state: LazyState::NoNode,
2163 type_shorthands: Default::default(),
2164 predicate_shorthands: Default::default(),
2166 interpret_allocs: Default::default(),
2167 required_source_files,
2168 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2169 hygiene_ctxt: &hygiene_ctxt,
2170 symbol_table: Default::default(),
2173 // Encode the rustc version string in a predictable location.
2174 rustc_version().encode(&mut ecx);
2176 // Encode all the entries and extra information in the crate,
2177 // culminating in the `CrateRoot` which points to all of it.
2178 let root = ecx.encode_crate_root();
2182 let mut file = ecx.opaque.file();
2183 // We will return to this position after writing the root position.
2184 let pos_before_seek = file.stream_position().unwrap();
2186 // Encode the root position.
2187 let header = METADATA_HEADER.len();
2188 file.seek(std::io::SeekFrom::Start(header as u64))
2189 .unwrap_or_else(|err| tcx.sess.emit_fatal(FailSeekFile { err }));
2190 let pos = root.position.get();
2191 file.write_all(&[(pos >> 24) as u8, (pos >> 16) as u8, (pos >> 8) as u8, (pos >> 0) as u8])
2192 .unwrap_or_else(|err| tcx.sess.emit_fatal(FailWriteFile { err }));
2194 // Return to the position where we are before writing the root position.
2195 file.seek(std::io::SeekFrom::Start(pos_before_seek)).unwrap();
2197 // Record metadata size for self-profiling
2198 tcx.prof.artifact_size(
2201 file.metadata().unwrap().len() as u64,
2205 pub fn provide(providers: &mut Providers) {
2206 *providers = Providers {
2207 traits_in_crate: |tcx, cnum| {
2208 assert_eq!(cnum, LOCAL_CRATE);
2210 let mut traits = Vec::new();
2211 for id in tcx.hir().items() {
2212 if matches!(tcx.def_kind(id.owner_id), DefKind::Trait | DefKind::TraitAlias) {
2213 traits.push(id.owner_id.to_def_id())
2217 // Bring everything into deterministic order.
2218 traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
2219 tcx.arena.alloc_slice(&traits)