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