]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/encoder.rs
Rollup merge of #88624 - kellerkindt:master, r=JohnTitor
[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 instance =
1323                 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1324             let unused = self.tcx.unused_generic_params(instance);
1325             if !unused.is_empty() {
1326                 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1327             }
1328         }
1329     }
1330
1331     fn encode_stability(&mut self, def_id: DefId) {
1332         debug!("EncodeContext::encode_stability({:?})", def_id);
1333
1334         // The query lookup can take a measurable amount of time in crates with many items. Check if
1335         // the stability attributes are even enabled before using their queries.
1336         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1337             if let Some(stab) = self.tcx.lookup_stability(def_id) {
1338                 record!(self.tables.stability[def_id] <- stab)
1339             }
1340         }
1341     }
1342
1343     fn encode_const_stability(&mut self, def_id: DefId) {
1344         debug!("EncodeContext::encode_const_stability({:?})", def_id);
1345
1346         // The query lookup can take a measurable amount of time in crates with many items. Check if
1347         // the stability attributes are even enabled before using their queries.
1348         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1349             if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1350                 record!(self.tables.const_stability[def_id] <- stab)
1351             }
1352         }
1353     }
1354
1355     fn encode_deprecation(&mut self, def_id: DefId) {
1356         debug!("EncodeContext::encode_deprecation({:?})", def_id);
1357         if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1358             record!(self.tables.deprecation[def_id] <- depr);
1359         }
1360     }
1361
1362     fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1363         let hir = self.tcx.hir();
1364         let body = hir.body(body_id);
1365         let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1366             s.print_expr(&body.value)
1367         });
1368         let rendered_const = &RenderedConst(rendered);
1369         self.lazy(rendered_const)
1370     }
1371
1372     fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1373         let tcx = self.tcx;
1374
1375         debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1376
1377         self.encode_ident_span(def_id, item.ident);
1378
1379         let entry_kind = match item.kind {
1380             hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1381             hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1382             hir::ItemKind::Const(_, body_id) => {
1383                 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1384                 EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id))
1385             }
1386             hir::ItemKind::Fn(ref sig, .., body) => {
1387                 let data = FnData {
1388                     asyncness: sig.header.asyncness,
1389                     constness: sig.header.constness,
1390                     param_names: self.encode_fn_param_names_for_body(body),
1391                 };
1392
1393                 EntryKind::Fn(self.lazy(data))
1394             }
1395             hir::ItemKind::Macro(ref macro_def) => {
1396                 EntryKind::MacroDef(self.lazy(macro_def.clone()))
1397             }
1398             hir::ItemKind::Mod(ref m) => {
1399                 return self.encode_info_for_mod(item.def_id, m);
1400             }
1401             hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1402             hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1403             hir::ItemKind::TyAlias(..) => EntryKind::Type,
1404             hir::ItemKind::OpaqueTy(..) => {
1405                 self.encode_explicit_item_bounds(def_id);
1406                 EntryKind::OpaqueTy
1407             }
1408             hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1409             hir::ItemKind::Struct(ref struct_def, _) => {
1410                 let adt_def = self.tcx.adt_def(def_id);
1411                 let variant = adt_def.non_enum_variant();
1412
1413                 // Encode def_ids for each field and method
1414                 // for methods, write all the stuff get_trait_method
1415                 // needs to know
1416                 let ctor = struct_def
1417                     .ctor_hir_id()
1418                     .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1419
1420                 EntryKind::Struct(
1421                     self.lazy(VariantData {
1422                         ctor_kind: variant.ctor_kind,
1423                         discr: variant.discr,
1424                         ctor,
1425                         is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1426                     }),
1427                     adt_def.repr,
1428                 )
1429             }
1430             hir::ItemKind::Union(..) => {
1431                 let adt_def = self.tcx.adt_def(def_id);
1432                 let variant = adt_def.non_enum_variant();
1433
1434                 EntryKind::Union(
1435                     self.lazy(VariantData {
1436                         ctor_kind: variant.ctor_kind,
1437                         discr: variant.discr,
1438                         ctor: None,
1439                         is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1440                     }),
1441                     adt_def.repr,
1442                 )
1443             }
1444             hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1445                 let trait_ref = self.tcx.impl_trait_ref(def_id);
1446                 let polarity = self.tcx.impl_polarity(def_id);
1447                 let parent = if let Some(trait_ref) = trait_ref {
1448                     let trait_def = self.tcx.trait_def(trait_ref.def_id);
1449                     trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| {
1450                         an.nth(1).and_then(|node| match node {
1451                             specialization_graph::Node::Impl(parent) => Some(parent),
1452                             _ => None,
1453                         })
1454                     })
1455                 } else {
1456                     None
1457                 };
1458
1459                 // if this is an impl of `CoerceUnsized`, create its
1460                 // "unsized info", else just store None
1461                 let coerce_unsized_info = trait_ref.and_then(|t| {
1462                     if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1463                         Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1464                     } else {
1465                         None
1466                     }
1467                 });
1468
1469                 let data = ImplData {
1470                     polarity,
1471                     defaultness,
1472                     constness,
1473                     parent_impl: parent,
1474                     coerce_unsized_info,
1475                 };
1476
1477                 EntryKind::Impl(self.lazy(data))
1478             }
1479             hir::ItemKind::Trait(..) => {
1480                 let trait_def = self.tcx.trait_def(def_id);
1481                 let data = TraitData {
1482                     unsafety: trait_def.unsafety,
1483                     paren_sugar: trait_def.paren_sugar,
1484                     has_auto_impl: self.tcx.trait_is_auto(def_id),
1485                     is_marker: trait_def.is_marker,
1486                     skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch,
1487                     specialization_kind: trait_def.specialization_kind,
1488                 };
1489
1490                 EntryKind::Trait(self.lazy(data))
1491             }
1492             hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1493             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1494                 bug!("cannot encode info for item {:?}", item)
1495             }
1496         };
1497         record!(self.tables.kind[def_id] <- entry_kind);
1498         // FIXME(eddyb) there should be a nicer way to do this.
1499         match item.kind {
1500             hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <-
1501                 items
1502                     .iter()
1503                     .map(|foreign_item| foreign_item.id.def_id.local_def_index)
1504             ),
1505             hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1506                 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1507                     assert!(v.def_id.is_local());
1508                     v.def_id.index
1509                 })
1510             ),
1511             hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1512                 record!(self.tables.children[def_id] <-
1513                     self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1514                         assert!(f.did.is_local());
1515                         f.did.index
1516                     })
1517                 )
1518             }
1519             hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1520                 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1521                 record!(self.tables.children[def_id] <-
1522                     associated_item_def_ids.iter().map(|&def_id| {
1523                         assert!(def_id.is_local());
1524                         def_id.index
1525                     })
1526                 );
1527             }
1528             _ => {}
1529         }
1530         match item.kind {
1531             hir::ItemKind::Static(..)
1532             | hir::ItemKind::Const(..)
1533             | hir::ItemKind::Fn(..)
1534             | hir::ItemKind::TyAlias(..)
1535             | hir::ItemKind::OpaqueTy(..)
1536             | hir::ItemKind::Enum(..)
1537             | hir::ItemKind::Struct(..)
1538             | hir::ItemKind::Union(..)
1539             | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1540             _ => {}
1541         }
1542         if let hir::ItemKind::Fn(..) = item.kind {
1543             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1544         }
1545         if let hir::ItemKind::Impl { .. } = item.kind {
1546             if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1547                 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1548             }
1549         }
1550     }
1551
1552     fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1553         record!(self.tables.kind[def_id] <- kind);
1554         if encode_type {
1555             self.encode_item_type(def_id);
1556         }
1557     }
1558
1559     fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1560         debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1561
1562         // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1563         // including on the signature, which is inferred in `typeck.
1564         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1565         let ty = self.tcx.typeck(def_id).node_type(hir_id);
1566
1567         match ty.kind() {
1568             ty::Generator(..) => {
1569                 let data = self.tcx.generator_kind(def_id).unwrap();
1570                 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data));
1571             }
1572
1573             ty::Closure(..) => {
1574                 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1575             }
1576
1577             _ => bug!("closure that is neither generator nor closure"),
1578         }
1579         self.encode_item_type(def_id.to_def_id());
1580         if let ty::Closure(def_id, substs) = *ty.kind() {
1581             record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1582         }
1583     }
1584
1585     fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1586         debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1587         let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1588         let body_id = self.tcx.hir().body_owned_by(id);
1589         let const_data = self.encode_rendered_const_for_body(body_id);
1590         let qualifs = self.tcx.mir_const_qualif(def_id);
1591
1592         record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1593         self.encode_item_type(def_id.to_def_id());
1594     }
1595
1596     fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1597         empty_proc_macro!(self);
1598         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1599         self.lazy(used_libraries.iter())
1600     }
1601
1602     fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1603         empty_proc_macro!(self);
1604         let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1605         self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1606     }
1607
1608     fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1609         let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1610         let mut expn_data_table: TableBuilder<_, _> = Default::default();
1611         let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1612
1613         let _: Result<(), !> = self.hygiene_ctxt.encode(
1614             &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1615             |(this, syntax_contexts, _, _), index, ctxt_data| {
1616                 syntax_contexts.set(index, this.lazy(ctxt_data));
1617                 Ok(())
1618             },
1619             |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1620                 if let Some(index) = index.as_local() {
1621                     expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1622                     expn_hash_table.set(index.as_raw(), this.lazy(hash));
1623                 }
1624                 Ok(())
1625             },
1626         );
1627
1628         (
1629             syntax_contexts.encode(&mut self.opaque),
1630             expn_data_table.encode(&mut self.opaque),
1631             expn_hash_table.encode(&mut self.opaque),
1632         )
1633     }
1634
1635     fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1636         let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1637         if is_proc_macro {
1638             let tcx = self.tcx;
1639             let hir = tcx.hir();
1640
1641             let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1642             let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1643             let macros =
1644                 self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1645             let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1646             for (i, span) in spans.into_iter().enumerate() {
1647                 let span = self.lazy(span);
1648                 self.tables.proc_macro_quoted_spans.set(i, span);
1649             }
1650
1651             record!(self.tables.def_kind[LOCAL_CRATE.as_def_id()] <- DefKind::Mod);
1652             record!(self.tables.span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1653             record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id()));
1654             record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1655             if let Some(stability) = stability {
1656                 record!(self.tables.stability[LOCAL_CRATE.as_def_id()] <- stability);
1657             }
1658             self.encode_deprecation(LOCAL_CRATE.as_def_id());
1659
1660             // Normally, this information is encoded when we walk the items
1661             // defined in this crate. However, we skip doing that for proc-macro crates,
1662             // so we manually encode just the information that we need
1663             for &proc_macro in &tcx.resolutions(()).proc_macros {
1664                 let id = proc_macro;
1665                 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1666                 let mut name = hir.name(proc_macro);
1667                 let span = hir.span(proc_macro);
1668                 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1669                 // so downstream crates need access to them.
1670                 let attrs = hir.attrs(proc_macro);
1671                 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1672                     MacroKind::Bang
1673                 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1674                     MacroKind::Attr
1675                 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1676                     // This unwrap chain should have been checked by the proc-macro harness.
1677                     name = attr.meta_item_list().unwrap()[0]
1678                         .meta_item()
1679                         .unwrap()
1680                         .ident()
1681                         .unwrap()
1682                         .name;
1683                     MacroKind::Derive
1684                 } else {
1685                     bug!("Unknown proc-macro type for item {:?}", id);
1686                 };
1687
1688                 let mut def_key = self.tcx.hir().def_key(id);
1689                 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1690
1691                 let def_id = id.to_def_id();
1692                 record!(self.tables.def_kind[def_id] <- DefKind::Macro(macro_kind));
1693                 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1694                 record!(self.tables.attributes[def_id] <- attrs);
1695                 record!(self.tables.def_keys[def_id] <- def_key);
1696                 record!(self.tables.ident_span[def_id] <- span);
1697                 record!(self.tables.span[def_id] <- span);
1698                 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1699                 if let Some(stability) = stability {
1700                     record!(self.tables.stability[def_id] <- stability);
1701                 }
1702             }
1703
1704             Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1705         } else {
1706             None
1707         }
1708     }
1709
1710     fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1711         empty_proc_macro!(self);
1712
1713         let deps = self
1714             .tcx
1715             .crates(())
1716             .iter()
1717             .map(|&cnum| {
1718                 let dep = CrateDep {
1719                     name: self.tcx.crate_name(cnum),
1720                     hash: self.tcx.crate_hash(cnum),
1721                     host_hash: self.tcx.crate_host_hash(cnum),
1722                     kind: self.tcx.dep_kind(cnum),
1723                     extra_filename: self.tcx.extra_filename(cnum),
1724                 };
1725                 (cnum, dep)
1726             })
1727             .collect::<Vec<_>>();
1728
1729         {
1730             // Sanity-check the crate numbers
1731             let mut expected_cnum = 1;
1732             for &(n, _) in &deps {
1733                 assert_eq!(n, CrateNum::new(expected_cnum));
1734                 expected_cnum += 1;
1735             }
1736         }
1737
1738         // We're just going to write a list of crate 'name-hash-version's, with
1739         // the assumption that they are numbered 1 to n.
1740         // FIXME (#2166): This is not nearly enough to support correct versioning
1741         // but is enough to get transitive crate dependencies working.
1742         self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1743     }
1744
1745     fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1746         empty_proc_macro!(self);
1747         let tcx = self.tcx;
1748         let lib_features = tcx.lib_features();
1749         self.lazy(lib_features.to_vec())
1750     }
1751
1752     fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1753         empty_proc_macro!(self);
1754         let tcx = self.tcx;
1755         let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1756         self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1757     }
1758
1759     fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1760         empty_proc_macro!(self);
1761         let tcx = self.tcx;
1762         let lang_items = tcx.lang_items();
1763         let lang_items = lang_items.items().iter();
1764         self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1765             if let Some(def_id) = opt_def_id {
1766                 if def_id.is_local() {
1767                     return Some((def_id.index, i));
1768                 }
1769             }
1770             None
1771         }))
1772     }
1773
1774     fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1775         empty_proc_macro!(self);
1776         let tcx = self.tcx;
1777         self.lazy(&tcx.lang_items().missing)
1778     }
1779
1780     /// Encodes an index, mapping each trait to its (local) implementations.
1781     fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1782         empty_proc_macro!(self);
1783         debug!("EncodeContext::encode_impls()");
1784         let tcx = self.tcx;
1785         let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1786         tcx.hir().visit_all_item_likes(&mut visitor);
1787
1788         let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1789
1790         // Bring everything into deterministic order for hashing
1791         all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1792
1793         let all_impls: Vec<_> = all_impls
1794             .into_iter()
1795             .map(|(trait_def_id, mut impls)| {
1796                 // Bring everything into deterministic order for hashing
1797                 impls.sort_by_cached_key(|&(index, _)| {
1798                     tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1799                 });
1800
1801                 TraitImpls {
1802                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1803                     impls: self.lazy(&impls),
1804                 }
1805             })
1806             .collect();
1807
1808         self.lazy(&all_impls)
1809     }
1810
1811     // Encodes all symbols exported from this crate into the metadata.
1812     //
1813     // This pass is seeded off the reachability list calculated in the
1814     // middle::reachable module but filters out items that either don't have a
1815     // symbol associated with them (they weren't translated) or if they're an FFI
1816     // definition (as that's not defined in this crate).
1817     fn encode_exported_symbols(
1818         &mut self,
1819         exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1820     ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1821         empty_proc_macro!(self);
1822         // The metadata symbol name is special. It should not show up in
1823         // downstream crates.
1824         let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1825
1826         self.lazy(
1827             exported_symbols
1828                 .iter()
1829                 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1830                     ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1831                     _ => true,
1832                 })
1833                 .cloned(),
1834         )
1835     }
1836
1837     fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1838         empty_proc_macro!(self);
1839         let formats = self.tcx.dependency_formats(());
1840         for (ty, arr) in formats.iter() {
1841             if *ty != CrateType::Dylib {
1842                 continue;
1843             }
1844             return self.lazy(arr.iter().map(|slot| match *slot {
1845                 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1846
1847                 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1848                 Linkage::Static => Some(LinkagePreference::RequireStatic),
1849             }));
1850         }
1851         Lazy::empty()
1852     }
1853
1854     fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1855         let tcx = self.tcx;
1856
1857         debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1858
1859         match nitem.kind {
1860             hir::ForeignItemKind::Fn(_, ref names, _) => {
1861                 let data = FnData {
1862                     asyncness: hir::IsAsync::NotAsync,
1863                     constness: if self.tcx.is_const_fn_raw(def_id) {
1864                         hir::Constness::Const
1865                     } else {
1866                         hir::Constness::NotConst
1867                     },
1868                     param_names: self.encode_fn_param_names(names),
1869                 };
1870                 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn(self.lazy(data)));
1871             }
1872             hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => {
1873                 record!(self.tables.kind[def_id] <- EntryKind::ForeignMutStatic);
1874             }
1875             hir::ForeignItemKind::Static(_, hir::Mutability::Not) => {
1876                 record!(self.tables.kind[def_id] <- EntryKind::ForeignImmStatic);
1877             }
1878             hir::ForeignItemKind::Type => {
1879                 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
1880             }
1881         }
1882         self.encode_ident_span(def_id, nitem.ident);
1883         self.encode_item_type(def_id);
1884         if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1885             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1886         }
1887     }
1888 }
1889
1890 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1891 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1892     type Map = Map<'tcx>;
1893
1894     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1895         NestedVisitorMap::OnlyBodies(self.tcx.hir())
1896     }
1897     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1898         intravisit::walk_expr(self, ex);
1899         self.encode_info_for_expr(ex);
1900     }
1901     fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1902         intravisit::walk_anon_const(self, c);
1903         let def_id = self.tcx.hir().local_def_id(c.hir_id);
1904         self.encode_info_for_anon_const(def_id);
1905     }
1906     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1907         intravisit::walk_item(self, item);
1908         match item.kind {
1909             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1910             _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
1911         }
1912         self.encode_addl_info_for_item(item);
1913     }
1914     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1915         intravisit::walk_foreign_item(self, ni);
1916         self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
1917     }
1918     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1919         intravisit::walk_generics(self, generics);
1920         self.encode_info_for_generics(generics);
1921     }
1922 }
1923
1924 impl EncodeContext<'a, 'tcx> {
1925     fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1926         for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1927             for (field_index, _field) in variant.fields.iter().enumerate() {
1928                 self.encode_field(adt_def, variant_index, field_index);
1929             }
1930         }
1931     }
1932
1933     fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1934         for param in generics.params {
1935             let def_id = self.tcx.hir().local_def_id(param.hir_id);
1936             match param.kind {
1937                 GenericParamKind::Lifetime { .. } => continue,
1938                 GenericParamKind::Type { default, .. } => {
1939                     self.encode_info_for_generic_param(
1940                         def_id.to_def_id(),
1941                         EntryKind::TypeParam,
1942                         default.is_some(),
1943                     );
1944                 }
1945                 GenericParamKind::Const { ref default, .. } => {
1946                     let def_id = def_id.to_def_id();
1947                     self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1948                     if default.is_some() {
1949                         record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id))
1950                     }
1951                 }
1952             }
1953         }
1954     }
1955
1956     fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1957         if let hir::ExprKind::Closure(..) = expr.kind {
1958             let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1959             self.encode_info_for_closure(def_id);
1960         }
1961     }
1962
1963     fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1964         record!(self.tables.ident_span[def_id] <- ident.span);
1965     }
1966
1967     /// In some cases, along with the item itself, we also
1968     /// encode some sub-items. Usually we want some info from the item
1969     /// so it's easier to do that here then to wait until we would encounter
1970     /// normally in the visitor walk.
1971     fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1972         match item.kind {
1973             hir::ItemKind::Static(..)
1974             | hir::ItemKind::Const(..)
1975             | hir::ItemKind::Fn(..)
1976             | hir::ItemKind::Macro(..)
1977             | hir::ItemKind::Mod(..)
1978             | hir::ItemKind::ForeignMod { .. }
1979             | hir::ItemKind::GlobalAsm(..)
1980             | hir::ItemKind::ExternCrate(..)
1981             | hir::ItemKind::Use(..)
1982             | hir::ItemKind::TyAlias(..)
1983             | hir::ItemKind::OpaqueTy(..)
1984             | hir::ItemKind::TraitAlias(..) => {
1985                 // no sub-item recording needed in these cases
1986             }
1987             hir::ItemKind::Enum(..) => {
1988                 let def = self.tcx.adt_def(item.def_id.to_def_id());
1989                 self.encode_fields(def);
1990
1991                 for (i, variant) in def.variants.iter_enumerated() {
1992                     self.encode_enum_variant_info(def, i);
1993
1994                     if let Some(_ctor_def_id) = variant.ctor_def_id {
1995                         self.encode_enum_variant_ctor(def, i);
1996                     }
1997                 }
1998             }
1999             hir::ItemKind::Struct(ref struct_def, _) => {
2000                 let def = self.tcx.adt_def(item.def_id.to_def_id());
2001                 self.encode_fields(def);
2002
2003                 // If the struct has a constructor, encode it.
2004                 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
2005                     let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
2006                     self.encode_struct_ctor(def, ctor_def_id.to_def_id());
2007                 }
2008             }
2009             hir::ItemKind::Union(..) => {
2010                 let def = self.tcx.adt_def(item.def_id.to_def_id());
2011                 self.encode_fields(def);
2012             }
2013             hir::ItemKind::Impl { .. } => {
2014                 for &trait_item_def_id in
2015                     self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2016                 {
2017                     self.encode_info_for_impl_item(trait_item_def_id);
2018                 }
2019             }
2020             hir::ItemKind::Trait(..) => {
2021                 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2022                 {
2023                     self.encode_info_for_trait_item(item_def_id);
2024                 }
2025             }
2026         }
2027     }
2028 }
2029
2030 struct ImplVisitor<'tcx> {
2031     tcx: TyCtxt<'tcx>,
2032     impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
2033 }
2034
2035 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
2036     fn visit_item(&mut self, item: &hir::Item<'_>) {
2037         if let hir::ItemKind::Impl { .. } = item.kind {
2038             if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) {
2039                 let simplified_self_ty =
2040                     ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
2041
2042                 self.impls
2043                     .entry(trait_ref.def_id)
2044                     .or_default()
2045                     .push((item.def_id.local_def_index, simplified_self_ty));
2046             }
2047         }
2048     }
2049
2050     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
2051
2052     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
2053         // handled in `visit_item` above
2054     }
2055
2056     fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
2057 }
2058
2059 /// Used to prefetch queries which will be needed later by metadata encoding.
2060 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2061 fn prefetch_mir(tcx: TyCtxt<'_>) {
2062     if !tcx.sess.opts.output_types.should_codegen() {
2063         // We won't emit MIR, so don't prefetch it.
2064         return;
2065     }
2066
2067     par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2068         let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2069
2070         if encode_const {
2071             tcx.ensure().mir_for_ctfe(def_id);
2072         }
2073         if encode_opt {
2074             tcx.ensure().optimized_mir(def_id);
2075         }
2076         if encode_opt || encode_const {
2077             tcx.ensure().promoted_mir(def_id);
2078         }
2079     })
2080 }
2081
2082 // NOTE(eddyb) The following comment was preserved for posterity, even
2083 // though it's no longer relevant as EBML (which uses nested & tagged
2084 // "documents") was replaced with a scheme that can't go out of bounds.
2085 //
2086 // And here we run into yet another obscure archive bug: in which metadata
2087 // loaded from archives may have trailing garbage bytes. Awhile back one of
2088 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2089 // and opt) by having ebml generate an out-of-bounds panic when looking at
2090 // metadata.
2091 //
2092 // Upon investigation it turned out that the metadata file inside of an rlib
2093 // (and ar archive) was being corrupted. Some compilations would generate a
2094 // metadata file which would end in a few extra bytes, while other
2095 // compilations would not have these extra bytes appended to the end. These
2096 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2097 // being interpreted causing the out-of-bounds.
2098 //
2099 // The root cause of why these extra bytes were appearing was never
2100 // discovered, and in the meantime the solution we're employing is to insert
2101 // the length of the metadata to the start of the metadata. Later on this
2102 // will allow us to slice the metadata to the precise length that we just
2103 // generated regardless of trailing bytes that end up in it.
2104
2105 #[derive(Encodable, Decodable)]
2106 pub struct EncodedMetadata {
2107     raw_data: Vec<u8>,
2108 }
2109
2110 impl EncodedMetadata {
2111     #[inline]
2112     pub fn new() -> EncodedMetadata {
2113         EncodedMetadata { raw_data: Vec::new() }
2114     }
2115
2116     #[inline]
2117     pub fn raw_data(&self) -> &[u8] {
2118         &self.raw_data[..]
2119     }
2120 }
2121
2122 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2123     let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2124
2125     // Since encoding metadata is not in a query, and nothing is cached,
2126     // there's no need to do dep-graph tracking for any of it.
2127     tcx.dep_graph.assert_ignored();
2128
2129     join(
2130         || encode_metadata_impl(tcx),
2131         || {
2132             if tcx.sess.threads() == 1 {
2133                 return;
2134             }
2135             // Prefetch some queries used by metadata encoding.
2136             // This is not necessary for correctness, but is only done for performance reasons.
2137             // It can be removed if it turns out to cause trouble or be detrimental to performance.
2138             join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2139         },
2140     )
2141     .0
2142 }
2143
2144 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2145     let mut encoder = opaque::Encoder::new(vec![]);
2146     encoder.emit_raw_bytes(METADATA_HEADER).unwrap();
2147
2148     // Will be filled with the root position after encoding everything.
2149     encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap();
2150
2151     let source_map_files = tcx.sess.source_map().files();
2152     let source_file_cache = (source_map_files[0].clone(), 0);
2153     let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2154     drop(source_map_files);
2155
2156     let hygiene_ctxt = HygieneEncodeContext::default();
2157
2158     let mut ecx = EncodeContext {
2159         opaque: encoder,
2160         tcx,
2161         feat: tcx.features(),
2162         tables: Default::default(),
2163         lazy_state: LazyState::NoNode,
2164         type_shorthands: Default::default(),
2165         predicate_shorthands: Default::default(),
2166         source_file_cache,
2167         interpret_allocs: Default::default(),
2168         required_source_files,
2169         is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2170         hygiene_ctxt: &hygiene_ctxt,
2171     };
2172
2173     // Encode the rustc version string in a predictable location.
2174     rustc_version().encode(&mut ecx).unwrap();
2175
2176     // Encode all the entries and extra information in the crate,
2177     // culminating in the `CrateRoot` which points to all of it.
2178     let root = ecx.encode_crate_root();
2179
2180     let mut result = ecx.opaque.into_inner();
2181
2182     // Encode the root position.
2183     let header = METADATA_HEADER.len();
2184     let pos = root.position.get();
2185     result[header + 0] = (pos >> 24) as u8;
2186     result[header + 1] = (pos >> 16) as u8;
2187     result[header + 2] = (pos >> 8) as u8;
2188     result[header + 3] = (pos >> 0) as u8;
2189
2190     EncodedMetadata { raw_data: result }
2191 }