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