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