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