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