]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/encoder.rs
Rollup merge of #103025 - notriddle:notriddle/search-container-star, r=GuillaumeGomez
[rust.git] / compiler / rustc_metadata / src / rmeta / encoder.rs
1 use crate::errors::{FailCreateFileEncoder, FailSeekFile, FailWriteFile};
2 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
3 use crate::rmeta::table::TableBuilder;
4 use crate::rmeta::*;
5
6 use rustc_data_structures::fingerprint::Fingerprint;
7 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
8 use rustc_data_structures::memmap::{Mmap, MmapMut};
9 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
10 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
11 use rustc_data_structures::temp_dir::MaybeTempDir;
12 use rustc_hir as hir;
13 use rustc_hir::def::DefKind;
14 use rustc_hir::def_id::{
15     CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
16 };
17 use rustc_hir::definitions::DefPathData;
18 use rustc_hir::intravisit::{self, Visitor};
19 use rustc_hir::lang_items;
20 use rustc_middle::hir::nested_filter;
21 use rustc_middle::middle::dependency_format::Linkage;
22 use rustc_middle::middle::exported_symbols::{
23     metadata_symbol_name, ExportedSymbol, SymbolExportInfo,
24 };
25 use rustc_middle::mir::interpret;
26 use rustc_middle::traits::specialization_graph;
27 use rustc_middle::ty::codec::TyEncoder;
28 use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams};
29 use rustc_middle::ty::query::Providers;
30 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
31 use rustc_middle::util::common::to_readable_str;
32 use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder};
33 use rustc_session::config::CrateType;
34 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
35 use rustc_span::hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind};
36 use rustc_span::symbol::{sym, Symbol};
37 use rustc_span::{
38     self, DebuggerVisualizerFile, ExternalSource, FileName, SourceFile, Span, SyntaxContext,
39 };
40 use rustc_target::abi::VariantIdx;
41 use std::borrow::Borrow;
42 use std::collections::hash_map::Entry;
43 use std::hash::Hash;
44 use std::io::{Read, Seek, Write};
45 use std::iter;
46 use std::num::NonZeroUsize;
47 use std::path::{Path, PathBuf};
48
49 pub(super) struct EncodeContext<'a, 'tcx> {
50     opaque: opaque::FileEncoder,
51     tcx: TyCtxt<'tcx>,
52     feat: &'tcx rustc_feature::Features,
53
54     tables: TableBuilders,
55
56     lazy_state: LazyState,
57     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
58     predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
59
60     interpret_allocs: FxIndexSet<interpret::AllocId>,
61
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>>,
73     is_proc_macro: bool,
74     hygiene_ctxt: &'a HygieneEncodeContext,
75     symbol_table: FxHashMap<Symbol, usize>,
76 }
77
78 /// If the current crate is a proc-macro, returns early with `Lazy: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 {
82     ($self:ident) => {
83         if $self.is_proc_macro {
84             return LazyArray::empty();
85         }
86     };
87 }
88
89 macro_rules! encoder_methods {
90     ($($name:ident($ty:ty);)*) => {
91         $(fn $name(&mut self, value: $ty) {
92             self.opaque.$name(value)
93         })*
94     }
95 }
96
97 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
98     encoder_methods! {
99         emit_usize(usize);
100         emit_u128(u128);
101         emit_u64(u64);
102         emit_u32(u32);
103         emit_u16(u16);
104         emit_u8(u8);
105
106         emit_isize(isize);
107         emit_i128(i128);
108         emit_i64(i64);
109         emit_i32(i32);
110         emit_i16(i16);
111         emit_i8(i8);
112
113         emit_bool(bool);
114         emit_f64(f64);
115         emit_f32(f32);
116         emit_char(char);
117         emit_str(&str);
118         emit_raw_bytes(&[u8]);
119     }
120 }
121
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);
125     }
126 }
127
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)
133         }
134     }
135 }
136
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);
141     }
142 }
143
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 {:?} for proc-macro crate", self);
148         }
149         s.emit_u32(self.as_u32());
150     }
151 }
152
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());
156     }
157 }
158
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());
162     }
163 }
164
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);
168     }
169 }
170
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);
179         }
180         self.krate.encode(s);
181         self.local_id.encode(s);
182     }
183 }
184
185 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
186     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
187         let span = self.data();
188
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.
194         //
195         // This can show up in two ways:
196         //
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.
201         //
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.
207         //
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.
211         //
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.
216         //
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.
220         if s.is_proc_macro {
221             SyntaxContext::root().encode(s);
222         } else {
223             span.ctxt.encode(s);
224         }
225
226         if self.is_dummy() {
227             return TAG_PARTIAL_SPAN.encode(s);
228         }
229
230         // The Span infrastructure should make sure that this invariant holds:
231         debug_assert!(span.lo <= span.hi);
232
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);
238         }
239         let (ref source_file, source_file_index) = s.source_file_cache;
240         debug_assert!(source_file.contains(span.lo));
241
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);
246         }
247
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.
258         //
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.
271             //
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),
279                 }
280             };
281
282             (TAG_VALID_SPAN_FOREIGN, metadata_index)
283         } else {
284             // Record the fact that we need to encode the data for this `SourceFile`
285             let source_files =
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");
290
291             (TAG_VALID_SPAN_LOCAL, metadata_index)
292         };
293
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;
297
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;
301
302         tag.encode(s);
303         lo.encode(s);
304         len.encode(s);
305
306         // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
307         metadata_index.encode(s);
308
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;
313             cnum.encode(s);
314         }
315     }
316 }
317
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());
324         } else {
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();
330                     o.insert(pos);
331                     s.emit_str(self.as_str());
332                 }
333                 Entry::Occupied(o) => {
334                     let x = o.get().clone();
335                     s.emit_u8(SYMBOL_OFFSET);
336                     s.emit_usize(x);
337                 }
338             }
339         }
340     }
341 }
342
343 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
344     const CLEAR_CROSS_CRATE: bool = true;
345
346     type I = TyCtxt<'tcx>;
347
348     fn position(&self) -> usize {
349         self.opaque.position()
350     }
351
352     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
353         &mut self.type_shorthands
354     }
355
356     fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
357         &mut self.predicate_shorthands
358     }
359
360     fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
361         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
362
363         index.encode(self);
364     }
365 }
366
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) => {{
371         {
372             let value = $value;
373             let lazy = $self.lazy(value);
374             $self.$tables.$table.set($def_id.index, lazy);
375         }
376     }};
377 }
378
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) => {{
383         {
384             let value = $value;
385             let lazy = $self.lazy_array(value);
386             $self.$tables.$table.set($def_id.index, lazy);
387         }
388     }};
389 }
390
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);
399                 start - pos
400             }
401             LazyState::Previous(last_pos) => {
402                 assert!(
403                     last_pos <= position,
404                     "make sure that the calls to `lazy*` \
405                      are in the same order as the metadata fields",
406                 );
407                 position.get() - last_pos.get()
408             }
409         };
410         self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap());
411         self.emit_usize(distance);
412     }
413
414     fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
415     where
416         T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
417     {
418         let pos = NonZeroUsize::new(self.position()).unwrap();
419
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;
424
425         assert!(pos.get() <= self.position());
426
427         LazyValue::from_position(pos)
428     }
429
430     fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
431         &mut self,
432         values: I,
433     ) -> LazyArray<T>
434     where
435         T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
436     {
437         let pos = NonZeroUsize::new(self.position()).unwrap();
438
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;
443
444         assert!(pos.get() <= self.position());
445
446         LazyArray::from_position_and_num_elems(pos, len)
447     }
448
449     fn encode_info_for_items(&mut self) {
450         self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
451
452         // Proc-macro crates only export proc-macro items, which are looked
453         // up using `proc_macro_data`
454         if self.is_proc_macro {
455             return;
456         }
457
458         self.tcx.hir().visit_all_item_likes_in_crate(self);
459     }
460
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))
466             {
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);
471             }
472         } else {
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);
477             }
478         }
479     }
480
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()))
483     }
484
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();
488
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
491         // is done.
492         let required_source_files = self.required_source_files.take().unwrap();
493
494         let working_directory = &self.tcx.sess.opts.working_dir;
495
496         let mut adapted = TableBuilder::default();
497
498         // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
499         //
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);
506
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.
511             //
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
517                         .path_mapping()
518                         .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
519
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>()
527                         };
528                         Lrc::new(adapted)
529                     } else {
530                         // Nothing to adapt
531                         source_file.clone()
532                     }
533                 }
534                 // expanded code, not from a file
535                 _ => source_file.clone(),
536             };
537
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;
546             }
547
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));
551         }
552
553         adapted.encode(&mut self.opaque)
554     }
555
556     fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
557         let tcx = self.tcx;
558         let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
559
560         macro_rules! stat {
561             ($label:literal, $f:expr) => {{
562                 let orig_pos = self.position();
563                 let res = $f();
564                 stats.push(($label, self.position() - orig_pos));
565                 res
566             }};
567         }
568
569         // We have already encoded some things. Get their combined size from the current position.
570         stats.push(("preamble", self.position()));
571
572         let (crate_deps, dylib_dependency_formats) =
573             stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
574
575         let lib_features = stat!("lib-features", || self.encode_lib_features());
576
577         let stability_implications =
578             stat!("stability-implications", || self.encode_stability_implications());
579
580         let (lang_items, lang_items_missing) = stat!("lang-items", || {
581             (self.encode_lang_items(), self.encode_lang_items_missing())
582         });
583
584         let diagnostic_items = stat!("diagnostic-items", || self.encode_diagnostic_items());
585
586         let native_libraries = stat!("native-libs", || self.encode_native_libraries());
587
588         let foreign_modules = stat!("foreign-modules", || self.encode_foreign_modules());
589
590         _ = stat!("def-path-table", || self.encode_def_path_table());
591
592         // Encode the def IDs of traits, for rustdoc and diagnostics.
593         let traits = stat!("traits", || self.encode_traits());
594
595         // Encode the def IDs of impls, for coherence checking.
596         let impls = stat!("impls", || self.encode_impls());
597
598         let incoherent_impls = stat!("incoherent-impls", || self.encode_incoherent_impls());
599
600         _ = stat!("mir", || self.encode_mir());
601
602         _ = stat!("items", || {
603             self.encode_def_ids();
604             self.encode_info_for_items();
605         });
606
607         let interpret_alloc_index = stat!("interpret-alloc-index", || {
608             let mut interpret_alloc_index = Vec::new();
609             let mut n = 0;
610             trace!("beginning to encode alloc ids");
611             loop {
612                 let new_n = self.interpret_allocs.len();
613                 // if we have found new ids, serialize those, too
614                 if n == new_n {
615                     // otherwise, abort
616                     break;
617                 }
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);
624                 }
625                 n = new_n;
626             }
627             self.lazy_array(interpret_alloc_index)
628         });
629
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());
634
635         let tables = stat!("tables", || self.tables.encode(&mut self.opaque));
636
637         let debugger_visualizers =
638             stat!("debugger-visualizers", || self.encode_debugger_visualizers());
639
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))
644         });
645
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());
653
654         let def_path_hash_map = stat!("def-path-hash-map", || self.encode_def_path_hash_map());
655
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());
659
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_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
673                 has_default_lib_allocator: tcx
674                     .sess
675                     .contains_name(&attrs, sym::default_lib_allocator),
676                 proc_macro_data,
677                 debugger_visualizers,
678                 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
679                 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
680                 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
681                 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
682                 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
683                 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
684                 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
685
686                 crate_deps,
687                 dylib_dependency_formats,
688                 lib_features,
689                 stability_implications,
690                 lang_items,
691                 diagnostic_items,
692                 lang_items_missing,
693                 native_libraries,
694                 foreign_modules,
695                 source_map,
696                 traits,
697                 impls,
698                 incoherent_impls,
699                 exported_symbols,
700                 interpret_alloc_index,
701                 tables,
702                 syntax_contexts,
703                 expn_data,
704                 expn_hashes,
705                 def_path_hash_map,
706             })
707         });
708
709         let total_bytes = self.position();
710
711         let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
712         assert_eq!(total_bytes, computed_total_bytes);
713
714         if tcx.sess.meta_stats() {
715             self.opaque.flush();
716
717             // Rewind and re-read all the metadata to count the zero bytes we wrote.
718             let pos_before_rewind = self.opaque.file().stream_position().unwrap();
719             let mut zero_bytes = 0;
720             self.opaque.file().rewind().unwrap();
721             let file = std::io::BufReader::new(self.opaque.file());
722             for e in file.bytes() {
723                 if e.unwrap() == 0 {
724                     zero_bytes += 1;
725                 }
726             }
727             assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
728
729             stats.sort_by_key(|&(_, usize)| usize);
730
731             let prefix = "meta-stats";
732             let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
733
734             eprintln!("{} METADATA STATS", prefix);
735             eprintln!("{} {:<23}{:>10}", prefix, "Section", "Size");
736             eprintln!(
737                 "{} ----------------------------------------------------------------",
738                 prefix
739             );
740             for (label, size) in stats {
741                 eprintln!(
742                     "{} {:<23}{:>10} ({:4.1}%)",
743                     prefix,
744                     label,
745                     to_readable_str(size),
746                     perc(size)
747                 );
748             }
749             eprintln!(
750                 "{} ----------------------------------------------------------------",
751                 prefix
752             );
753             eprintln!(
754                 "{} {:<23}{:>10} (of which {:.1}% are zero bytes)",
755                 prefix,
756                 "Total",
757                 to_readable_str(total_bytes),
758                 perc(zero_bytes)
759             );
760             eprintln!("{}", prefix);
761         }
762
763         root
764     }
765 }
766
767 fn should_encode_visibility(def_kind: DefKind) -> bool {
768     match def_kind {
769         DefKind::Mod
770         | DefKind::Struct
771         | DefKind::Union
772         | DefKind::Enum
773         | DefKind::Variant
774         | DefKind::Trait
775         | DefKind::TyAlias
776         | DefKind::ForeignTy
777         | DefKind::TraitAlias
778         | DefKind::AssocTy
779         | DefKind::Fn
780         | DefKind::Const
781         | DefKind::Static(..)
782         | DefKind::Ctor(..)
783         | DefKind::AssocFn
784         | DefKind::AssocConst
785         | DefKind::Macro(..)
786         | DefKind::Use
787         | DefKind::ForeignMod
788         | DefKind::OpaqueTy
789         | DefKind::ImplTraitPlaceholder
790         | DefKind::Impl
791         | DefKind::Field => true,
792         DefKind::TyParam
793         | DefKind::ConstParam
794         | DefKind::LifetimeParam
795         | DefKind::AnonConst
796         | DefKind::InlineConst
797         | DefKind::GlobalAsm
798         | DefKind::Closure
799         | DefKind::Generator
800         | DefKind::ExternCrate => false,
801     }
802 }
803
804 fn should_encode_stability(def_kind: DefKind) -> bool {
805     match def_kind {
806         DefKind::Mod
807         | DefKind::Ctor(..)
808         | DefKind::Variant
809         | DefKind::Field
810         | DefKind::Struct
811         | DefKind::AssocTy
812         | DefKind::AssocFn
813         | DefKind::AssocConst
814         | DefKind::TyParam
815         | DefKind::ConstParam
816         | DefKind::Static(..)
817         | DefKind::Const
818         | DefKind::Fn
819         | DefKind::ForeignMod
820         | DefKind::TyAlias
821         | DefKind::OpaqueTy
822         | DefKind::ImplTraitPlaceholder
823         | DefKind::Enum
824         | DefKind::Union
825         | DefKind::Impl
826         | DefKind::Trait
827         | DefKind::TraitAlias
828         | DefKind::Macro(..)
829         | DefKind::ForeignTy => true,
830         DefKind::Use
831         | DefKind::LifetimeParam
832         | DefKind::AnonConst
833         | DefKind::InlineConst
834         | DefKind::GlobalAsm
835         | DefKind::Closure
836         | DefKind::Generator
837         | DefKind::ExternCrate => false,
838     }
839 }
840
841 /// Whether we should encode MIR.
842 ///
843 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
844 /// We want to avoid this work when not required. Therefore:
845 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
846 /// - we skip `optimized_mir` for check runs.
847 ///
848 /// Return a pair, resp. for CTFE and for LLVM.
849 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
850     match tcx.def_kind(def_id) {
851         // Constructors
852         DefKind::Ctor(_, _) => {
853             let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
854                 || tcx.sess.opts.unstable_opts.always_encode_mir;
855             (true, mir_opt_base)
856         }
857         // Constants
858         DefKind::AnonConst
859         | DefKind::InlineConst
860         | DefKind::AssocConst
861         | DefKind::Static(..)
862         | DefKind::Const => (true, false),
863         // Full-fledged functions
864         DefKind::AssocFn | DefKind::Fn => {
865             let generics = tcx.generics_of(def_id);
866             let needs_inline = (generics.requires_monomorphization(tcx)
867                 || tcx.codegen_fn_attrs(def_id).requests_inline())
868                 && tcx.sess.opts.output_types.should_codegen();
869             // The function has a `const` modifier or is in a `#[const_trait]`.
870             let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id())
871                 || tcx.is_const_default_method(def_id.to_def_id());
872             let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
873             (is_const_fn, needs_inline || always_encode_mir)
874         }
875         // Closures can't be const fn.
876         DefKind::Closure => {
877             let generics = tcx.generics_of(def_id);
878             let needs_inline = (generics.requires_monomorphization(tcx)
879                 || tcx.codegen_fn_attrs(def_id).requests_inline())
880                 && tcx.sess.opts.output_types.should_codegen();
881             let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
882             (false, needs_inline || always_encode_mir)
883         }
884         // Generators require optimized MIR to compute layout.
885         DefKind::Generator => (false, true),
886         // The others don't have MIR.
887         _ => (false, false),
888     }
889 }
890
891 fn should_encode_variances(def_kind: DefKind) -> bool {
892     match def_kind {
893         DefKind::Struct
894         | DefKind::Union
895         | DefKind::Enum
896         | DefKind::Variant
897         | DefKind::Fn
898         | DefKind::Ctor(..)
899         | DefKind::AssocFn => true,
900         DefKind::Mod
901         | DefKind::Field
902         | DefKind::AssocTy
903         | DefKind::AssocConst
904         | DefKind::TyParam
905         | DefKind::ConstParam
906         | DefKind::Static(..)
907         | DefKind::Const
908         | DefKind::ForeignMod
909         | DefKind::TyAlias
910         | DefKind::OpaqueTy
911         | DefKind::ImplTraitPlaceholder
912         | DefKind::Impl
913         | DefKind::Trait
914         | DefKind::TraitAlias
915         | DefKind::Macro(..)
916         | DefKind::ForeignTy
917         | DefKind::Use
918         | DefKind::LifetimeParam
919         | DefKind::AnonConst
920         | DefKind::InlineConst
921         | DefKind::GlobalAsm
922         | DefKind::Closure
923         | DefKind::Generator
924         | DefKind::ExternCrate => false,
925     }
926 }
927
928 fn should_encode_generics(def_kind: DefKind) -> bool {
929     match def_kind {
930         DefKind::Struct
931         | DefKind::Union
932         | DefKind::Enum
933         | DefKind::Variant
934         | DefKind::Trait
935         | DefKind::TyAlias
936         | DefKind::ForeignTy
937         | DefKind::TraitAlias
938         | DefKind::AssocTy
939         | DefKind::Fn
940         | DefKind::Const
941         | DefKind::Static(..)
942         | DefKind::Ctor(..)
943         | DefKind::AssocFn
944         | DefKind::AssocConst
945         | DefKind::AnonConst
946         | DefKind::InlineConst
947         | DefKind::OpaqueTy
948         | DefKind::ImplTraitPlaceholder
949         | DefKind::Impl
950         | DefKind::Field
951         | DefKind::TyParam
952         | DefKind::Closure
953         | DefKind::Generator => true,
954         DefKind::Mod
955         | DefKind::ForeignMod
956         | DefKind::ConstParam
957         | DefKind::Macro(..)
958         | DefKind::Use
959         | DefKind::LifetimeParam
960         | DefKind::GlobalAsm
961         | DefKind::ExternCrate => false,
962     }
963 }
964
965 fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
966     match def_kind {
967         DefKind::Struct
968         | DefKind::Union
969         | DefKind::Enum
970         | DefKind::Variant
971         | DefKind::Ctor(..)
972         | DefKind::Field
973         | DefKind::Fn
974         | DefKind::Const
975         | DefKind::Static(..)
976         | DefKind::TyAlias
977         | DefKind::OpaqueTy
978         | DefKind::ForeignTy
979         | DefKind::Impl
980         | DefKind::AssocFn
981         | DefKind::AssocConst
982         | DefKind::Closure
983         | DefKind::Generator
984         | DefKind::ConstParam
985         | DefKind::AnonConst
986         | DefKind::InlineConst => true,
987
988         DefKind::ImplTraitPlaceholder => {
989             let parent_def_id = tcx.impl_trait_in_trait_parent(def_id.to_def_id());
990             let assoc_item = tcx.associated_item(parent_def_id);
991             match assoc_item.container {
992                 // Always encode an RPIT in an impl fn, since it always has a body
993                 ty::AssocItemContainer::ImplContainer => true,
994                 ty::AssocItemContainer::TraitContainer => {
995                     // Encode an RPIT for a trait only if the trait has a default body
996                     assoc_item.defaultness(tcx).has_value()
997                 }
998             }
999         }
1000
1001         DefKind::AssocTy => {
1002             let assoc_item = tcx.associated_item(def_id);
1003             match assoc_item.container {
1004                 ty::AssocItemContainer::ImplContainer => true,
1005                 ty::AssocItemContainer::TraitContainer => assoc_item.defaultness(tcx).has_value(),
1006             }
1007         }
1008         DefKind::TyParam => {
1009             let hir::Node::GenericParam(param) = tcx.hir().get_by_def_id(def_id) else { bug!() };
1010             let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() };
1011             default.is_some()
1012         }
1013
1014         DefKind::Trait
1015         | DefKind::TraitAlias
1016         | DefKind::Mod
1017         | DefKind::ForeignMod
1018         | DefKind::Macro(..)
1019         | DefKind::Use
1020         | DefKind::LifetimeParam
1021         | DefKind::GlobalAsm
1022         | DefKind::ExternCrate => false,
1023     }
1024 }
1025
1026 fn should_encode_const(def_kind: DefKind) -> bool {
1027     match def_kind {
1028         DefKind::Const | DefKind::AssocConst | DefKind::AnonConst => true,
1029
1030         DefKind::Struct
1031         | DefKind::Union
1032         | DefKind::Enum
1033         | DefKind::Variant
1034         | DefKind::Ctor(..)
1035         | DefKind::Field
1036         | DefKind::Fn
1037         | DefKind::Static(..)
1038         | DefKind::TyAlias
1039         | DefKind::OpaqueTy
1040         | DefKind::ImplTraitPlaceholder
1041         | DefKind::ForeignTy
1042         | DefKind::Impl
1043         | DefKind::AssocFn
1044         | DefKind::Closure
1045         | DefKind::Generator
1046         | DefKind::ConstParam
1047         | DefKind::InlineConst
1048         | DefKind::AssocTy
1049         | DefKind::TyParam
1050         | DefKind::Trait
1051         | DefKind::TraitAlias
1052         | DefKind::Mod
1053         | DefKind::ForeignMod
1054         | DefKind::Macro(..)
1055         | DefKind::Use
1056         | DefKind::LifetimeParam
1057         | DefKind::GlobalAsm
1058         | DefKind::ExternCrate => false,
1059     }
1060 }
1061
1062 fn should_encode_constness(def_kind: DefKind) -> bool {
1063     match def_kind {
1064         DefKind::Struct
1065         | DefKind::Union
1066         | DefKind::Enum
1067         | DefKind::Trait
1068         | DefKind::AssocTy
1069         | DefKind::Fn
1070         | DefKind::Const
1071         | DefKind::Static(..)
1072         | DefKind::Ctor(..)
1073         | DefKind::AssocFn
1074         | DefKind::AssocConst
1075         | DefKind::AnonConst
1076         | DefKind::InlineConst
1077         | DefKind::OpaqueTy
1078         | DefKind::ImplTraitPlaceholder
1079         | DefKind::Impl
1080         | DefKind::Closure
1081         | DefKind::Generator
1082         | DefKind::TyAlias => true,
1083         DefKind::Variant
1084         | DefKind::TraitAlias
1085         | DefKind::ForeignTy
1086         | DefKind::Field
1087         | DefKind::TyParam
1088         | DefKind::Mod
1089         | DefKind::ForeignMod
1090         | DefKind::ConstParam
1091         | DefKind::Macro(..)
1092         | DefKind::Use
1093         | DefKind::LifetimeParam
1094         | DefKind::GlobalAsm
1095         | DefKind::ExternCrate => false,
1096     }
1097 }
1098
1099 fn should_encode_trait_impl_trait_tys<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1100     if tcx.def_kind(def_id) != DefKind::AssocFn {
1101         return false;
1102     }
1103
1104     let Some(item) = tcx.opt_associated_item(def_id) else { return false; };
1105     if item.container != ty::AssocItemContainer::ImplContainer {
1106         return false;
1107     }
1108
1109     let Some(trait_item_def_id) = item.trait_item_def_id else { return false; };
1110
1111     // FIXME(RPITIT): This does a somewhat manual walk through the signature
1112     // of the trait fn to look for any RPITITs, but that's kinda doing a lot
1113     // of work. We can probably remove this when we refactor RPITITs to be
1114     // associated types.
1115     tcx.fn_sig(trait_item_def_id).skip_binder().output().walk().any(|arg| {
1116         if let ty::GenericArgKind::Type(ty) = arg.unpack()
1117             && let ty::Projection(data) = ty.kind()
1118             && tcx.def_kind(data.item_def_id) == DefKind::ImplTraitPlaceholder
1119         {
1120             true
1121         } else {
1122             false
1123         }
1124     })
1125 }
1126
1127 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1128     fn encode_attrs(&mut self, def_id: LocalDefId) {
1129         let mut attrs = self
1130             .tcx
1131             .hir()
1132             .attrs(self.tcx.hir().local_def_id_to_hir_id(def_id))
1133             .iter()
1134             .filter(|attr| !rustc_feature::is_builtin_only_local(attr.name_or_empty()));
1135
1136         record_array!(self.tables.attributes[def_id.to_def_id()] <- attrs.clone());
1137         if attrs.any(|attr| attr.may_have_doc_links()) {
1138             self.tables.may_have_doc_links.set(def_id.local_def_index, ());
1139         }
1140     }
1141
1142     fn encode_def_ids(&mut self) {
1143         if self.is_proc_macro {
1144             return;
1145         }
1146         let tcx = self.tcx;
1147         for local_id in tcx.iter_local_def_id() {
1148             let def_id = local_id.to_def_id();
1149             let def_kind = tcx.opt_def_kind(local_id);
1150             let Some(def_kind) = def_kind else { continue };
1151             self.tables.opt_def_kind.set(def_id.index, def_kind);
1152             let def_span = tcx.def_span(local_id);
1153             record!(self.tables.def_span[def_id] <- def_span);
1154             self.encode_attrs(local_id);
1155             record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1156             if let Some(ident_span) = tcx.def_ident_span(def_id) {
1157                 record!(self.tables.def_ident_span[def_id] <- ident_span);
1158             }
1159             if def_kind.has_codegen_attrs() {
1160                 record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1161             }
1162             if should_encode_visibility(def_kind) {
1163                 let vis =
1164                     self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);
1165                 record!(self.tables.visibility[def_id] <- vis);
1166             }
1167             if should_encode_stability(def_kind) {
1168                 self.encode_stability(def_id);
1169                 self.encode_const_stability(def_id);
1170                 self.encode_default_body_stability(def_id);
1171                 self.encode_deprecation(def_id);
1172             }
1173             if should_encode_variances(def_kind) {
1174                 let v = self.tcx.variances_of(def_id);
1175                 record_array!(self.tables.variances_of[def_id] <- v);
1176             }
1177             if should_encode_generics(def_kind) {
1178                 let g = tcx.generics_of(def_id);
1179                 record!(self.tables.generics_of[def_id] <- g);
1180                 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1181                 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1182                 if !inferred_outlives.is_empty() {
1183                     record_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1184                 }
1185             }
1186             if should_encode_type(tcx, local_id, def_kind) {
1187                 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1188             }
1189             if let DefKind::TyParam = def_kind {
1190                 let default = self.tcx.object_lifetime_default(def_id);
1191                 record!(self.tables.object_lifetime_default[def_id] <- default);
1192             }
1193             if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1194                 record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id));
1195             }
1196             if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1197                 let params_in_repr = self.tcx.params_in_repr(def_id);
1198                 record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1199             }
1200             if should_encode_trait_impl_trait_tys(tcx, def_id)
1201                 && let Ok(table) = self.tcx.collect_trait_impl_trait_tys(def_id)
1202             {
1203                 record!(self.tables.trait_impl_trait_tys[def_id] <- table);
1204             }
1205             if should_encode_constness(def_kind) {
1206                 self.tables.constness.set(def_id.index, tcx.constness(def_id));
1207             }
1208         }
1209         let inherent_impls = tcx.crate_inherent_impls(());
1210         for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
1211             if implementations.is_empty() {
1212                 continue;
1213             }
1214             record_array!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1215                 assert!(def_id.is_local());
1216                 def_id.index
1217             }));
1218         }
1219     }
1220
1221     fn encode_enum_variant_info(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1222         let tcx = self.tcx;
1223         let variant = &def.variant(index);
1224         let def_id = variant.def_id;
1225         debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1226
1227         let data = VariantData {
1228             ctor_kind: variant.ctor_kind,
1229             discr: variant.discr,
1230             ctor: variant.ctor_def_id.map(|did| did.index),
1231             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1232         };
1233
1234         record!(self.tables.variant_data[def_id] <- data);
1235         record_array!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1236             assert!(f.did.is_local());
1237             f.did.index
1238         }));
1239         if variant.ctor_kind == CtorKind::Fn {
1240             // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1241             if let Some(ctor_def_id) = variant.ctor_def_id {
1242                 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1243             }
1244         }
1245     }
1246
1247     fn encode_enum_variant_ctor(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1248         let tcx = self.tcx;
1249         let variant = &def.variant(index);
1250         let def_id = variant.ctor_def_id.unwrap();
1251         debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1252
1253         // FIXME(eddyb) encode only the `CtorKind` for constructors.
1254         let data = VariantData {
1255             ctor_kind: variant.ctor_kind,
1256             discr: variant.discr,
1257             ctor: Some(def_id.index),
1258             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1259         };
1260
1261         record!(self.tables.variant_data[def_id] <- data);
1262         if variant.ctor_kind == CtorKind::Fn {
1263             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1264         }
1265     }
1266
1267     fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1268         let tcx = self.tcx;
1269         let def_id = local_def_id.to_def_id();
1270         debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1271
1272         // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1273         // only ever get called for the crate root. We still want to encode
1274         // the crate root for consistency with other crates (some of the resolver
1275         // code uses it). However, we skip encoding anything relating to child
1276         // items - we encode information about proc-macros later on.
1277         let reexports = if !self.is_proc_macro {
1278             tcx.module_reexports(local_def_id).unwrap_or(&[])
1279         } else {
1280             &[]
1281         };
1282
1283         record_array!(self.tables.module_reexports[def_id] <- reexports);
1284         if self.is_proc_macro {
1285             // Encode this here because we don't do it in encode_def_ids.
1286             record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1287         } else {
1288             record_array!(self.tables.children[def_id] <- iter::from_generator(|| {
1289                 for item_id in md.item_ids {
1290                     match tcx.hir().item(*item_id).kind {
1291                         // Foreign items are planted into their parent modules
1292                         // from name resolution point of view.
1293                         hir::ItemKind::ForeignMod { items, .. } => {
1294                             for foreign_item in items {
1295                                 yield foreign_item.id.def_id.def_id.local_def_index;
1296                             }
1297                         }
1298                         // Only encode named non-reexport children, reexports are encoded
1299                         // separately and unnamed items are not used by name resolution.
1300                         hir::ItemKind::ExternCrate(..) => continue,
1301                         _ if tcx.def_key(item_id.def_id.to_def_id()).get_opt_name().is_some() => {
1302                             yield item_id.def_id.def_id.local_def_index;
1303                         }
1304                         _ => continue,
1305                     }
1306                 }
1307             }));
1308         }
1309     }
1310
1311     fn encode_struct_ctor(&mut self, adt_def: ty::AdtDef<'tcx>, def_id: DefId) {
1312         debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1313         let tcx = self.tcx;
1314         let variant = adt_def.non_enum_variant();
1315
1316         let data = VariantData {
1317             ctor_kind: variant.ctor_kind,
1318             discr: variant.discr,
1319             ctor: Some(def_id.index),
1320             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1321         };
1322
1323         record!(self.tables.repr_options[def_id] <- adt_def.repr());
1324         record!(self.tables.variant_data[def_id] <- data);
1325         if variant.ctor_kind == CtorKind::Fn {
1326             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1327         }
1328     }
1329
1330     fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1331         debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1332         let bounds = self.tcx.explicit_item_bounds(def_id);
1333         if !bounds.is_empty() {
1334             record_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1335         }
1336     }
1337
1338     fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1339         debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1340         let tcx = self.tcx;
1341
1342         let ast_item = tcx.hir().expect_trait_item(def_id.expect_local());
1343         self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
1344         let trait_item = tcx.associated_item(def_id);
1345         self.tables.assoc_container.set(def_id.index, trait_item.container);
1346
1347         match trait_item.kind {
1348             ty::AssocKind::Const => {}
1349             ty::AssocKind::Fn => {
1350                 let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind else { bug!() };
1351                 match *m {
1352                     hir::TraitFn::Required(ref names) => {
1353                         record_array!(self.tables.fn_arg_names[def_id] <- *names)
1354                     }
1355                     hir::TraitFn::Provided(body) => {
1356                         record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body))
1357                     }
1358                 };
1359                 self.tables.asyncness.set(def_id.index, m_sig.header.asyncness);
1360             }
1361             ty::AssocKind::Type => {
1362                 self.encode_explicit_item_bounds(def_id);
1363             }
1364         }
1365         if trait_item.kind == ty::AssocKind::Fn {
1366             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1367         }
1368     }
1369
1370     fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1371         debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1372         let tcx = self.tcx;
1373
1374         let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local());
1375         self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
1376         let impl_item = self.tcx.associated_item(def_id);
1377         self.tables.assoc_container.set(def_id.index, impl_item.container);
1378
1379         match impl_item.kind {
1380             ty::AssocKind::Fn => {
1381                 let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() };
1382                 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1383                 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1384             }
1385             ty::AssocKind::Const | ty::AssocKind::Type => {}
1386         }
1387         if let Some(trait_item_def_id) = impl_item.trait_item_def_id {
1388             self.tables.trait_item_def_id.set(def_id.index, trait_item_def_id.into());
1389         }
1390         if impl_item.kind == ty::AssocKind::Fn {
1391             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1392             if tcx.is_intrinsic(def_id) {
1393                 self.tables.is_intrinsic.set(def_id.index, ());
1394             }
1395         }
1396     }
1397
1398     fn encode_mir(&mut self) {
1399         if self.is_proc_macro {
1400             return;
1401         }
1402
1403         let tcx = self.tcx;
1404
1405         let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1406             let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
1407             if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1408         });
1409         for (def_id, encode_const, encode_opt) in keys_and_jobs {
1410             debug_assert!(encode_const || encode_opt);
1411
1412             debug!("EntryBuilder::encode_mir({:?})", def_id);
1413             if encode_opt {
1414                 record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1415             }
1416             if encode_const {
1417                 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1418
1419                 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1420                 let abstract_const = tcx.thir_abstract_const(def_id);
1421                 if let Ok(Some(abstract_const)) = abstract_const {
1422                     record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1423                 }
1424
1425                 if should_encode_const(tcx.def_kind(def_id)) {
1426                     let qualifs = tcx.mir_const_qualif(def_id);
1427                     record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1428                     let body_id = tcx.hir().maybe_body_owned_by(def_id);
1429                     if let Some(body_id) = body_id {
1430                         let const_data = self.encode_rendered_const_for_body(body_id);
1431                         record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1432                     }
1433                 }
1434             }
1435             record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1436
1437             let instance =
1438                 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1439             let unused = tcx.unused_generic_params(instance);
1440             if !unused.is_empty() {
1441                 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1442             }
1443         }
1444     }
1445
1446     fn encode_stability(&mut self, def_id: DefId) {
1447         debug!("EncodeContext::encode_stability({:?})", def_id);
1448
1449         // The query lookup can take a measurable amount of time in crates with many items. Check if
1450         // the stability attributes are even enabled before using their queries.
1451         if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1452             if let Some(stab) = self.tcx.lookup_stability(def_id) {
1453                 record!(self.tables.lookup_stability[def_id] <- stab)
1454             }
1455         }
1456     }
1457
1458     fn encode_const_stability(&mut self, def_id: DefId) {
1459         debug!("EncodeContext::encode_const_stability({:?})", def_id);
1460
1461         // The query lookup can take a measurable amount of time in crates with many items. Check if
1462         // the stability attributes are even enabled before using their queries.
1463         if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1464             if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1465                 record!(self.tables.lookup_const_stability[def_id] <- stab)
1466             }
1467         }
1468     }
1469
1470     fn encode_default_body_stability(&mut self, def_id: DefId) {
1471         debug!("EncodeContext::encode_default_body_stability({:?})", def_id);
1472
1473         // The query lookup can take a measurable amount of time in crates with many items. Check if
1474         // the stability attributes are even enabled before using their queries.
1475         if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1476             if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1477                 record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1478             }
1479         }
1480     }
1481
1482     fn encode_deprecation(&mut self, def_id: DefId) {
1483         debug!("EncodeContext::encode_deprecation({:?})", def_id);
1484         if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1485             record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1486         }
1487     }
1488
1489     fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> String {
1490         let hir = self.tcx.hir();
1491         let body = hir.body(body_id);
1492         rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1493             s.print_expr(&body.value)
1494         })
1495     }
1496
1497     fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1498         let tcx = self.tcx;
1499
1500         debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1501
1502         match item.kind {
1503             hir::ItemKind::Fn(ref sig, .., body) => {
1504                 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1505                 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1506             }
1507             hir::ItemKind::Macro(ref macro_def, _) => {
1508                 if macro_def.macro_rules {
1509                     self.tables.macro_rules.set(def_id.index, ());
1510                 }
1511                 record!(self.tables.macro_definition[def_id] <- &*macro_def.body);
1512             }
1513             hir::ItemKind::Mod(ref m) => {
1514                 return self.encode_info_for_mod(item.def_id.def_id, m);
1515             }
1516             hir::ItemKind::OpaqueTy(..) => {
1517                 self.encode_explicit_item_bounds(def_id);
1518             }
1519             hir::ItemKind::Enum(..) => {
1520                 let adt_def = self.tcx.adt_def(def_id);
1521                 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1522             }
1523             hir::ItemKind::Struct(ref struct_def, _) => {
1524                 let adt_def = self.tcx.adt_def(def_id);
1525                 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1526
1527                 // Encode def_ids for each field and method
1528                 // for methods, write all the stuff get_trait_method
1529                 // needs to know
1530                 let ctor = struct_def
1531                     .ctor_hir_id()
1532                     .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1533
1534                 let variant = adt_def.non_enum_variant();
1535                 record!(self.tables.variant_data[def_id] <- VariantData {
1536                     ctor_kind: variant.ctor_kind,
1537                     discr: variant.discr,
1538                     ctor,
1539                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1540                 });
1541             }
1542             hir::ItemKind::Union(..) => {
1543                 let adt_def = self.tcx.adt_def(def_id);
1544                 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1545
1546                 let variant = adt_def.non_enum_variant();
1547                 record!(self.tables.variant_data[def_id] <- VariantData {
1548                     ctor_kind: variant.ctor_kind,
1549                     discr: variant.discr,
1550                     ctor: None,
1551                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1552                 });
1553             }
1554             hir::ItemKind::Impl(hir::Impl { defaultness, .. }) => {
1555                 self.tables.impl_defaultness.set(def_id.index, *defaultness);
1556
1557                 let trait_ref = self.tcx.impl_trait_ref(def_id);
1558                 if let Some(trait_ref) = trait_ref {
1559                     let trait_def = self.tcx.trait_def(trait_ref.def_id);
1560                     if let Some(mut an) = trait_def.ancestors(self.tcx, def_id).ok() {
1561                         if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
1562                             self.tables.impl_parent.set(def_id.index, parent.into());
1563                         }
1564                     }
1565
1566                     // if this is an impl of `CoerceUnsized`, create its
1567                     // "unsized info", else just store None
1568                     if Some(trait_ref.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1569                         let coerce_unsized_info =
1570                             self.tcx.at(item.span).coerce_unsized_info(def_id);
1571                         record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
1572                     }
1573                 }
1574
1575                 let polarity = self.tcx.impl_polarity(def_id);
1576                 self.tables.impl_polarity.set(def_id.index, polarity);
1577             }
1578             hir::ItemKind::Trait(..) => {
1579                 let trait_def = self.tcx.trait_def(def_id);
1580                 record!(self.tables.trait_def[def_id] <- trait_def);
1581             }
1582             hir::ItemKind::TraitAlias(..) => {
1583                 let trait_def = self.tcx.trait_def(def_id);
1584                 record!(self.tables.trait_def[def_id] <- trait_def);
1585             }
1586             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1587                 bug!("cannot encode info for item {:?}", item)
1588             }
1589             hir::ItemKind::Static(..)
1590             | hir::ItemKind::Const(..)
1591             | hir::ItemKind::ForeignMod { .. }
1592             | hir::ItemKind::GlobalAsm(..)
1593             | hir::ItemKind::TyAlias(..) => {}
1594         };
1595         // FIXME(eddyb) there should be a nicer way to do this.
1596         match item.kind {
1597             hir::ItemKind::Enum(..) => record_array!(self.tables.children[def_id] <-
1598                 self.tcx.adt_def(def_id).variants().iter().map(|v| {
1599                     assert!(v.def_id.is_local());
1600                     v.def_id.index
1601                 })
1602             ),
1603             hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1604                 record_array!(self.tables.children[def_id] <-
1605                     self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1606                         assert!(f.did.is_local());
1607                         f.did.index
1608                     })
1609                 )
1610             }
1611             hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1612                 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1613                 record_array!(self.tables.children[def_id] <-
1614                     associated_item_def_ids.iter().map(|&def_id| {
1615                         assert!(def_id.is_local());
1616                         def_id.index
1617                     })
1618                 );
1619             }
1620             _ => {}
1621         }
1622         if let hir::ItemKind::Fn(..) = item.kind {
1623             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1624             if tcx.is_intrinsic(def_id) {
1625                 self.tables.is_intrinsic.set(def_id.index, ());
1626             }
1627         }
1628         if let hir::ItemKind::Impl { .. } = item.kind {
1629             if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1630                 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1631             }
1632         }
1633         // In some cases, along with the item itself, we also
1634         // encode some sub-items. Usually we want some info from the item
1635         // so it's easier to do that here then to wait until we would encounter
1636         // normally in the visitor walk.
1637         match item.kind {
1638             hir::ItemKind::Enum(..) => {
1639                 let def = self.tcx.adt_def(item.def_id.to_def_id());
1640                 for (i, variant) in def.variants().iter_enumerated() {
1641                     self.encode_enum_variant_info(def, i);
1642
1643                     if let Some(_ctor_def_id) = variant.ctor_def_id {
1644                         self.encode_enum_variant_ctor(def, i);
1645                     }
1646                 }
1647             }
1648             hir::ItemKind::Struct(ref struct_def, _) => {
1649                 let def = self.tcx.adt_def(item.def_id.to_def_id());
1650                 // If the struct has a constructor, encode it.
1651                 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1652                     let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1653                     self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1654                 }
1655             }
1656             hir::ItemKind::Impl { .. } => {
1657                 for &trait_item_def_id in
1658                     self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
1659                 {
1660                     self.encode_info_for_impl_item(trait_item_def_id);
1661                 }
1662             }
1663             hir::ItemKind::Trait(..) => {
1664                 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
1665                 {
1666                     self.encode_info_for_trait_item(item_def_id);
1667                 }
1668             }
1669             _ => {}
1670         }
1671     }
1672
1673     fn encode_info_for_closure(&mut self, hir_id: hir::HirId) {
1674         let def_id = self.tcx.hir().local_def_id(hir_id);
1675         debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1676         // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1677         // including on the signature, which is inferred in `typeck.
1678         let typeck_result: &'tcx ty::TypeckResults<'tcx> = self.tcx.typeck(def_id);
1679         let ty = typeck_result.node_type(hir_id);
1680         match ty.kind() {
1681             ty::Generator(..) => {
1682                 let data = self.tcx.generator_kind(def_id).unwrap();
1683                 let generator_diagnostic_data = typeck_result.get_generator_diagnostic_data();
1684                 record!(self.tables.generator_kind[def_id.to_def_id()] <- data);
1685                 record!(self.tables.generator_diagnostic_data[def_id.to_def_id()]  <- generator_diagnostic_data);
1686             }
1687
1688             ty::Closure(_, substs) => {
1689                 record!(self.tables.fn_sig[def_id.to_def_id()] <- substs.as_closure().sig());
1690             }
1691
1692             _ => bug!("closure that is neither generator nor closure"),
1693         }
1694     }
1695
1696     fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1697         empty_proc_macro!(self);
1698         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1699         self.lazy_array(used_libraries.iter())
1700     }
1701
1702     fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1703         empty_proc_macro!(self);
1704         let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1705         self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1706     }
1707
1708     fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1709         let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1710         let mut expn_data_table: TableBuilder<_, _> = Default::default();
1711         let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1712
1713         self.hygiene_ctxt.encode(
1714             &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1715             |(this, syntax_contexts, _, _), index, ctxt_data| {
1716                 syntax_contexts.set(index, this.lazy(ctxt_data));
1717             },
1718             |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1719                 if let Some(index) = index.as_local() {
1720                     expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1721                     expn_hash_table.set(index.as_raw(), this.lazy(hash));
1722                 }
1723             },
1724         );
1725
1726         (
1727             syntax_contexts.encode(&mut self.opaque),
1728             expn_data_table.encode(&mut self.opaque),
1729             expn_hash_table.encode(&mut self.opaque),
1730         )
1731     }
1732
1733     fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1734         let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1735         if is_proc_macro {
1736             let tcx = self.tcx;
1737             let hir = tcx.hir();
1738
1739             let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1740             let stability = tcx.lookup_stability(CRATE_DEF_ID);
1741             let macros =
1742                 self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1743             let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1744             for (i, span) in spans.into_iter().enumerate() {
1745                 let span = self.lazy(span);
1746                 self.tables.proc_macro_quoted_spans.set(i, span);
1747             }
1748
1749             self.tables.opt_def_kind.set(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1750             record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1751             self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1752             let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|def_id| def_id.local_def_index);
1753             record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
1754             if let Some(stability) = stability {
1755                 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1756             }
1757             self.encode_deprecation(LOCAL_CRATE.as_def_id());
1758
1759             // Normally, this information is encoded when we walk the items
1760             // defined in this crate. However, we skip doing that for proc-macro crates,
1761             // so we manually encode just the information that we need
1762             for &proc_macro in &tcx.resolutions(()).proc_macros {
1763                 let id = proc_macro;
1764                 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1765                 let mut name = hir.name(proc_macro);
1766                 let span = hir.span(proc_macro);
1767                 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1768                 // so downstream crates need access to them.
1769                 let attrs = hir.attrs(proc_macro);
1770                 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1771                     MacroKind::Bang
1772                 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1773                     MacroKind::Attr
1774                 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1775                     // This unwrap chain should have been checked by the proc-macro harness.
1776                     name = attr.meta_item_list().unwrap()[0]
1777                         .meta_item()
1778                         .unwrap()
1779                         .ident()
1780                         .unwrap()
1781                         .name;
1782                     MacroKind::Derive
1783                 } else {
1784                     bug!("Unknown proc-macro type for item {:?}", id);
1785                 };
1786
1787                 let mut def_key = self.tcx.hir().def_key(id);
1788                 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1789
1790                 let def_id = id.to_def_id();
1791                 self.tables.opt_def_kind.set(def_id.index, DefKind::Macro(macro_kind));
1792                 self.tables.proc_macro.set(def_id.index, macro_kind);
1793                 self.encode_attrs(id);
1794                 record!(self.tables.def_keys[def_id] <- def_key);
1795                 record!(self.tables.def_ident_span[def_id] <- span);
1796                 record!(self.tables.def_span[def_id] <- span);
1797                 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1798                 if let Some(stability) = stability {
1799                     record!(self.tables.lookup_stability[def_id] <- stability);
1800                 }
1801             }
1802
1803             Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1804         } else {
1805             None
1806         }
1807     }
1808
1809     fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1810         empty_proc_macro!(self);
1811         self.lazy_array(self.tcx.debugger_visualizers(LOCAL_CRATE).iter())
1812     }
1813
1814     fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1815         empty_proc_macro!(self);
1816
1817         let deps = self
1818             .tcx
1819             .crates(())
1820             .iter()
1821             .map(|&cnum| {
1822                 let dep = CrateDep {
1823                     name: self.tcx.crate_name(cnum),
1824                     hash: self.tcx.crate_hash(cnum),
1825                     host_hash: self.tcx.crate_host_hash(cnum),
1826                     kind: self.tcx.dep_kind(cnum),
1827                     extra_filename: self.tcx.extra_filename(cnum).clone(),
1828                 };
1829                 (cnum, dep)
1830             })
1831             .collect::<Vec<_>>();
1832
1833         {
1834             // Sanity-check the crate numbers
1835             let mut expected_cnum = 1;
1836             for &(n, _) in &deps {
1837                 assert_eq!(n, CrateNum::new(expected_cnum));
1838                 expected_cnum += 1;
1839             }
1840         }
1841
1842         // We're just going to write a list of crate 'name-hash-version's, with
1843         // the assumption that they are numbered 1 to n.
1844         // FIXME (#2166): This is not nearly enough to support correct versioning
1845         // but is enough to get transitive crate dependencies working.
1846         self.lazy_array(deps.iter().map(|&(_, ref dep)| dep))
1847     }
1848
1849     fn encode_lib_features(&mut self) -> LazyArray<(Symbol, Option<Symbol>)> {
1850         empty_proc_macro!(self);
1851         let tcx = self.tcx;
1852         let lib_features = tcx.lib_features(());
1853         self.lazy_array(lib_features.to_vec())
1854     }
1855
1856     fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
1857         empty_proc_macro!(self);
1858         let tcx = self.tcx;
1859         let implications = tcx.stability_implications(LOCAL_CRATE);
1860         self.lazy_array(implications.iter().map(|(k, v)| (*k, *v)))
1861     }
1862
1863     fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
1864         empty_proc_macro!(self);
1865         let tcx = self.tcx;
1866         let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1867         self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1868     }
1869
1870     fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, usize)> {
1871         empty_proc_macro!(self);
1872         let tcx = self.tcx;
1873         let lang_items = tcx.lang_items();
1874         let lang_items = lang_items.items().iter();
1875         self.lazy_array(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1876             if let Some(def_id) = opt_def_id {
1877                 if def_id.is_local() {
1878                     return Some((def_id.index, i));
1879                 }
1880             }
1881             None
1882         }))
1883     }
1884
1885     fn encode_lang_items_missing(&mut self) -> LazyArray<lang_items::LangItem> {
1886         empty_proc_macro!(self);
1887         let tcx = self.tcx;
1888         self.lazy_array(&tcx.lang_items().missing)
1889     }
1890
1891     fn encode_traits(&mut self) -> LazyArray<DefIndex> {
1892         empty_proc_macro!(self);
1893         self.lazy_array(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index))
1894     }
1895
1896     /// Encodes an index, mapping each trait to its (local) implementations.
1897     fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
1898         debug!("EncodeContext::encode_traits_and_impls()");
1899         empty_proc_macro!(self);
1900         let tcx = self.tcx;
1901         let mut fx_hash_map: FxHashMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
1902             FxHashMap::default();
1903
1904         for id in tcx.hir().items() {
1905             if matches!(tcx.def_kind(id.def_id), DefKind::Impl) {
1906                 if let Some(trait_ref) = tcx.impl_trait_ref(id.def_id) {
1907                     let simplified_self_ty = fast_reject::simplify_type(
1908                         self.tcx,
1909                         trait_ref.self_ty(),
1910                         TreatParams::AsInfer,
1911                     );
1912
1913                     fx_hash_map
1914                         .entry(trait_ref.def_id)
1915                         .or_default()
1916                         .push((id.def_id.def_id.local_def_index, simplified_self_ty));
1917                 }
1918             }
1919         }
1920
1921         let mut all_impls: Vec<_> = fx_hash_map.into_iter().collect();
1922
1923         // Bring everything into deterministic order for hashing
1924         all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1925
1926         let all_impls: Vec<_> = all_impls
1927             .into_iter()
1928             .map(|(trait_def_id, mut impls)| {
1929                 // Bring everything into deterministic order for hashing
1930                 impls.sort_by_cached_key(|&(index, _)| {
1931                     tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1932                 });
1933
1934                 TraitImpls {
1935                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1936                     impls: self.lazy_array(&impls),
1937                 }
1938             })
1939             .collect();
1940
1941         self.lazy_array(&all_impls)
1942     }
1943
1944     fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
1945         debug!("EncodeContext::encode_traits_and_impls()");
1946         empty_proc_macro!(self);
1947         let tcx = self.tcx;
1948         let mut all_impls: Vec<_> = tcx.crate_inherent_impls(()).incoherent_impls.iter().collect();
1949         tcx.with_stable_hashing_context(|mut ctx| {
1950             all_impls.sort_by_cached_key(|&(&simp, _)| {
1951                 let mut hasher = StableHasher::new();
1952                 simp.hash_stable(&mut ctx, &mut hasher);
1953                 hasher.finish::<Fingerprint>()
1954             })
1955         });
1956         let all_impls: Vec<_> = all_impls
1957             .into_iter()
1958             .map(|(&simp, impls)| {
1959                 let mut impls: Vec<_> =
1960                     impls.into_iter().map(|def_id| def_id.local_def_index).collect();
1961                 impls.sort_by_cached_key(|&local_def_index| {
1962                     tcx.hir().def_path_hash(LocalDefId { local_def_index })
1963                 });
1964
1965                 IncoherentImpls { self_ty: simp, impls: self.lazy_array(impls) }
1966             })
1967             .collect();
1968
1969         self.lazy_array(&all_impls)
1970     }
1971
1972     // Encodes all symbols exported from this crate into the metadata.
1973     //
1974     // This pass is seeded off the reachability list calculated in the
1975     // middle::reachable module but filters out items that either don't have a
1976     // symbol associated with them (they weren't translated) or if they're an FFI
1977     // definition (as that's not defined in this crate).
1978     fn encode_exported_symbols(
1979         &mut self,
1980         exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
1981     ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
1982         empty_proc_macro!(self);
1983         // The metadata symbol name is special. It should not show up in
1984         // downstream crates.
1985         let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1986
1987         self.lazy_array(
1988             exported_symbols
1989                 .iter()
1990                 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1991                     ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1992                     _ => true,
1993                 })
1994                 .cloned(),
1995         )
1996     }
1997
1998     fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
1999         empty_proc_macro!(self);
2000         let formats = self.tcx.dependency_formats(());
2001         for (ty, arr) in formats.iter() {
2002             if *ty != CrateType::Dylib {
2003                 continue;
2004             }
2005             return self.lazy_array(arr.iter().map(|slot| match *slot {
2006                 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2007
2008                 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2009                 Linkage::Static => Some(LinkagePreference::RequireStatic),
2010             }));
2011         }
2012         LazyArray::empty()
2013     }
2014
2015     fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
2016         let tcx = self.tcx;
2017
2018         debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
2019
2020         match nitem.kind {
2021             hir::ForeignItemKind::Fn(_, ref names, _) => {
2022                 self.tables.asyncness.set(def_id.index, hir::IsAsync::NotAsync);
2023                 record_array!(self.tables.fn_arg_names[def_id] <- *names);
2024                 let constness = if self.tcx.is_const_fn_raw(def_id) {
2025                     hir::Constness::Const
2026                 } else {
2027                     hir::Constness::NotConst
2028                 };
2029                 self.tables.constness.set(def_id.index, constness);
2030                 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
2031             }
2032             hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => {}
2033         }
2034         if let hir::ForeignItemKind::Fn(..) = nitem.kind {
2035             if tcx.is_intrinsic(def_id) {
2036                 self.tables.is_intrinsic.set(def_id.index, ());
2037             }
2038         }
2039     }
2040 }
2041
2042 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
2043 impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> {
2044     type NestedFilter = nested_filter::OnlyBodies;
2045
2046     fn nested_visit_map(&mut self) -> Self::Map {
2047         self.tcx.hir()
2048     }
2049     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2050         intravisit::walk_expr(self, ex);
2051         self.encode_info_for_expr(ex);
2052     }
2053     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
2054         intravisit::walk_item(self, item);
2055         match item.kind {
2056             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
2057             _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
2058         }
2059     }
2060     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
2061         intravisit::walk_foreign_item(self, ni);
2062         self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
2063     }
2064     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
2065         intravisit::walk_generics(self, generics);
2066         self.encode_info_for_generics(generics);
2067     }
2068 }
2069
2070 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
2071     fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
2072         for param in generics.params {
2073             let def_id = self.tcx.hir().local_def_id(param.hir_id);
2074             match param.kind {
2075                 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => {}
2076                 hir::GenericParamKind::Const { ref default, .. } => {
2077                     let def_id = def_id.to_def_id();
2078                     if default.is_some() {
2079                         record!(self.tables.const_param_default[def_id] <- self.tcx.const_param_default(def_id))
2080                     }
2081                 }
2082             }
2083         }
2084     }
2085
2086     fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
2087         if let hir::ExprKind::Closure { .. } = expr.kind {
2088             self.encode_info_for_closure(expr.hir_id);
2089         }
2090     }
2091 }
2092
2093 /// Used to prefetch queries which will be needed later by metadata encoding.
2094 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2095 fn prefetch_mir(tcx: TyCtxt<'_>) {
2096     if !tcx.sess.opts.output_types.should_codegen() {
2097         // We won't emit MIR, so don't prefetch it.
2098         return;
2099     }
2100
2101     par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2102         let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2103
2104         if encode_const {
2105             tcx.ensure().mir_for_ctfe(def_id);
2106         }
2107         if encode_opt {
2108             tcx.ensure().optimized_mir(def_id);
2109         }
2110         if encode_opt || encode_const {
2111             tcx.ensure().promoted_mir(def_id);
2112         }
2113     })
2114 }
2115
2116 // NOTE(eddyb) The following comment was preserved for posterity, even
2117 // though it's no longer relevant as EBML (which uses nested & tagged
2118 // "documents") was replaced with a scheme that can't go out of bounds.
2119 //
2120 // And here we run into yet another obscure archive bug: in which metadata
2121 // loaded from archives may have trailing garbage bytes. Awhile back one of
2122 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2123 // and opt) by having ebml generate an out-of-bounds panic when looking at
2124 // metadata.
2125 //
2126 // Upon investigation it turned out that the metadata file inside of an rlib
2127 // (and ar archive) was being corrupted. Some compilations would generate a
2128 // metadata file which would end in a few extra bytes, while other
2129 // compilations would not have these extra bytes appended to the end. These
2130 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2131 // being interpreted causing the out-of-bounds.
2132 //
2133 // The root cause of why these extra bytes were appearing was never
2134 // discovered, and in the meantime the solution we're employing is to insert
2135 // the length of the metadata to the start of the metadata. Later on this
2136 // will allow us to slice the metadata to the precise length that we just
2137 // generated regardless of trailing bytes that end up in it.
2138
2139 pub struct EncodedMetadata {
2140     // The declaration order matters because `mmap` should be dropped before `_temp_dir`.
2141     mmap: Option<Mmap>,
2142     // We need to carry MaybeTempDir to avoid deleting the temporary
2143     // directory while accessing the Mmap.
2144     _temp_dir: Option<MaybeTempDir>,
2145 }
2146
2147 impl EncodedMetadata {
2148     #[inline]
2149     pub fn from_path(path: PathBuf, temp_dir: Option<MaybeTempDir>) -> std::io::Result<Self> {
2150         let file = std::fs::File::open(&path)?;
2151         let file_metadata = file.metadata()?;
2152         if file_metadata.len() == 0 {
2153             return Ok(Self { mmap: None, _temp_dir: None });
2154         }
2155         let mmap = unsafe { Some(Mmap::map(file)?) };
2156         Ok(Self { mmap, _temp_dir: temp_dir })
2157     }
2158
2159     #[inline]
2160     pub fn raw_data(&self) -> &[u8] {
2161         self.mmap.as_ref().map(|mmap| mmap.as_ref()).unwrap_or_default()
2162     }
2163 }
2164
2165 impl<S: Encoder> Encodable<S> for EncodedMetadata {
2166     fn encode(&self, s: &mut S) {
2167         let slice = self.raw_data();
2168         slice.encode(s)
2169     }
2170 }
2171
2172 impl<D: Decoder> Decodable<D> for EncodedMetadata {
2173     fn decode(d: &mut D) -> Self {
2174         let len = d.read_usize();
2175         let mmap = if len > 0 {
2176             let mut mmap = MmapMut::map_anon(len).unwrap();
2177             for _ in 0..len {
2178                 (&mut mmap[..]).write(&[d.read_u8()]).unwrap();
2179             }
2180             mmap.flush().unwrap();
2181             Some(mmap.make_read_only().unwrap())
2182         } else {
2183             None
2184         };
2185
2186         Self { mmap, _temp_dir: None }
2187     }
2188 }
2189
2190 pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path) {
2191     let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2192
2193     // Since encoding metadata is not in a query, and nothing is cached,
2194     // there's no need to do dep-graph tracking for any of it.
2195     tcx.dep_graph.assert_ignored();
2196
2197     join(
2198         || encode_metadata_impl(tcx, path),
2199         || {
2200             if tcx.sess.threads() == 1 {
2201                 return;
2202             }
2203             // Prefetch some queries used by metadata encoding.
2204             // This is not necessary for correctness, but is only done for performance reasons.
2205             // It can be removed if it turns out to cause trouble or be detrimental to performance.
2206             join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2207         },
2208     );
2209 }
2210
2211 fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) {
2212     let mut encoder = opaque::FileEncoder::new(path)
2213         .unwrap_or_else(|err| tcx.sess.emit_fatal(FailCreateFileEncoder { err }));
2214     encoder.emit_raw_bytes(METADATA_HEADER);
2215
2216     // Will be filled with the root position after encoding everything.
2217     encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2218
2219     let source_map_files = tcx.sess.source_map().files();
2220     let source_file_cache = (source_map_files[0].clone(), 0);
2221     let required_source_files = Some(FxIndexSet::default());
2222     drop(source_map_files);
2223
2224     let hygiene_ctxt = HygieneEncodeContext::default();
2225
2226     let mut ecx = EncodeContext {
2227         opaque: encoder,
2228         tcx,
2229         feat: tcx.features(),
2230         tables: Default::default(),
2231         lazy_state: LazyState::NoNode,
2232         type_shorthands: Default::default(),
2233         predicate_shorthands: Default::default(),
2234         source_file_cache,
2235         interpret_allocs: Default::default(),
2236         required_source_files,
2237         is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2238         hygiene_ctxt: &hygiene_ctxt,
2239         symbol_table: Default::default(),
2240     };
2241
2242     // Encode the rustc version string in a predictable location.
2243     rustc_version().encode(&mut ecx);
2244
2245     // Encode all the entries and extra information in the crate,
2246     // culminating in the `CrateRoot` which points to all of it.
2247     let root = ecx.encode_crate_root();
2248
2249     ecx.opaque.flush();
2250
2251     let mut file = ecx.opaque.file();
2252     // We will return to this position after writing the root position.
2253     let pos_before_seek = file.stream_position().unwrap();
2254
2255     // Encode the root position.
2256     let header = METADATA_HEADER.len();
2257     file.seek(std::io::SeekFrom::Start(header as u64))
2258         .unwrap_or_else(|err| tcx.sess.emit_fatal(FailSeekFile { err }));
2259     let pos = root.position.get();
2260     file.write_all(&[(pos >> 24) as u8, (pos >> 16) as u8, (pos >> 8) as u8, (pos >> 0) as u8])
2261         .unwrap_or_else(|err| tcx.sess.emit_fatal(FailWriteFile { err }));
2262
2263     // Return to the position where we are before writing the root position.
2264     file.seek(std::io::SeekFrom::Start(pos_before_seek)).unwrap();
2265
2266     // Record metadata size for self-profiling
2267     tcx.prof.artifact_size(
2268         "crate_metadata",
2269         "crate_metadata",
2270         file.metadata().unwrap().len() as u64,
2271     );
2272 }
2273
2274 pub fn provide(providers: &mut Providers) {
2275     *providers = Providers {
2276         traits_in_crate: |tcx, cnum| {
2277             assert_eq!(cnum, LOCAL_CRATE);
2278
2279             let mut traits = Vec::new();
2280             for id in tcx.hir().items() {
2281                 if matches!(tcx.def_kind(id.def_id), DefKind::Trait | DefKind::TraitAlias) {
2282                     traits.push(id.def_id.to_def_id())
2283                 }
2284             }
2285
2286             // Bring everything into deterministic order.
2287             traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
2288             tcx.arena.alloc_slice(&traits)
2289         },
2290
2291         ..*providers
2292     }
2293 }