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