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