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