]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/encoder.rs
Rollup merge of #80035 - ChayimFriedman2:patch-1, r=nagisa
[rust.git] / compiler / rustc_metadata / src / rmeta / encoder.rs
1 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
2 use crate::rmeta::*;
3
4 use rustc_ast as ast;
5 use rustc_data_structures::fingerprint::{Fingerprint, FingerprintEncoder};
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
7 use rustc_data_structures::stable_hasher::StableHasher;
8 use rustc_data_structures::sync::{join, Lrc};
9 use rustc_hir as hir;
10 use rustc_hir::def::CtorKind;
11 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::definitions::DefPathData;
13 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
14 use rustc_hir::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor};
15 use rustc_hir::lang_items;
16 use rustc_hir::{AnonConst, GenericParamKind};
17 use rustc_index::bit_set::GrowableBitSet;
18 use rustc_index::vec::Idx;
19 use rustc_middle::hir::map::Map;
20 use rustc_middle::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLib};
21 use rustc_middle::middle::dependency_format::Linkage;
22 use rustc_middle::middle::exported_symbols::{
23     metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
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::{self, SymbolName, Ty, TyCtxt};
29 use rustc_serialize::{opaque, Encodable, Encoder};
30 use rustc_session::config::CrateType;
31 use rustc_span::hygiene::{ExpnDataEncodeMode, HygieneEncodeContext, MacroKind};
32 use rustc_span::symbol::{sym, Ident, Symbol};
33 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
34 use rustc_target::abi::VariantIdx;
35 use std::hash::Hash;
36 use std::num::NonZeroUsize;
37 use std::path::Path;
38 use tracing::{debug, trace};
39
40 pub(super) struct EncodeContext<'a, 'tcx> {
41     opaque: opaque::Encoder,
42     tcx: TyCtxt<'tcx>,
43     feat: &'tcx rustc_feature::Features,
44
45     tables: TableBuilders<'tcx>,
46
47     lazy_state: LazyState,
48     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
49     predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
50
51     interpret_allocs: FxIndexSet<interpret::AllocId>,
52
53     // This is used to speed up Span encoding.
54     // The `usize` is an index into the `MonotonicVec`
55     // that stores the `SourceFile`
56     source_file_cache: (Lrc<SourceFile>, usize),
57     // The indices (into the `SourceMap`'s `MonotonicVec`)
58     // of all of the `SourceFiles` that we need to serialize.
59     // When we serialize a `Span`, we insert the index of its
60     // `SourceFile` into the `GrowableBitSet`.
61     //
62     // This needs to be a `GrowableBitSet` and not a
63     // regular `BitSet` because we may actually import new `SourceFiles`
64     // during metadata encoding, due to executing a query
65     // with a result containing a foreign `Span`.
66     required_source_files: Option<GrowableBitSet<usize>>,
67     is_proc_macro: bool,
68     hygiene_ctxt: &'a HygieneEncodeContext,
69 }
70
71 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
72 /// This is useful for skipping the encoding of things that aren't needed
73 /// for proc-macro crates.
74 macro_rules! empty_proc_macro {
75     ($self:ident) => {
76         if $self.is_proc_macro {
77             return Lazy::empty();
78         }
79     };
80 }
81
82 macro_rules! encoder_methods {
83     ($($name:ident($ty:ty);)*) => {
84         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
85             self.opaque.$name(value)
86         })*
87     }
88 }
89
90 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
91     type Error = <opaque::Encoder as Encoder>::Error;
92
93     #[inline]
94     fn emit_unit(&mut self) -> Result<(), Self::Error> {
95         Ok(())
96     }
97
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     }
119 }
120
121 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
122     for Lazy<T>
123 {
124     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
125         e.emit_lazy_distance(*self)
126     }
127 }
128
129 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
130     for Lazy<[T]>
131 {
132     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
133         e.emit_usize(self.meta)?;
134         if self.meta == 0 {
135             return Ok(());
136         }
137         e.emit_lazy_distance(*self)
138     }
139 }
140
141 impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
142     for Lazy<Table<I, T>>
143 where
144     Option<T>: FixedSizeEncoding,
145 {
146     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
147         e.emit_usize(self.meta)?;
148         e.emit_lazy_distance(*self)
149     }
150 }
151
152 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
153     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
154         if *self != LOCAL_CRATE && s.is_proc_macro {
155             panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
156         }
157         s.emit_u32(self.as_u32())
158     }
159 }
160
161 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
162     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
163         s.emit_u32(self.as_u32())
164     }
165 }
166
167 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
168     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
169         rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
170     }
171 }
172
173 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
174     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
175         rustc_span::hygiene::raw_encode_expn_id(
176             *self,
177             &s.hygiene_ctxt,
178             ExpnDataEncodeMode::Metadata,
179             s,
180         )
181     }
182 }
183
184 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
185     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
186         if *self == rustc_span::DUMMY_SP {
187             return TAG_INVALID_SPAN.encode(s);
188         }
189
190         let span = self.data();
191
192         // The Span infrastructure should make sure that this invariant holds:
193         debug_assert!(span.lo <= span.hi);
194
195         if !s.source_file_cache.0.contains(span.lo) {
196             let source_map = s.tcx.sess.source_map();
197             let source_file_index = source_map.lookup_source_file_idx(span.lo);
198             s.source_file_cache =
199                 (source_map.files()[source_file_index].clone(), source_file_index);
200         }
201
202         if !s.source_file_cache.0.contains(span.hi) {
203             // Unfortunately, macro expansion still sometimes generates Spans
204             // that malformed in this way.
205             return TAG_INVALID_SPAN.encode(s);
206         }
207
208         let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
209         // Record the fact that we need to encode the data for this `SourceFile`
210         source_files.insert(s.source_file_cache.1);
211
212         // There are two possible cases here:
213         // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
214         // crate we are writing metadata for. When the metadata for *this* crate gets
215         // deserialized, the deserializer will need to know which crate it originally came
216         // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
217         // be deserialized after the rest of the span data, which tells the deserializer
218         // which crate contains the source map information.
219         // 2. This span comes from our own crate. No special hamdling is needed - we just
220         // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
221         // our own source map information.
222         //
223         // If we're a proc-macro crate, we always treat this as a local `Span`.
224         // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
225         // if we're a proc-macro crate.
226         // This allows us to avoid loading the dependencies of proc-macro crates: all of
227         // the information we need to decode `Span`s is stored in the proc-macro crate.
228         let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
229             // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
230             // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
231             // are relative to the source map information for the 'foreign' crate whose CrateNum
232             // we write into the metadata. This allows `imported_source_files` to binary
233             // search through the 'foreign' crate's source map information, using the
234             // deserialized 'lo' and 'hi' values directly.
235             //
236             // All of this logic ensures that the final result of deserialization is a 'normal'
237             // Span that can be used without any additional trouble.
238             let external_start_pos = {
239                 // Introduce a new scope so that we drop the 'lock()' temporary
240                 match &*s.source_file_cache.0.external_src.lock() {
241                     ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
242                     src => panic!("Unexpected external source {:?}", src),
243                 }
244             };
245             let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
246             let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
247
248             (TAG_VALID_SPAN_FOREIGN, lo, hi)
249         } else {
250             (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
251         };
252
253         tag.encode(s)?;
254         lo.encode(s)?;
255
256         // Encode length which is usually less than span.hi and profits more
257         // from the variable-length integer encoding that we use.
258         let len = hi - lo;
259         len.encode(s)?;
260
261         // Don't serialize any `SyntaxContext`s from a proc-macro crate,
262         // since we don't load proc-macro dependencies during serialization.
263         // This means that any hygiene information from macros used *within*
264         // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
265         // definition) will be lost.
266         //
267         // This can show up in two ways:
268         //
269         // 1. Any hygiene information associated with identifier of
270         // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
271         // Since proc-macros can only be invoked from a different crate,
272         // real code should never need to care about this.
273         //
274         // 2. Using `Span::def_site` or `Span::mixed_site` will not
275         // include any hygiene information associated with the definition
276         // site. This means that a proc-macro cannot emit a `$crate`
277         // identifier which resolves to one of its dependencies,
278         // which also should never come up in practice.
279         //
280         // Additionally, this affects `Span::parent`, and any other
281         // span inspection APIs that would otherwise allow traversing
282         // the `SyntaxContexts` associated with a span.
283         //
284         // None of these user-visible effects should result in any
285         // cross-crate inconsistencies (getting one behavior in the same
286         // crate, and a different behavior in another crate) due to the
287         // limited surface that proc-macros can expose.
288         //
289         // IMPORTANT: If this is ever changed, be sure to update
290         // `rustc_span::hygiene::raw_encode_expn_id` to handle
291         // encoding `ExpnData` for proc-macro crates.
292         if s.is_proc_macro {
293             SyntaxContext::root().encode(s)?;
294         } else {
295             span.ctxt.encode(s)?;
296         }
297
298         if tag == TAG_VALID_SPAN_FOREIGN {
299             // This needs to be two lines to avoid holding the `s.source_file_cache`
300             // while calling `cnum.encode(s)`
301             let cnum = s.source_file_cache.0.cnum;
302             cnum.encode(s)?;
303         }
304
305         Ok(())
306     }
307 }
308
309 impl<'a, 'tcx> FingerprintEncoder for EncodeContext<'a, 'tcx> {
310     fn encode_fingerprint(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
311         f.encode_opaque(&mut self.opaque)
312     }
313 }
314
315 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
316     const CLEAR_CROSS_CRATE: bool = true;
317
318     fn position(&self) -> usize {
319         self.opaque.position()
320     }
321
322     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
323         &mut self.type_shorthands
324     }
325
326     fn predicate_shorthands(&mut self) -> &mut FxHashMap<rustc_middle::ty::Predicate<'tcx>, usize> {
327         &mut self.predicate_shorthands
328     }
329
330     fn encode_alloc_id(
331         &mut self,
332         alloc_id: &rustc_middle::mir::interpret::AllocId,
333     ) -> Result<(), Self::Error> {
334         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
335
336         index.encode(self)
337     }
338 }
339
340 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] {
341     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
342         (**self).encode(s)
343     }
344 }
345
346 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
347     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
348         (**self).encode(s)
349     }
350 }
351
352 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
353 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
354     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
355 }
356
357 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
358     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
359         self.encode(ecx).unwrap()
360     }
361 }
362
363 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
364     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
365         self.encode(ecx).unwrap()
366     }
367 }
368
369 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
370 where
371     I: IntoIterator,
372     I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
373 {
374     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
375         self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
376     }
377 }
378
379 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
380 // normally need extra variables to avoid errors about multiple mutable borrows.
381 macro_rules! record {
382     ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
383         {
384             let value = $value;
385             let lazy = $self.lazy(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<T: ?Sized + LazyMeta>(
393         &mut self,
394         lazy: Lazy<T>,
395     ) -> Result<(), <Self as Encoder>::Error> {
396         let min_end = lazy.position.get() + T::min_size(lazy.meta);
397         let distance = match self.lazy_state {
398             LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
399             LazyState::NodeStart(start) => {
400                 let start = start.get();
401                 assert!(min_end <= start);
402                 start - min_end
403             }
404             LazyState::Previous(last_min_end) => {
405                 assert!(
406                     last_min_end <= lazy.position,
407                     "make sure that the calls to `lazy*` \
408                      are in the same order as the metadata fields",
409                 );
410                 lazy.position.get() - last_min_end.get()
411             }
412         };
413         self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
414         self.emit_usize(distance)
415     }
416
417     fn lazy<T: ?Sized + LazyMeta>(
418         &mut self,
419         value: impl EncodeContentsForLazy<'a, 'tcx, T>,
420     ) -> Lazy<T> {
421         let pos = NonZeroUsize::new(self.position()).unwrap();
422
423         assert_eq!(self.lazy_state, LazyState::NoNode);
424         self.lazy_state = LazyState::NodeStart(pos);
425         let meta = value.encode_contents_for_lazy(self);
426         self.lazy_state = LazyState::NoNode;
427
428         assert!(pos.get() + <T>::min_size(meta) <= self.position());
429
430         Lazy::from_position_and_meta(pos, meta)
431     }
432
433     fn encode_info_for_items(&mut self) {
434         let krate = self.tcx.hir().krate();
435         self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.item.module, &krate.item.attrs);
436
437         // Proc-macro crates only export proc-macro items, which are looked
438         // up using `proc_macro_data`
439         if self.is_proc_macro {
440             return;
441         }
442
443         krate.visit_all_item_likes(&mut self.as_deep_visitor());
444         for macro_def in krate.exported_macros {
445             self.visit_macro_def(macro_def);
446         }
447     }
448
449     fn encode_def_path_table(&mut self) {
450         let table = self.tcx.hir().definitions().def_path_table();
451         if self.is_proc_macro {
452             for def_index in std::iter::once(CRATE_DEF_INDEX)
453                 .chain(self.tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index))
454             {
455                 let def_key = self.lazy(table.def_key(def_index));
456                 let def_path_hash = self.lazy(table.def_path_hash(def_index));
457                 self.tables.def_keys.set(def_index, def_key);
458                 self.tables.def_path_hashes.set(def_index, def_path_hash);
459             }
460         } else {
461             for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
462                 let def_key = self.lazy(def_key);
463                 let def_path_hash = self.lazy(def_path_hash);
464                 self.tables.def_keys.set(def_index, def_key);
465                 self.tables.def_path_hashes.set(def_index, def_path_hash);
466             }
467         }
468     }
469
470     fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
471         let source_map = self.tcx.sess.source_map();
472         let all_source_files = source_map.files();
473
474         let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
475         // By replacing the `Option` with `None`, we ensure that we can't
476         // accidentally serialize any more `Span`s after the source map encoding
477         // is done.
478         let required_source_files = self.required_source_files.take().unwrap();
479
480         let adapted = all_source_files
481             .iter()
482             .enumerate()
483             .filter(|(idx, source_file)| {
484                 // Only serialize `SourceFile`s that were used
485                 // during the encoding of a `Span`
486                 required_source_files.contains(*idx) &&
487                 // Don't serialize imported `SourceFile`s, unless
488                 // we're in a proc-macro crate.
489                 (!source_file.is_imported() || self.is_proc_macro)
490             })
491             .map(|(_, source_file)| {
492                 let mut adapted = match source_file.name {
493                     // This path of this SourceFile has been modified by
494                     // path-remapping, so we use it verbatim (and avoid
495                     // cloning the whole map in the process).
496                     _ if source_file.name_was_remapped => source_file.clone(),
497
498                     // Otherwise expand all paths to absolute paths because
499                     // any relative paths are potentially relative to a
500                     // wrong directory.
501                     FileName::Real(ref name) => {
502                         let name = name.stable_name();
503                         let mut adapted = (**source_file).clone();
504                         adapted.name = Path::new(&working_dir).join(name).into();
505                         adapted.name_hash = {
506                             let mut hasher: StableHasher = StableHasher::new();
507                             adapted.name.hash(&mut hasher);
508                             hasher.finish::<u128>()
509                         };
510                         Lrc::new(adapted)
511                     }
512
513                     // expanded code, not from a file
514                     _ => source_file.clone(),
515                 };
516
517                 // We're serializing this `SourceFile` into our crate metadata,
518                 // so mark it as coming from this crate.
519                 // This also ensures that we don't try to deserialize the
520                 // `CrateNum` for a proc-macro dependency - since proc macro
521                 // dependencies aren't loaded when we deserialize a proc-macro,
522                 // trying to remap the `CrateNum` would fail.
523                 if self.is_proc_macro {
524                     Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
525                 }
526                 adapted
527             })
528             .collect::<Vec<_>>();
529
530         self.lazy(adapted.iter().map(|rc| &**rc))
531     }
532
533     fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
534         let mut i = self.position();
535
536         // Encode the crate deps
537         let crate_deps = self.encode_crate_deps();
538         let dylib_dependency_formats = self.encode_dylib_dependency_formats();
539         let dep_bytes = self.position() - i;
540
541         // Encode the lib features.
542         i = self.position();
543         let lib_features = self.encode_lib_features();
544         let lib_feature_bytes = self.position() - i;
545
546         // Encode the language items.
547         i = self.position();
548         let lang_items = self.encode_lang_items();
549         let lang_items_missing = self.encode_lang_items_missing();
550         let lang_item_bytes = self.position() - i;
551
552         // Encode the diagnostic items.
553         i = self.position();
554         let diagnostic_items = self.encode_diagnostic_items();
555         let diagnostic_item_bytes = self.position() - i;
556
557         // Encode the native libraries used
558         i = self.position();
559         let native_libraries = self.encode_native_libraries();
560         let native_lib_bytes = self.position() - i;
561
562         let foreign_modules = self.encode_foreign_modules();
563
564         // Encode DefPathTable
565         i = self.position();
566         self.encode_def_path_table();
567         let def_path_table_bytes = self.position() - i;
568
569         // Encode the def IDs of impls, for coherence checking.
570         i = self.position();
571         let impls = self.encode_impls();
572         let impl_bytes = self.position() - i;
573
574         let tcx = self.tcx;
575
576         // Encode the items.
577         i = self.position();
578         self.encode_info_for_items();
579         let item_bytes = self.position() - i;
580
581         // Encode the allocation index
582         let interpret_alloc_index = {
583             let mut interpret_alloc_index = Vec::new();
584             let mut n = 0;
585             trace!("beginning to encode alloc ids");
586             loop {
587                 let new_n = self.interpret_allocs.len();
588                 // if we have found new ids, serialize those, too
589                 if n == new_n {
590                     // otherwise, abort
591                     break;
592                 }
593                 trace!("encoding {} further alloc ids", new_n - n);
594                 for idx in n..new_n {
595                     let id = self.interpret_allocs[idx];
596                     let pos = self.position() as u32;
597                     interpret_alloc_index.push(pos);
598                     interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
599                 }
600                 n = new_n;
601             }
602             self.lazy(interpret_alloc_index)
603         };
604
605         // Encode the proc macro data. This affects 'tables',
606         // so we need to do this before we encode the tables
607         i = self.position();
608         let proc_macro_data = self.encode_proc_macros();
609         let proc_macro_data_bytes = self.position() - i;
610
611         i = self.position();
612         let tables = self.tables.encode(&mut self.opaque);
613         let tables_bytes = self.position() - i;
614
615         // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
616         // this as late as possible to give the prefetching as much time as possible to complete.
617         i = self.position();
618         let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
619         let exported_symbols = self.encode_exported_symbols(&exported_symbols);
620         let exported_symbols_bytes = self.position() - i;
621
622         // Encode the hygiene data,
623         // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
624         // of encoding other items (e.g. `optimized_mir`) may cause us to load
625         // data from the incremental cache. If this causes us to deserialize a `Span`,
626         // then we may load additional `SyntaxContext`s into the global `HygieneData`.
627         // Therefore, we need to encode the hygiene data last to ensure that we encode
628         // any `SyntaxContext`s that might be used.
629         i = self.position();
630         let (syntax_contexts, expn_data) = self.encode_hygiene();
631         let hygiene_bytes = self.position() - i;
632
633         // Encode source_map. This needs to be done last,
634         // since encoding `Span`s tells us which `SourceFiles` we actually
635         // need to encode.
636         i = self.position();
637         let source_map = self.encode_source_map();
638         let source_map_bytes = self.position() - i;
639
640         let attrs = tcx.hir().krate_attrs();
641         let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
642
643         let root = self.lazy(CrateRoot {
644             name: tcx.crate_name(LOCAL_CRATE),
645             extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
646             triple: tcx.sess.opts.target_triple.clone(),
647             hash: tcx.crate_hash(LOCAL_CRATE),
648             disambiguator: tcx.sess.local_crate_disambiguator(),
649             panic_strategy: tcx.sess.panic_strategy(),
650             edition: tcx.sess.edition(),
651             has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
652             has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
653             has_default_lib_allocator,
654             plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
655             proc_macro_data,
656             compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
657             needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
658             needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
659             no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
660             panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
661             profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
662             symbol_mangling_version: tcx.sess.opts.debugging_opts.get_symbol_mangling_version(),
663
664             crate_deps,
665             dylib_dependency_formats,
666             lib_features,
667             lang_items,
668             diagnostic_items,
669             lang_items_missing,
670             native_libraries,
671             foreign_modules,
672             source_map,
673             impls,
674             exported_symbols,
675             interpret_alloc_index,
676             tables,
677             syntax_contexts,
678             expn_data,
679         });
680
681         let total_bytes = self.position();
682
683         if tcx.sess.meta_stats() {
684             let mut zero_bytes = 0;
685             for e in self.opaque.data.iter() {
686                 if *e == 0 {
687                     zero_bytes += 1;
688                 }
689             }
690
691             println!("metadata stats:");
692             println!("             dep bytes: {}", dep_bytes);
693             println!("     lib feature bytes: {}", lib_feature_bytes);
694             println!("       lang item bytes: {}", lang_item_bytes);
695             println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
696             println!("          native bytes: {}", native_lib_bytes);
697             println!("         source_map bytes: {}", source_map_bytes);
698             println!("            impl bytes: {}", impl_bytes);
699             println!("    exp. symbols bytes: {}", exported_symbols_bytes);
700             println!("  def-path table bytes: {}", def_path_table_bytes);
701             println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
702             println!("            item bytes: {}", item_bytes);
703             println!("           table bytes: {}", tables_bytes);
704             println!("         hygiene bytes: {}", hygiene_bytes);
705             println!("            zero bytes: {}", zero_bytes);
706             println!("           total bytes: {}", total_bytes);
707         }
708
709         root
710     }
711 }
712
713 impl EncodeContext<'a, 'tcx> {
714     fn encode_variances_of(&mut self, def_id: DefId) {
715         debug!("EncodeContext::encode_variances_of({:?})", def_id);
716         record!(self.tables.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
717     }
718
719     fn encode_item_type(&mut self, def_id: DefId) {
720         debug!("EncodeContext::encode_item_type({:?})", def_id);
721         record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
722     }
723
724     fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
725         let tcx = self.tcx;
726         let variant = &def.variants[index];
727         let def_id = variant.def_id;
728         debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
729
730         let data = VariantData {
731             ctor_kind: variant.ctor_kind,
732             discr: variant.discr,
733             ctor: variant.ctor_def_id.map(|did| did.index),
734             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
735         };
736
737         record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
738         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
739         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
740         record!(self.tables.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
741         record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
742         record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
743             assert!(f.did.is_local());
744             f.did.index
745         }));
746         self.encode_ident_span(def_id, variant.ident);
747         self.encode_stability(def_id);
748         self.encode_deprecation(def_id);
749         self.encode_item_type(def_id);
750         if variant.ctor_kind == CtorKind::Fn {
751             // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
752             if let Some(ctor_def_id) = variant.ctor_def_id {
753                 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
754             }
755             // FIXME(eddyb) is this ever used?
756             self.encode_variances_of(def_id);
757         }
758         self.encode_generics(def_id);
759         self.encode_explicit_predicates(def_id);
760         self.encode_inferred_outlives(def_id);
761         self.encode_optimized_mir(def_id.expect_local());
762         self.encode_promoted_mir(def_id.expect_local());
763     }
764
765     fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
766         let tcx = self.tcx;
767         let variant = &def.variants[index];
768         let def_id = variant.ctor_def_id.unwrap();
769         debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
770
771         // FIXME(eddyb) encode only the `CtorKind` for constructors.
772         let data = VariantData {
773             ctor_kind: variant.ctor_kind,
774             discr: variant.discr,
775             ctor: Some(def_id.index),
776             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
777         };
778
779         record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
780         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
781         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
782         self.encode_stability(def_id);
783         self.encode_deprecation(def_id);
784         self.encode_item_type(def_id);
785         if variant.ctor_kind == CtorKind::Fn {
786             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
787             self.encode_variances_of(def_id);
788         }
789         self.encode_generics(def_id);
790         self.encode_explicit_predicates(def_id);
791         self.encode_inferred_outlives(def_id);
792         self.encode_optimized_mir(def_id.expect_local());
793         self.encode_promoted_mir(def_id.expect_local());
794     }
795
796     fn encode_info_for_mod(&mut self, id: hir::HirId, md: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
797         let tcx = self.tcx;
798         let local_def_id = tcx.hir().local_def_id(id);
799         let def_id = local_def_id.to_def_id();
800         debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
801
802         // If we are encoding a proc-macro crates, `encode_info_for_mod` will
803         // only ever get called for the crate root. We still want to encode
804         // the crate root for consistency with other crates (some of the resolver
805         // code uses it). However, we skip encoding anything relating to child
806         // items - we encode information about proc-macros later on.
807         let reexports = if !self.is_proc_macro {
808             match tcx.module_exports(local_def_id) {
809                 Some(exports) => {
810                     let hir = self.tcx.hir();
811                     self.lazy(
812                         exports
813                             .iter()
814                             .map(|export| export.map_id(|id| hir.local_def_id_to_hir_id(id))),
815                     )
816                 }
817                 _ => Lazy::empty(),
818             }
819         } else {
820             Lazy::empty()
821         };
822
823         let data = ModData {
824             reexports,
825             expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
826         };
827
828         record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
829         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
830         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
831         record!(self.tables.attributes[def_id] <- attrs);
832         if self.is_proc_macro {
833             record!(self.tables.children[def_id] <- &[]);
834         } else {
835             record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
836                 tcx.hir().local_def_id(item_id.id).local_def_index
837             }));
838         }
839         self.encode_stability(def_id);
840         self.encode_deprecation(def_id);
841     }
842
843     fn encode_field(
844         &mut self,
845         adt_def: &ty::AdtDef,
846         variant_index: VariantIdx,
847         field_index: usize,
848     ) {
849         let tcx = self.tcx;
850         let variant = &adt_def.variants[variant_index];
851         let field = &variant.fields[field_index];
852
853         let def_id = field.did;
854         debug!("EncodeContext::encode_field({:?})", def_id);
855
856         let variant_id = tcx.hir().local_def_id_to_hir_id(variant.def_id.expect_local());
857         let variant_data = tcx.hir().expect_variant_data(variant_id);
858
859         record!(self.tables.kind[def_id] <- EntryKind::Field);
860         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
861         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
862         record!(self.tables.attributes[def_id] <- variant_data.fields()[field_index].attrs);
863         record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
864         self.encode_ident_span(def_id, field.ident);
865         self.encode_stability(def_id);
866         self.encode_deprecation(def_id);
867         self.encode_item_type(def_id);
868         self.encode_generics(def_id);
869         self.encode_explicit_predicates(def_id);
870         self.encode_inferred_outlives(def_id);
871     }
872
873     fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
874         debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
875         let tcx = self.tcx;
876         let variant = adt_def.non_enum_variant();
877
878         let data = VariantData {
879             ctor_kind: variant.ctor_kind,
880             discr: variant.discr,
881             ctor: Some(def_id.index),
882             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
883         };
884
885         record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
886         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
887         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
888         record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
889         self.encode_stability(def_id);
890         self.encode_deprecation(def_id);
891         self.encode_item_type(def_id);
892         if variant.ctor_kind == CtorKind::Fn {
893             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
894             self.encode_variances_of(def_id);
895         }
896         self.encode_generics(def_id);
897         self.encode_explicit_predicates(def_id);
898         self.encode_inferred_outlives(def_id);
899         self.encode_optimized_mir(def_id.expect_local());
900         self.encode_promoted_mir(def_id.expect_local());
901     }
902
903     fn encode_generics(&mut self, def_id: DefId) {
904         debug!("EncodeContext::encode_generics({:?})", def_id);
905         record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
906     }
907
908     fn encode_explicit_predicates(&mut self, def_id: DefId) {
909         debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
910         record!(self.tables.explicit_predicates[def_id] <-
911             self.tcx.explicit_predicates_of(def_id));
912     }
913
914     fn encode_inferred_outlives(&mut self, def_id: DefId) {
915         debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
916         let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
917         if !inferred_outlives.is_empty() {
918             record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
919         }
920     }
921
922     fn encode_super_predicates(&mut self, def_id: DefId) {
923         debug!("EncodeContext::encode_super_predicates({:?})", def_id);
924         record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
925     }
926
927     fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
928         debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
929         let bounds = self.tcx.explicit_item_bounds(def_id);
930         if !bounds.is_empty() {
931             record!(self.tables.explicit_item_bounds[def_id] <- bounds);
932         }
933     }
934
935     fn encode_info_for_trait_item(&mut self, def_id: DefId) {
936         debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
937         let tcx = self.tcx;
938
939         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
940         let ast_item = tcx.hir().expect_trait_item(hir_id);
941         let trait_item = tcx.associated_item(def_id);
942
943         let container = match trait_item.defaultness {
944             hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
945             hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
946             hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
947         };
948
949         record!(self.tables.kind[def_id] <- match trait_item.kind {
950             ty::AssocKind::Const => {
951                 let rendered = rustc_hir_pretty::to_string(
952                     &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
953                     |s| s.print_trait_item(ast_item)
954                 );
955                 let rendered_const = self.lazy(RenderedConst(rendered));
956
957                 EntryKind::AssocConst(
958                     container,
959                     Default::default(),
960                     rendered_const,
961                 )
962             }
963             ty::AssocKind::Fn => {
964                 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
965                     let param_names = match *m {
966                         hir::TraitFn::Required(ref names) => {
967                             self.encode_fn_param_names(names)
968                         }
969                         hir::TraitFn::Provided(body) => {
970                             self.encode_fn_param_names_for_body(body)
971                         }
972                     };
973                     FnData {
974                         asyncness: m_sig.header.asyncness,
975                         constness: hir::Constness::NotConst,
976                         param_names,
977                     }
978                 } else {
979                     bug!()
980                 };
981                 EntryKind::AssocFn(self.lazy(AssocFnData {
982                     fn_data,
983                     container,
984                     has_self: trait_item.fn_has_self_parameter,
985                 }))
986             }
987             ty::AssocKind::Type => {
988                 self.encode_explicit_item_bounds(def_id);
989                 EntryKind::AssocType(container)
990             }
991         });
992         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
993         record!(self.tables.span[def_id] <- ast_item.span);
994         record!(self.tables.attributes[def_id] <- ast_item.attrs);
995         self.encode_ident_span(def_id, ast_item.ident);
996         self.encode_stability(def_id);
997         self.encode_const_stability(def_id);
998         self.encode_deprecation(def_id);
999         match trait_item.kind {
1000             ty::AssocKind::Const | ty::AssocKind::Fn => {
1001                 self.encode_item_type(def_id);
1002             }
1003             ty::AssocKind::Type => {
1004                 if trait_item.defaultness.has_value() {
1005                     self.encode_item_type(def_id);
1006                 }
1007             }
1008         }
1009         if trait_item.kind == ty::AssocKind::Fn {
1010             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1011             self.encode_variances_of(def_id);
1012         }
1013         self.encode_generics(def_id);
1014         self.encode_explicit_predicates(def_id);
1015         self.encode_inferred_outlives(def_id);
1016
1017         // This should be kept in sync with `PrefetchVisitor.visit_trait_item`.
1018         self.encode_optimized_mir(def_id.expect_local());
1019         self.encode_promoted_mir(def_id.expect_local());
1020     }
1021
1022     fn metadata_output_only(&self) -> bool {
1023         // MIR optimisation can be skipped when we're just interested in the metadata.
1024         !self.tcx.sess.opts.output_types.should_codegen()
1025     }
1026
1027     fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1028         debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1029         let tcx = self.tcx;
1030
1031         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1032         let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1033         let impl_item = self.tcx.associated_item(def_id);
1034
1035         let container = match impl_item.defaultness {
1036             hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1037             hir::Defaultness::Final => AssocContainer::ImplFinal,
1038             hir::Defaultness::Default { has_value: false } => {
1039                 span_bug!(ast_item.span, "impl items always have values (currently)")
1040             }
1041         };
1042
1043         record!(self.tables.kind[def_id] <- match impl_item.kind {
1044             ty::AssocKind::Const => {
1045                 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1046                     let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1047
1048                     EntryKind::AssocConst(
1049                         container,
1050                         qualifs,
1051                         self.encode_rendered_const_for_body(body_id))
1052                 } else {
1053                     bug!()
1054                 }
1055             }
1056             ty::AssocKind::Fn => {
1057                 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1058                     FnData {
1059                         asyncness: sig.header.asyncness,
1060                         constness: sig.header.constness,
1061                         param_names: self.encode_fn_param_names_for_body(body),
1062                     }
1063                 } else {
1064                     bug!()
1065                 };
1066                 EntryKind::AssocFn(self.lazy(AssocFnData {
1067                     fn_data,
1068                     container,
1069                     has_self: impl_item.fn_has_self_parameter,
1070                 }))
1071             }
1072             ty::AssocKind::Type => EntryKind::AssocType(container)
1073         });
1074         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1075         record!(self.tables.span[def_id] <- ast_item.span);
1076         record!(self.tables.attributes[def_id] <- ast_item.attrs);
1077         self.encode_ident_span(def_id, impl_item.ident);
1078         self.encode_stability(def_id);
1079         self.encode_const_stability(def_id);
1080         self.encode_deprecation(def_id);
1081         self.encode_item_type(def_id);
1082         if impl_item.kind == ty::AssocKind::Fn {
1083             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1084             self.encode_variances_of(def_id);
1085         }
1086         self.encode_generics(def_id);
1087         self.encode_explicit_predicates(def_id);
1088         self.encode_inferred_outlives(def_id);
1089
1090         // The following part should be kept in sync with `PrefetchVisitor.visit_impl_item`.
1091
1092         let mir = match ast_item.kind {
1093             hir::ImplItemKind::Const(..) => true,
1094             hir::ImplItemKind::Fn(ref sig, _) => {
1095                 let generics = self.tcx.generics_of(def_id);
1096                 let needs_inline = (generics.requires_monomorphization(self.tcx)
1097                     || tcx.codegen_fn_attrs(def_id).requests_inline())
1098                     && !self.metadata_output_only();
1099                 let is_const_fn = sig.header.constness == hir::Constness::Const;
1100                 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1101                 needs_inline || is_const_fn || always_encode_mir
1102             }
1103             hir::ImplItemKind::TyAlias(..) => false,
1104         };
1105         if mir {
1106             self.encode_optimized_mir(def_id.expect_local());
1107             self.encode_promoted_mir(def_id.expect_local());
1108         }
1109     }
1110
1111     fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1112         self.lazy(self.tcx.hir().body_param_names(body_id))
1113     }
1114
1115     fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1116         self.lazy(param_names.iter())
1117     }
1118
1119     fn encode_optimized_mir(&mut self, def_id: LocalDefId) {
1120         debug!("EntryBuilder::encode_mir({:?})", def_id);
1121         if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1122             record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1123
1124             let unused = self.tcx.unused_generic_params(def_id);
1125             if !unused.is_empty() {
1126                 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1127             }
1128
1129             let abstract_const = self.tcx.mir_abstract_const(def_id);
1130             if let Ok(Some(abstract_const)) = abstract_const {
1131                 record!(self.tables.mir_abstract_consts[def_id.to_def_id()] <- abstract_const);
1132             }
1133         }
1134     }
1135
1136     fn encode_promoted_mir(&mut self, def_id: LocalDefId) {
1137         debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1138         if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1139             record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1140         }
1141     }
1142
1143     // Encodes the inherent implementations of a structure, enumeration, or trait.
1144     fn encode_inherent_implementations(&mut self, def_id: DefId) {
1145         debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1146         let implementations = self.tcx.inherent_impls(def_id);
1147         if !implementations.is_empty() {
1148             record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1149                 assert!(def_id.is_local());
1150                 def_id.index
1151             }));
1152         }
1153     }
1154
1155     fn encode_stability(&mut self, def_id: DefId) {
1156         debug!("EncodeContext::encode_stability({:?})", def_id);
1157
1158         // The query lookup can take a measurable amount of time in crates with many items. Check if
1159         // the stability attributes are even enabled before using their queries.
1160         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1161             if let Some(stab) = self.tcx.lookup_stability(def_id) {
1162                 record!(self.tables.stability[def_id] <- stab)
1163             }
1164         }
1165     }
1166
1167     fn encode_const_stability(&mut self, def_id: DefId) {
1168         debug!("EncodeContext::encode_const_stability({:?})", def_id);
1169
1170         // The query lookup can take a measurable amount of time in crates with many items. Check if
1171         // the stability attributes are even enabled before using their queries.
1172         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1173             if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1174                 record!(self.tables.const_stability[def_id] <- stab)
1175             }
1176         }
1177     }
1178
1179     fn encode_deprecation(&mut self, def_id: DefId) {
1180         debug!("EncodeContext::encode_deprecation({:?})", def_id);
1181         if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1182             record!(self.tables.deprecation[def_id] <- depr);
1183         }
1184     }
1185
1186     fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1187         let hir = self.tcx.hir();
1188         let body = hir.body(body_id);
1189         let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1190             s.print_expr(&body.value)
1191         });
1192         let rendered_const = &RenderedConst(rendered);
1193         self.lazy(rendered_const)
1194     }
1195
1196     fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1197         let tcx = self.tcx;
1198
1199         debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1200
1201         self.encode_ident_span(def_id, item.ident);
1202
1203         record!(self.tables.kind[def_id] <- match item.kind {
1204             hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1205             hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1206             hir::ItemKind::Const(_, body_id) => {
1207                 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1208                 EntryKind::Const(
1209                     qualifs,
1210                     self.encode_rendered_const_for_body(body_id)
1211                 )
1212             }
1213             hir::ItemKind::Fn(ref sig, .., body) => {
1214                 let data = FnData {
1215                     asyncness: sig.header.asyncness,
1216                     constness: sig.header.constness,
1217                     param_names: self.encode_fn_param_names_for_body(body),
1218                 };
1219
1220                 EntryKind::Fn(self.lazy(data))
1221             }
1222             hir::ItemKind::Mod(ref m) => {
1223                 return self.encode_info_for_mod(item.hir_id, m, &item.attrs);
1224             }
1225             hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1226             hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1227             hir::ItemKind::TyAlias(..) => EntryKind::Type,
1228             hir::ItemKind::OpaqueTy(..) => {
1229                 self.encode_explicit_item_bounds(def_id);
1230                 EntryKind::OpaqueTy
1231             }
1232             hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1233             hir::ItemKind::Struct(ref struct_def, _) => {
1234                 let adt_def = self.tcx.adt_def(def_id);
1235                 let variant = adt_def.non_enum_variant();
1236
1237                 // Encode def_ids for each field and method
1238                 // for methods, write all the stuff get_trait_method
1239                 // needs to know
1240                 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1241                     self.tcx.hir().local_def_id(ctor_hir_id).local_def_index
1242                 });
1243
1244                 EntryKind::Struct(self.lazy(VariantData {
1245                     ctor_kind: variant.ctor_kind,
1246                     discr: variant.discr,
1247                     ctor,
1248                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1249                 }), adt_def.repr)
1250             }
1251             hir::ItemKind::Union(..) => {
1252                 let adt_def = self.tcx.adt_def(def_id);
1253                 let variant = adt_def.non_enum_variant();
1254
1255                 EntryKind::Union(self.lazy(VariantData {
1256                     ctor_kind: variant.ctor_kind,
1257                     discr: variant.discr,
1258                     ctor: None,
1259                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1260                 }), adt_def.repr)
1261             }
1262             hir::ItemKind::Impl { defaultness, .. } => {
1263                 let trait_ref = self.tcx.impl_trait_ref(def_id);
1264                 let polarity = self.tcx.impl_polarity(def_id);
1265                 let parent = if let Some(trait_ref) = trait_ref {
1266                     let trait_def = self.tcx.trait_def(trait_ref.def_id);
1267                     trait_def.ancestors(self.tcx, def_id).ok()
1268                         .and_then(|mut an| an.nth(1).and_then(|node| {
1269                             match node {
1270                                 specialization_graph::Node::Impl(parent) => Some(parent),
1271                                 _ => None,
1272                             }
1273                         }))
1274                 } else {
1275                     None
1276                 };
1277
1278                 // if this is an impl of `CoerceUnsized`, create its
1279                 // "unsized info", else just store None
1280                 let coerce_unsized_info =
1281                     trait_ref.and_then(|t| {
1282                         if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1283                             Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1284                         } else {
1285                             None
1286                         }
1287                     });
1288
1289                 let data = ImplData {
1290                     polarity,
1291                     defaultness,
1292                     parent_impl: parent,
1293                     coerce_unsized_info,
1294                 };
1295
1296                 EntryKind::Impl(self.lazy(data))
1297             }
1298             hir::ItemKind::Trait(..) => {
1299                 let trait_def = self.tcx.trait_def(def_id);
1300                 let data = TraitData {
1301                     unsafety: trait_def.unsafety,
1302                     paren_sugar: trait_def.paren_sugar,
1303                     has_auto_impl: self.tcx.trait_is_auto(def_id),
1304                     is_marker: trait_def.is_marker,
1305                     specialization_kind: trait_def.specialization_kind,
1306                 };
1307
1308                 EntryKind::Trait(self.lazy(data))
1309             }
1310             hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1311             hir::ItemKind::ExternCrate(_) |
1312             hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1313         });
1314         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1315         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1316         record!(self.tables.attributes[def_id] <- item.attrs);
1317         record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
1318         // FIXME(eddyb) there should be a nicer way to do this.
1319         match item.kind {
1320             hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <-
1321                 items
1322                     .iter()
1323                     .map(|foreign_item| tcx.hir().local_def_id(
1324                         foreign_item.id.hir_id).local_def_index)
1325             ),
1326             hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1327                 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1328                     assert!(v.def_id.is_local());
1329                     v.def_id.index
1330                 })
1331             ),
1332             hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1333                 record!(self.tables.children[def_id] <-
1334                     self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1335                         assert!(f.did.is_local());
1336                         f.did.index
1337                     })
1338                 )
1339             }
1340             hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1341                 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1342                 record!(self.tables.children[def_id] <-
1343                     associated_item_def_ids.iter().map(|&def_id| {
1344                         assert!(def_id.is_local());
1345                         def_id.index
1346                     })
1347                 );
1348             }
1349             _ => {}
1350         }
1351         self.encode_stability(def_id);
1352         self.encode_const_stability(def_id);
1353         self.encode_deprecation(def_id);
1354         match item.kind {
1355             hir::ItemKind::Static(..)
1356             | hir::ItemKind::Const(..)
1357             | hir::ItemKind::Fn(..)
1358             | hir::ItemKind::TyAlias(..)
1359             | hir::ItemKind::OpaqueTy(..)
1360             | hir::ItemKind::Enum(..)
1361             | hir::ItemKind::Struct(..)
1362             | hir::ItemKind::Union(..)
1363             | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1364             _ => {}
1365         }
1366         if let hir::ItemKind::Fn(..) = item.kind {
1367             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1368         }
1369         if let hir::ItemKind::Impl { .. } = item.kind {
1370             if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1371                 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1372             }
1373         }
1374         self.encode_inherent_implementations(def_id);
1375         match item.kind {
1376             hir::ItemKind::Enum(..)
1377             | hir::ItemKind::Struct(..)
1378             | hir::ItemKind::Union(..)
1379             | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1380             _ => {}
1381         }
1382         match item.kind {
1383             hir::ItemKind::Static(..)
1384             | hir::ItemKind::Const(..)
1385             | hir::ItemKind::Fn(..)
1386             | hir::ItemKind::TyAlias(..)
1387             | hir::ItemKind::Enum(..)
1388             | hir::ItemKind::Struct(..)
1389             | hir::ItemKind::Union(..)
1390             | hir::ItemKind::Impl { .. }
1391             | hir::ItemKind::OpaqueTy(..)
1392             | hir::ItemKind::Trait(..)
1393             | hir::ItemKind::TraitAlias(..) => {
1394                 self.encode_generics(def_id);
1395                 self.encode_explicit_predicates(def_id);
1396                 self.encode_inferred_outlives(def_id);
1397             }
1398             _ => {}
1399         }
1400         match item.kind {
1401             hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1402                 self.encode_super_predicates(def_id);
1403             }
1404             _ => {}
1405         }
1406
1407         // The following part should be kept in sync with `PrefetchVisitor.visit_item`.
1408
1409         let mir = match item.kind {
1410             hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1411             hir::ItemKind::Fn(ref sig, ..) => {
1412                 let generics = tcx.generics_of(def_id);
1413                 let needs_inline = (generics.requires_monomorphization(tcx)
1414                     || tcx.codegen_fn_attrs(def_id).requests_inline())
1415                     && !self.metadata_output_only();
1416                 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1417                 needs_inline || sig.header.constness == hir::Constness::Const || always_encode_mir
1418             }
1419             _ => false,
1420         };
1421         if mir {
1422             self.encode_optimized_mir(def_id.expect_local());
1423             self.encode_promoted_mir(def_id.expect_local());
1424         }
1425     }
1426
1427     /// Serialize the text of exported macros
1428     fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1429         let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id();
1430         record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1431         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1432         record!(self.tables.span[def_id] <- macro_def.span);
1433         record!(self.tables.attributes[def_id] <- macro_def.attrs);
1434         self.encode_ident_span(def_id, macro_def.ident);
1435         self.encode_stability(def_id);
1436         self.encode_deprecation(def_id);
1437     }
1438
1439     fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1440         record!(self.tables.kind[def_id] <- kind);
1441         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1442         if encode_type {
1443             self.encode_item_type(def_id);
1444         }
1445     }
1446
1447     fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1448         debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1449
1450         // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1451         // including on the signature, which is inferred in `typeck.
1452         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1453         let ty = self.tcx.typeck(def_id).node_type(hir_id);
1454
1455         record!(self.tables.kind[def_id.to_def_id()] <- match ty.kind() {
1456             ty::Generator(..) => {
1457                 let data = self.tcx.generator_kind(def_id).unwrap();
1458                 EntryKind::Generator(data)
1459             }
1460
1461             ty::Closure(..) => EntryKind::Closure,
1462
1463             _ => bug!("closure that is neither generator nor closure"),
1464         });
1465         record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1466         record!(self.tables.attributes[def_id.to_def_id()] <- &self.tcx.get_attrs(def_id.to_def_id())[..]);
1467         self.encode_item_type(def_id.to_def_id());
1468         if let ty::Closure(def_id, substs) = *ty.kind() {
1469             record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1470         }
1471         self.encode_generics(def_id.to_def_id());
1472         self.encode_optimized_mir(def_id);
1473         self.encode_promoted_mir(def_id);
1474     }
1475
1476     fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1477         debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1478         let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1479         let body_id = self.tcx.hir().body_owned_by(id);
1480         let const_data = self.encode_rendered_const_for_body(body_id);
1481         let qualifs = self.tcx.mir_const_qualif(def_id);
1482
1483         record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1484         record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1485         self.encode_item_type(def_id.to_def_id());
1486         self.encode_generics(def_id.to_def_id());
1487         self.encode_explicit_predicates(def_id.to_def_id());
1488         self.encode_inferred_outlives(def_id.to_def_id());
1489         self.encode_optimized_mir(def_id);
1490         self.encode_promoted_mir(def_id);
1491     }
1492
1493     fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1494         empty_proc_macro!(self);
1495         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1496         self.lazy(used_libraries.iter().cloned())
1497     }
1498
1499     fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1500         empty_proc_macro!(self);
1501         let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1502         self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1503     }
1504
1505     fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) {
1506         let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1507         let mut expn_data_table: TableBuilder<_, _> = Default::default();
1508
1509         let _: Result<(), !> = self.hygiene_ctxt.encode(
1510             &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table),
1511             |(this, syntax_contexts, _), index, ctxt_data| {
1512                 syntax_contexts.set(index, this.lazy(ctxt_data));
1513                 Ok(())
1514             },
1515             |(this, _, expn_data_table), index, expn_data| {
1516                 expn_data_table.set(index, this.lazy(expn_data));
1517                 Ok(())
1518             },
1519         );
1520
1521         (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque))
1522     }
1523
1524     fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1525         let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1526         if is_proc_macro {
1527             let tcx = self.tcx;
1528             let hir = tcx.hir();
1529
1530             let proc_macro_decls_static = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap().index;
1531             let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1532             let macros = self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.local_def_index));
1533
1534             // Normally, this information is encoded when we walk the items
1535             // defined in this crate. However, we skip doing that for proc-macro crates,
1536             // so we manually encode just the information that we need
1537             for proc_macro in &hir.krate().proc_macros {
1538                 let id = proc_macro.owner.local_def_index;
1539                 let mut name = hir.name(*proc_macro);
1540                 let span = hir.span(*proc_macro);
1541                 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1542                 // so downstream crates need access to them.
1543                 let attrs = hir.attrs(*proc_macro);
1544                 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1545                     MacroKind::Bang
1546                 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1547                     MacroKind::Attr
1548                 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1549                     // This unwrap chain should have been checked by the proc-macro harness.
1550                     name = attr.meta_item_list().unwrap()[0]
1551                         .meta_item()
1552                         .unwrap()
1553                         .ident()
1554                         .unwrap()
1555                         .name;
1556                     MacroKind::Derive
1557                 } else {
1558                     bug!("Unknown proc-macro type for item {:?}", id);
1559                 };
1560
1561                 let mut def_key = self.tcx.hir().def_key(proc_macro.owner);
1562                 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1563
1564                 let def_id = DefId::local(id);
1565                 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1566                 record!(self.tables.attributes[def_id] <- attrs);
1567                 record!(self.tables.def_keys[def_id] <- def_key);
1568                 record!(self.tables.ident_span[def_id] <- span);
1569                 record!(self.tables.span[def_id] <- span);
1570                 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1571                 if let Some(stability) = stability {
1572                     record!(self.tables.stability[def_id] <- stability);
1573                 }
1574             }
1575
1576             Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1577         } else {
1578             None
1579         }
1580     }
1581
1582     fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1583         empty_proc_macro!(self);
1584         let crates = self.tcx.crates();
1585
1586         let mut deps = crates
1587             .iter()
1588             .map(|&cnum| {
1589                 let dep = CrateDep {
1590                     name: self.tcx.original_crate_name(cnum),
1591                     hash: self.tcx.crate_hash(cnum),
1592                     host_hash: self.tcx.crate_host_hash(cnum),
1593                     kind: self.tcx.dep_kind(cnum),
1594                     extra_filename: self.tcx.extra_filename(cnum),
1595                 };
1596                 (cnum, dep)
1597             })
1598             .collect::<Vec<_>>();
1599
1600         deps.sort_by_key(|&(cnum, _)| cnum);
1601
1602         {
1603             // Sanity-check the crate numbers
1604             let mut expected_cnum = 1;
1605             for &(n, _) in &deps {
1606                 assert_eq!(n, CrateNum::new(expected_cnum));
1607                 expected_cnum += 1;
1608             }
1609         }
1610
1611         // We're just going to write a list of crate 'name-hash-version's, with
1612         // the assumption that they are numbered 1 to n.
1613         // FIXME (#2166): This is not nearly enough to support correct versioning
1614         // but is enough to get transitive crate dependencies working.
1615         self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1616     }
1617
1618     fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1619         empty_proc_macro!(self);
1620         let tcx = self.tcx;
1621         let lib_features = tcx.lib_features();
1622         self.lazy(lib_features.to_vec())
1623     }
1624
1625     fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1626         empty_proc_macro!(self);
1627         let tcx = self.tcx;
1628         let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1629         self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1630     }
1631
1632     fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1633         empty_proc_macro!(self);
1634         let tcx = self.tcx;
1635         let lang_items = tcx.lang_items();
1636         let lang_items = lang_items.items().iter();
1637         self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1638             if let Some(def_id) = opt_def_id {
1639                 if def_id.is_local() {
1640                     return Some((def_id.index, i));
1641                 }
1642             }
1643             None
1644         }))
1645     }
1646
1647     fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1648         empty_proc_macro!(self);
1649         let tcx = self.tcx;
1650         self.lazy(&tcx.lang_items().missing)
1651     }
1652
1653     /// Encodes an index, mapping each trait to its (local) implementations.
1654     fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1655         empty_proc_macro!(self);
1656         debug!("EncodeContext::encode_impls()");
1657         let tcx = self.tcx;
1658         let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1659         tcx.hir().krate().visit_all_item_likes(&mut visitor);
1660
1661         let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1662
1663         // Bring everything into deterministic order for hashing
1664         all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1665
1666         let all_impls: Vec<_> = all_impls
1667             .into_iter()
1668             .map(|(trait_def_id, mut impls)| {
1669                 // Bring everything into deterministic order for hashing
1670                 impls.sort_by_cached_key(|&(index, _)| {
1671                     tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1672                 });
1673
1674                 TraitImpls {
1675                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1676                     impls: self.lazy(&impls),
1677                 }
1678             })
1679             .collect();
1680
1681         self.lazy(&all_impls)
1682     }
1683
1684     // Encodes all symbols exported from this crate into the metadata.
1685     //
1686     // This pass is seeded off the reachability list calculated in the
1687     // middle::reachable module but filters out items that either don't have a
1688     // symbol associated with them (they weren't translated) or if they're an FFI
1689     // definition (as that's not defined in this crate).
1690     fn encode_exported_symbols(
1691         &mut self,
1692         exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1693     ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1694         empty_proc_macro!(self);
1695         // The metadata symbol name is special. It should not show up in
1696         // downstream crates.
1697         let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1698
1699         self.lazy(
1700             exported_symbols
1701                 .iter()
1702                 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1703                     ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1704                     _ => true,
1705                 })
1706                 .cloned(),
1707         )
1708     }
1709
1710     fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1711         empty_proc_macro!(self);
1712         let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1713         for (ty, arr) in formats.iter() {
1714             if *ty != CrateType::Dylib {
1715                 continue;
1716             }
1717             return self.lazy(arr.iter().map(|slot| match *slot {
1718                 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1719
1720                 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1721                 Linkage::Static => Some(LinkagePreference::RequireStatic),
1722             }));
1723         }
1724         Lazy::empty()
1725     }
1726
1727     fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1728         let tcx = self.tcx;
1729
1730         debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1731
1732         record!(self.tables.kind[def_id] <- match nitem.kind {
1733             hir::ForeignItemKind::Fn(_, ref names, _) => {
1734                 let data = FnData {
1735                     asyncness: hir::IsAsync::NotAsync,
1736                     constness: if self.tcx.is_const_fn_raw(def_id) {
1737                         hir::Constness::Const
1738                     } else {
1739                         hir::Constness::NotConst
1740                     },
1741                     param_names: self.encode_fn_param_names(names),
1742                 };
1743                 EntryKind::ForeignFn(self.lazy(data))
1744             }
1745             hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1746             hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1747             hir::ForeignItemKind::Type => EntryKind::ForeignType,
1748         });
1749         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1750         record!(self.tables.span[def_id] <- nitem.span);
1751         record!(self.tables.attributes[def_id] <- nitem.attrs);
1752         self.encode_ident_span(def_id, nitem.ident);
1753         self.encode_stability(def_id);
1754         self.encode_const_stability(def_id);
1755         self.encode_deprecation(def_id);
1756         self.encode_item_type(def_id);
1757         self.encode_inherent_implementations(def_id);
1758         if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1759             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1760             self.encode_variances_of(def_id);
1761         }
1762         self.encode_generics(def_id);
1763         self.encode_explicit_predicates(def_id);
1764         self.encode_inferred_outlives(def_id);
1765     }
1766 }
1767
1768 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1769 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1770     type Map = Map<'tcx>;
1771
1772     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1773         NestedVisitorMap::OnlyBodies(self.tcx.hir())
1774     }
1775     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1776         intravisit::walk_expr(self, ex);
1777         self.encode_info_for_expr(ex);
1778     }
1779     fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1780         intravisit::walk_anon_const(self, c);
1781         let def_id = self.tcx.hir().local_def_id(c.hir_id);
1782         self.encode_info_for_anon_const(def_id);
1783     }
1784     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1785         intravisit::walk_item(self, item);
1786         let def_id = self.tcx.hir().local_def_id(item.hir_id);
1787         match item.kind {
1788             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1789             _ => self.encode_info_for_item(def_id.to_def_id(), item),
1790         }
1791         self.encode_addl_info_for_item(item);
1792     }
1793     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1794         intravisit::walk_foreign_item(self, ni);
1795         let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1796         self.encode_info_for_foreign_item(def_id.to_def_id(), ni);
1797     }
1798     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1799         intravisit::walk_generics(self, generics);
1800         self.encode_info_for_generics(generics);
1801     }
1802     fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1803         self.encode_info_for_macro_def(macro_def);
1804     }
1805 }
1806
1807 impl EncodeContext<'a, 'tcx> {
1808     fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1809         for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1810             for (field_index, _field) in variant.fields.iter().enumerate() {
1811                 self.encode_field(adt_def, variant_index, field_index);
1812             }
1813         }
1814     }
1815
1816     fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1817         for param in generics.params {
1818             let def_id = self.tcx.hir().local_def_id(param.hir_id);
1819             match param.kind {
1820                 GenericParamKind::Lifetime { .. } => continue,
1821                 GenericParamKind::Type { ref default, .. } => {
1822                     self.encode_info_for_generic_param(
1823                         def_id.to_def_id(),
1824                         EntryKind::TypeParam,
1825                         default.is_some(),
1826                     );
1827                     if default.is_some() {
1828                         self.encode_stability(def_id.to_def_id());
1829                     }
1830                 }
1831                 GenericParamKind::Const { .. } => {
1832                     self.encode_info_for_generic_param(
1833                         def_id.to_def_id(),
1834                         EntryKind::ConstParam,
1835                         true,
1836                     );
1837                     // FIXME(const_generics:defaults)
1838                 }
1839             }
1840         }
1841     }
1842
1843     fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1844         if let hir::ExprKind::Closure(..) = expr.kind {
1845             let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1846             self.encode_info_for_closure(def_id);
1847         }
1848     }
1849
1850     fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1851         record!(self.tables.ident_span[def_id] <- ident.span);
1852     }
1853
1854     /// In some cases, along with the item itself, we also
1855     /// encode some sub-items. Usually we want some info from the item
1856     /// so it's easier to do that here then to wait until we would encounter
1857     /// normally in the visitor walk.
1858     fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1859         let def_id = self.tcx.hir().local_def_id(item.hir_id);
1860         match item.kind {
1861             hir::ItemKind::Static(..)
1862             | hir::ItemKind::Const(..)
1863             | hir::ItemKind::Fn(..)
1864             | hir::ItemKind::Mod(..)
1865             | hir::ItemKind::ForeignMod { .. }
1866             | hir::ItemKind::GlobalAsm(..)
1867             | hir::ItemKind::ExternCrate(..)
1868             | hir::ItemKind::Use(..)
1869             | hir::ItemKind::TyAlias(..)
1870             | hir::ItemKind::OpaqueTy(..)
1871             | hir::ItemKind::TraitAlias(..) => {
1872                 // no sub-item recording needed in these cases
1873             }
1874             hir::ItemKind::Enum(..) => {
1875                 let def = self.tcx.adt_def(def_id.to_def_id());
1876                 self.encode_fields(def);
1877
1878                 for (i, variant) in def.variants.iter_enumerated() {
1879                     self.encode_enum_variant_info(def, i);
1880
1881                     if let Some(_ctor_def_id) = variant.ctor_def_id {
1882                         self.encode_enum_variant_ctor(def, i);
1883                     }
1884                 }
1885             }
1886             hir::ItemKind::Struct(ref struct_def, _) => {
1887                 let def = self.tcx.adt_def(def_id.to_def_id());
1888                 self.encode_fields(def);
1889
1890                 // If the struct has a constructor, encode it.
1891                 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1892                     let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1893                     self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1894                 }
1895             }
1896             hir::ItemKind::Union(..) => {
1897                 let def = self.tcx.adt_def(def_id.to_def_id());
1898                 self.encode_fields(def);
1899             }
1900             hir::ItemKind::Impl { .. } => {
1901                 for &trait_item_def_id in
1902                     self.tcx.associated_item_def_ids(def_id.to_def_id()).iter()
1903                 {
1904                     self.encode_info_for_impl_item(trait_item_def_id);
1905                 }
1906             }
1907             hir::ItemKind::Trait(..) => {
1908                 for &item_def_id in self.tcx.associated_item_def_ids(def_id.to_def_id()).iter() {
1909                     self.encode_info_for_trait_item(item_def_id);
1910                 }
1911             }
1912         }
1913     }
1914 }
1915
1916 struct ImplVisitor<'tcx> {
1917     tcx: TyCtxt<'tcx>,
1918     impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
1919 }
1920
1921 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1922     fn visit_item(&mut self, item: &hir::Item<'_>) {
1923         if let hir::ItemKind::Impl { .. } = item.kind {
1924             let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1925             if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id.to_def_id()) {
1926                 let simplified_self_ty =
1927                     ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
1928
1929                 self.impls
1930                     .entry(trait_ref.def_id)
1931                     .or_default()
1932                     .push((impl_id.local_def_index, simplified_self_ty));
1933             }
1934         }
1935     }
1936
1937     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1938
1939     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1940         // handled in `visit_item` above
1941     }
1942
1943     fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
1944 }
1945
1946 /// Used to prefetch queries which will be needed later by metadata encoding.
1947 /// Only a subset of the queries are actually prefetched to keep this code smaller.
1948 struct PrefetchVisitor<'tcx> {
1949     tcx: TyCtxt<'tcx>,
1950     mir_keys: &'tcx FxHashSet<LocalDefId>,
1951 }
1952
1953 impl<'tcx> PrefetchVisitor<'tcx> {
1954     fn prefetch_mir(&self, def_id: LocalDefId) {
1955         if self.mir_keys.contains(&def_id) {
1956             self.tcx.ensure().optimized_mir(def_id);
1957             self.tcx.ensure().promoted_mir(def_id);
1958         }
1959     }
1960 }
1961
1962 impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> {
1963     fn visit_item(&self, item: &hir::Item<'_>) {
1964         // This should be kept in sync with `encode_info_for_item`.
1965         let tcx = self.tcx;
1966         match item.kind {
1967             hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
1968                 self.prefetch_mir(tcx.hir().local_def_id(item.hir_id))
1969             }
1970             hir::ItemKind::Fn(ref sig, ..) => {
1971                 let def_id = tcx.hir().local_def_id(item.hir_id);
1972                 let generics = tcx.generics_of(def_id.to_def_id());
1973                 let needs_inline = generics.requires_monomorphization(tcx)
1974                     || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1975                 if needs_inline || sig.header.constness == hir::Constness::Const {
1976                     self.prefetch_mir(def_id)
1977                 }
1978             }
1979             _ => (),
1980         }
1981     }
1982
1983     fn visit_trait_item(&self, trait_item: &'v hir::TraitItem<'v>) {
1984         // This should be kept in sync with `encode_info_for_trait_item`.
1985         self.prefetch_mir(self.tcx.hir().local_def_id(trait_item.hir_id));
1986     }
1987
1988     fn visit_impl_item(&self, impl_item: &'v hir::ImplItem<'v>) {
1989         // This should be kept in sync with `encode_info_for_impl_item`.
1990         let tcx = self.tcx;
1991         match impl_item.kind {
1992             hir::ImplItemKind::Const(..) => {
1993                 self.prefetch_mir(tcx.hir().local_def_id(impl_item.hir_id))
1994             }
1995             hir::ImplItemKind::Fn(ref sig, _) => {
1996                 let def_id = tcx.hir().local_def_id(impl_item.hir_id);
1997                 let generics = tcx.generics_of(def_id.to_def_id());
1998                 let needs_inline = generics.requires_monomorphization(tcx)
1999                     || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
2000                 let is_const_fn = sig.header.constness == hir::Constness::Const;
2001                 if needs_inline || is_const_fn {
2002                     self.prefetch_mir(def_id)
2003                 }
2004             }
2005             hir::ImplItemKind::TyAlias(..) => (),
2006         }
2007     }
2008
2009     fn visit_foreign_item(&self, _foreign_item: &'v hir::ForeignItem<'v>) {
2010         // This should be kept in sync with `encode_info_for_foreign_item`.
2011         // Foreign items contain no MIR.
2012     }
2013 }
2014
2015 // NOTE(eddyb) The following comment was preserved for posterity, even
2016 // though it's no longer relevant as EBML (which uses nested & tagged
2017 // "documents") was replaced with a scheme that can't go out of bounds.
2018 //
2019 // And here we run into yet another obscure archive bug: in which metadata
2020 // loaded from archives may have trailing garbage bytes. Awhile back one of
2021 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2022 // and opt) by having ebml generate an out-of-bounds panic when looking at
2023 // metadata.
2024 //
2025 // Upon investigation it turned out that the metadata file inside of an rlib
2026 // (and ar archive) was being corrupted. Some compilations would generate a
2027 // metadata file which would end in a few extra bytes, while other
2028 // compilations would not have these extra bytes appended to the end. These
2029 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2030 // being interpreted causing the out-of-bounds.
2031 //
2032 // The root cause of why these extra bytes were appearing was never
2033 // discovered, and in the meantime the solution we're employing is to insert
2034 // the length of the metadata to the start of the metadata. Later on this
2035 // will allow us to slice the metadata to the precise length that we just
2036 // generated regardless of trailing bytes that end up in it.
2037
2038 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2039     // Since encoding metadata is not in a query, and nothing is cached,
2040     // there's no need to do dep-graph tracking for any of it.
2041     tcx.dep_graph.assert_ignored();
2042
2043     join(
2044         || encode_metadata_impl(tcx),
2045         || {
2046             if tcx.sess.threads() == 1 {
2047                 return;
2048             }
2049             // Prefetch some queries used by metadata encoding.
2050             // This is not necessary for correctness, but is only done for performance reasons.
2051             // It can be removed if it turns out to cause trouble or be detrimental to performance.
2052             join(
2053                 || {
2054                     if !tcx.sess.opts.output_types.should_codegen() {
2055                         // We won't emit MIR, so don't prefetch it.
2056                         return;
2057                     }
2058                     tcx.hir().krate().par_visit_all_item_likes(&PrefetchVisitor {
2059                         tcx,
2060                         mir_keys: tcx.mir_keys(LOCAL_CRATE),
2061                     });
2062                 },
2063                 || tcx.exported_symbols(LOCAL_CRATE),
2064             );
2065         },
2066     )
2067     .0
2068 }
2069
2070 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2071     let mut encoder = opaque::Encoder::new(vec![]);
2072     encoder.emit_raw_bytes(METADATA_HEADER);
2073
2074     // Will be filled with the root position after encoding everything.
2075     encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2076
2077     let source_map_files = tcx.sess.source_map().files();
2078     let source_file_cache = (source_map_files[0].clone(), 0);
2079     let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2080     drop(source_map_files);
2081
2082     let hygiene_ctxt = HygieneEncodeContext::default();
2083
2084     let mut ecx = EncodeContext {
2085         opaque: encoder,
2086         tcx,
2087         feat: tcx.features(),
2088         tables: Default::default(),
2089         lazy_state: LazyState::NoNode,
2090         type_shorthands: Default::default(),
2091         predicate_shorthands: Default::default(),
2092         source_file_cache,
2093         interpret_allocs: Default::default(),
2094         required_source_files,
2095         is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2096         hygiene_ctxt: &hygiene_ctxt,
2097     };
2098
2099     // Encode the rustc version string in a predictable location.
2100     rustc_version().encode(&mut ecx).unwrap();
2101
2102     // Encode all the entries and extra information in the crate,
2103     // culminating in the `CrateRoot` which points to all of it.
2104     let root = ecx.encode_crate_root();
2105
2106     let mut result = ecx.opaque.into_inner();
2107
2108     // Encode the root position.
2109     let header = METADATA_HEADER.len();
2110     let pos = root.position.get();
2111     result[header + 0] = (pos >> 24) as u8;
2112     result[header + 1] = (pos >> 16) as u8;
2113     result[header + 2] = (pos >> 8) as u8;
2114     result[header + 3] = (pos >> 0) as u8;
2115
2116     EncodedMetadata { raw_data: result }
2117 }