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