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