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