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