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