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