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