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