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