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