1 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
4 use log::{debug, trace};
7 use rustc_data_structures::fingerprint::Fingerprint;
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_data_structures::stable_hasher::StableHasher;
10 use rustc_data_structures::sync::{join, Lrc};
12 use rustc_hir::def::CtorKind;
13 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
14 use rustc_hir::definitions::DefPathTable;
15 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
16 use rustc_hir::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor};
17 use rustc_hir::lang_items;
18 use rustc_hir::{AnonConst, GenericParamKind};
19 use rustc_index::bit_set::GrowableBitSet;
20 use rustc_index::vec::Idx;
21 use rustc_middle::hir::map::Map;
22 use rustc_middle::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLib};
23 use rustc_middle::middle::dependency_format::Linkage;
24 use rustc_middle::middle::exported_symbols::{
25 metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
27 use rustc_middle::mir::{self, interpret};
28 use rustc_middle::traits::specialization_graph;
29 use rustc_middle::ty::codec::{self as ty_codec, TyEncoder};
30 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
31 use rustc_serialize::{opaque, Encodable, Encoder, SpecializedEncoder, UseSpecializedEncodable};
32 use rustc_session::config::CrateType;
33 use rustc_span::hygiene::{ExpnDataEncodeMode, HygieneEncodeContext};
34 use rustc_span::source_map::Spanned;
35 use rustc_span::symbol::{sym, Ident, Symbol};
36 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
37 use rustc_target::abi::VariantIdx;
39 use std::num::NonZeroUsize;
42 struct EncodeContext<'a, 'tcx> {
43 opaque: opaque::Encoder,
46 tables: TableBuilders<'tcx>,
48 lazy_state: LazyState,
49 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
50 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
52 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
53 interpret_allocs_inverse: Vec<interpret::AllocId>,
55 // This is used to speed up Span encoding.
56 // The `usize` is an index into the `MonotonicVec`
57 // that stores the `SourceFile`
58 source_file_cache: (Lrc<SourceFile>, usize),
59 // The indices (into the `SourceMap`'s `MonotonicVec`)
60 // of all of the `SourceFiles` that we need to serialize.
61 // When we serialize a `Span`, we insert the index of its
62 // `SourceFile` into the `GrowableBitSet`.
64 // This needs to be a `GrowableBitSet` and not a
65 // regular `BitSet` because we may actually import new `SourceFiles`
66 // during metadata encoding, due to executing a query
67 // with a result containing a foreign `Span`.
68 required_source_files: Option<GrowableBitSet<usize>>,
70 hygiene_ctxt: &'a HygieneEncodeContext,
73 macro_rules! encoder_methods {
74 ($($name:ident($ty:ty);)*) => {
75 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
76 self.opaque.$name(value)
81 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
82 type Error = <opaque::Encoder as Encoder>::Error;
85 fn emit_unit(&mut self) -> Result<(), Self::Error> {
112 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T, ()>> for EncodeContext<'a, 'tcx> {
113 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
114 self.emit_lazy_distance(*lazy)
118 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<[T], usize>> for EncodeContext<'a, 'tcx> {
119 fn specialized_encode(&mut self, lazy: &Lazy<[T]>) -> Result<(), Self::Error> {
120 self.emit_usize(lazy.meta)?;
124 self.emit_lazy_distance(*lazy)
128 impl<'a, 'tcx, I: Idx, T> SpecializedEncoder<Lazy<Table<I, T>, usize>> for EncodeContext<'a, 'tcx>
130 Option<T>: FixedSizeEncoding,
132 fn specialized_encode(&mut self, lazy: &Lazy<Table<I, T>>) -> Result<(), Self::Error> {
133 self.emit_usize(lazy.meta)?;
134 self.emit_lazy_distance(*lazy)
138 impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> {
140 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
141 self.emit_u32(cnum.as_u32())
145 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
147 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
148 let DefId { krate, index } = *def_id;
155 impl<'a, 'tcx> SpecializedEncoder<SyntaxContext> for EncodeContext<'a, 'tcx> {
156 fn specialized_encode(&mut self, ctxt: &SyntaxContext) -> Result<(), Self::Error> {
157 rustc_span::hygiene::raw_encode_syntax_context(*ctxt, &self.hygiene_ctxt, self)
161 impl<'a, 'tcx> SpecializedEncoder<ExpnId> for EncodeContext<'a, 'tcx> {
162 fn specialized_encode(&mut self, expn: &ExpnId) -> Result<(), Self::Error> {
163 rustc_span::hygiene::raw_encode_expn_id(
165 &mut self.hygiene_ctxt,
166 ExpnDataEncodeMode::Metadata,
172 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
174 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
175 self.emit_u32(def_index.as_u32())
179 impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> {
180 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
182 return TAG_INVALID_SPAN.encode(self);
185 let span = span.data();
187 // The Span infrastructure should make sure that this invariant holds:
188 debug_assert!(span.lo <= span.hi);
190 if !self.source_file_cache.0.contains(span.lo) {
191 let source_map = self.tcx.sess.source_map();
192 let source_file_index = source_map.lookup_source_file_idx(span.lo);
193 self.source_file_cache =
194 (source_map.files()[source_file_index].clone(), source_file_index);
197 if !self.source_file_cache.0.contains(span.hi) {
198 // Unfortunately, macro expansion still sometimes generates Spans
199 // that malformed in this way.
200 return TAG_INVALID_SPAN.encode(self);
203 let source_files = self.required_source_files.as_mut().expect("Already encoded SourceMap!");
204 // Record the fact that we need to encode the data for this `SourceFile`
205 source_files.insert(self.source_file_cache.1);
207 // There are two possible cases here:
208 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
209 // crate we are writing metadata for. When the metadata for *this* crate gets
210 // deserialized, the deserializer will need to know which crate it originally came
211 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
212 // be deserialized after the rest of the span data, which tells the deserializer
213 // which crate contains the source map information.
214 // 2. This span comes from our own crate. No special hamdling is needed - we just
215 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
216 // our own source map information.
218 // If we're a proc-macro crate, we always treat this as a local `Span`.
219 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
220 // if we're a proc-macro crate.
221 // This allows us to avoid loading the dependencies of proc-macro crates: all of
222 // the information we need to decode `Span`s is stored in the proc-macro crate.
223 let (tag, lo, hi) = if self.source_file_cache.0.is_imported() && !self.is_proc_macro {
224 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
225 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
226 // are relative to the source map information for the 'foreign' crate whose CrateNum
227 // we write into the metadata. This allows `imported_source_files` to binary
228 // search through the 'foreign' crate's source map information, using the
229 // deserialized 'lo' and 'hi' values directly.
231 // All of this logic ensures that the final result of deserialization is a 'normal'
232 // Span that can be used without any additional trouble.
233 let external_start_pos = {
234 // Introduce a new scope so that we drop the 'lock()' temporary
235 match &*self.source_file_cache.0.external_src.lock() {
236 ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
237 src => panic!("Unexpected external source {:?}", src),
240 let lo = (span.lo - self.source_file_cache.0.start_pos) + external_start_pos;
241 let hi = (span.hi - self.source_file_cache.0.start_pos) + external_start_pos;
243 (TAG_VALID_SPAN_FOREIGN, lo, hi)
245 (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
251 // Encode length which is usually less than span.hi and profits more
252 // from the variable-length integer encoding that we use.
256 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
257 // since we don't load proc-macro dependencies during serialization.
258 // This means that any hygiene information from macros used *within*
259 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
260 // definition) will be lost.
262 // This can show up in two ways:
264 // 1. Any hygiene information associated with identifier of
265 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
266 // Since proc-macros can only be invoked from a different crate,
267 // real code should never need to care about this.
269 // 2. Using `Span::def_site` or `Span::mixed_site` will not
270 // include any hygiene information associated with the definition
271 // site. This means that a proc-macro cannot emit a `$crate`
272 // identifier which resolves to one of its dependencies,
273 // which also should never come up in practice.
275 // Additionally, this affects `Span::parent`, and any other
276 // span inspection APIs that would otherwise allow traversing
277 // the `SyntaxContexts` associated with a span.
279 // None of these user-visible effects should result in any
280 // cross-crate inconsistencies (getting one behavior in the same
281 // crate, and a different behavior in another crate) due to the
282 // limited surface that proc-macros can expose.
284 // IMPORTANT: If this is ever changed, be sure to update
285 // `rustc_span::hygiene::raw_encode_expn_id` to handle
286 // encoding `ExpnData` for proc-macro crates.
287 if self.is_proc_macro {
288 SyntaxContext::root().encode(self)?;
290 span.ctxt.encode(self)?;
293 if tag == TAG_VALID_SPAN_FOREIGN {
294 // This needs to be two lines to avoid holding the `self.source_file_cache`
295 // while calling `cnum.encode(self)`
296 let cnum = self.source_file_cache.0.cnum;
304 impl<'a, 'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'a, 'tcx> {
306 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
307 self.specialized_encode(&def_id.to_def_id())
311 impl<'a, 'b, 'c, 'tcx> SpecializedEncoder<&'a ty::TyS<'b>> for EncodeContext<'c, 'tcx>
313 &'a ty::TyS<'b>: UseSpecializedEncodable,
315 fn specialized_encode(&mut self, ty: &&'a ty::TyS<'b>) -> Result<(), Self::Error> {
316 debug_assert!(self.tcx.lift(ty).is_some());
317 let ty = unsafe { std::mem::transmute::<&&'a ty::TyS<'b>, &&'tcx ty::TyS<'tcx>>(ty) };
318 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
322 impl<'a, 'b, 'tcx> SpecializedEncoder<ty::Predicate<'b>> for EncodeContext<'a, 'tcx> {
323 fn specialized_encode(&mut self, predicate: &ty::Predicate<'b>) -> Result<(), Self::Error> {
324 debug_assert!(self.tcx.lift(predicate).is_some());
326 unsafe { std::mem::transmute::<&ty::Predicate<'b>, &ty::Predicate<'tcx>>(predicate) };
327 ty_codec::encode_with_shorthand(self, predicate, |encoder| {
328 &mut encoder.predicate_shorthands
333 impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> {
334 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
335 use std::collections::hash_map::Entry;
336 let index = match self.interpret_allocs.entry(*alloc_id) {
337 Entry::Occupied(e) => *e.get(),
338 Entry::Vacant(e) => {
339 let idx = self.interpret_allocs_inverse.len();
340 self.interpret_allocs_inverse.push(*alloc_id);
350 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
351 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
352 f.encode_opaque(&mut self.opaque)
356 impl<'a, 'tcx, T> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'a, 'tcx>
358 mir::ClearCrossCrate<T>: UseSpecializedEncodable,
360 fn specialized_encode(&mut self, _: &mir::ClearCrossCrate<T>) -> Result<(), Self::Error> {
365 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
366 fn position(&self) -> usize {
367 self.opaque.position()
371 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
372 trait EncodeContentsForLazy<T: ?Sized + LazyMeta> {
373 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
376 impl<T: Encodable> EncodeContentsForLazy<T> for &T {
377 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
378 self.encode(ecx).unwrap()
382 impl<T: Encodable> EncodeContentsForLazy<T> for T {
383 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
384 self.encode(ecx).unwrap()
388 impl<I, T: Encodable> EncodeContentsForLazy<[T]> for I
391 I::Item: EncodeContentsForLazy<T>,
393 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
394 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
398 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
399 // normally need extra variables to avoid errors about multiple mutable borrows.
400 macro_rules! record {
401 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
404 let lazy = $self.lazy(value);
405 $self.$tables.$table.set($def_id.index, lazy);
410 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
411 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
414 ) -> Result<(), <Self as Encoder>::Error> {
415 let min_end = lazy.position.get() + T::min_size(lazy.meta);
416 let distance = match self.lazy_state {
417 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
418 LazyState::NodeStart(start) => {
419 let start = start.get();
420 assert!(min_end <= start);
423 LazyState::Previous(last_min_end) => {
425 last_min_end <= lazy.position,
426 "make sure that the calls to `lazy*` \
427 are in the same order as the metadata fields",
429 lazy.position.get() - last_min_end.get()
432 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
433 self.emit_usize(distance)
436 fn lazy<T: ?Sized + LazyMeta>(&mut self, value: impl EncodeContentsForLazy<T>) -> Lazy<T> {
437 let pos = NonZeroUsize::new(self.position()).unwrap();
439 assert_eq!(self.lazy_state, LazyState::NoNode);
440 self.lazy_state = LazyState::NodeStart(pos);
441 let meta = value.encode_contents_for_lazy(self);
442 self.lazy_state = LazyState::NoNode;
444 assert!(pos.get() + <T>::min_size(meta) <= self.position());
446 Lazy::from_position_and_meta(pos, meta)
449 fn encode_info_for_items(&mut self) {
450 let krate = self.tcx.hir().krate();
451 let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public };
452 self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.item.module, &krate.item.attrs, &vis);
453 krate.visit_all_item_likes(&mut self.as_deep_visitor());
454 for macro_def in krate.exported_macros {
455 self.visit_macro_def(macro_def);
459 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
460 let definitions = self.tcx.hir().definitions();
461 self.lazy(definitions.def_path_table())
464 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
465 let source_map = self.tcx.sess.source_map();
466 let all_source_files = source_map.files();
468 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
469 // By replacing the `Option` with `None`, we ensure that we can't
470 // accidentally serialize any more `Span`s after the source map encoding
472 let required_source_files = self.required_source_files.take().unwrap();
474 let adapted = all_source_files
477 .filter(|(idx, source_file)| {
478 // Only serialize `SourceFile`s that were used
479 // during the encoding of a `Span`
480 required_source_files.contains(*idx) &&
481 // Don't serialize imported `SourceFile`s, unless
482 // we're in a proc-macro crate.
483 (!source_file.is_imported() || self.is_proc_macro)
485 .map(|(_, source_file)| {
486 let mut adapted = match source_file.name {
487 // This path of this SourceFile has been modified by
488 // path-remapping, so we use it verbatim (and avoid
489 // cloning the whole map in the process).
490 _ if source_file.name_was_remapped => source_file.clone(),
492 // Otherwise expand all paths to absolute paths because
493 // any relative paths are potentially relative to a
495 FileName::Real(ref name) => {
496 let name = name.stable_name();
497 let mut adapted = (**source_file).clone();
498 adapted.name = Path::new(&working_dir).join(name).into();
499 adapted.name_hash = {
500 let mut hasher: StableHasher = StableHasher::new();
501 adapted.name.hash(&mut hasher);
502 hasher.finish::<u128>()
507 // expanded code, not from a file
508 _ => source_file.clone(),
511 // We're serializing this `SourceFile` into our crate metadata,
512 // so mark it as coming from this crate.
513 // This also ensures that we don't try to deserialize the
514 // `CrateNum` for a proc-macro dependency - since proc macro
515 // dependencies aren't loaded when we deserialize a proc-macro,
516 // trying to remap the `CrateNum` would fail.
517 if self.is_proc_macro {
518 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
522 .collect::<Vec<_>>();
524 self.lazy(adapted.iter().map(|rc| &**rc))
527 fn is_proc_macro(&self) -> bool {
528 self.tcx.sess.crate_types().contains(&CrateType::ProcMacro)
531 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
532 let is_proc_macro = self.is_proc_macro();
534 let mut i = self.position();
536 // Encode the crate deps
537 let crate_deps = self.encode_crate_deps();
538 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
539 let dep_bytes = self.position() - i;
541 // Encode the lib features.
543 let lib_features = self.encode_lib_features();
544 let lib_feature_bytes = self.position() - i;
546 // Encode the language items.
548 let lang_items = self.encode_lang_items();
549 let lang_items_missing = self.encode_lang_items_missing();
550 let lang_item_bytes = self.position() - i;
552 // Encode the diagnostic items.
554 let diagnostic_items = self.encode_diagnostic_items();
555 let diagnostic_item_bytes = self.position() - i;
557 // Encode the native libraries used
559 let native_libraries = self.encode_native_libraries();
560 let native_lib_bytes = self.position() - i;
562 let foreign_modules = self.encode_foreign_modules();
564 // Encode DefPathTable
566 let def_path_table = self.encode_def_path_table();
567 let def_path_table_bytes = self.position() - i;
569 // Encode the def IDs of impls, for coherence checking.
571 let impls = self.encode_impls();
572 let impl_bytes = self.position() - i;
578 self.encode_info_for_items();
579 let item_bytes = self.position() - i;
581 // Encode the allocation index
582 let interpret_alloc_index = {
583 let mut interpret_alloc_index = Vec::new();
585 trace!("beginning to encode alloc ids");
587 let new_n = self.interpret_allocs_inverse.len();
588 // if we have found new ids, serialize those, too
593 trace!("encoding {} further alloc ids", new_n - n);
594 for idx in n..new_n {
595 let id = self.interpret_allocs_inverse[idx];
596 let pos = self.position() as u32;
597 interpret_alloc_index.push(pos);
598 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
602 self.lazy(interpret_alloc_index)
606 let tables = self.tables.encode(&mut self.opaque);
607 let tables_bytes = self.position() - i;
609 // Encode the proc macro data
611 let proc_macro_data = self.encode_proc_macros();
612 let proc_macro_data_bytes = self.position() - i;
614 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
615 // this as late as possible to give the prefetching as much time as possible to complete.
617 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
618 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
619 let exported_symbols_bytes = self.position() - i;
621 // Encode the hygiene data,
622 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
623 // of encoding other items (e.g. `optimized_mir`) may cause us to load
624 // data from the incremental cache. If this causes us to deserialize a `Span`,
625 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
626 // Therefore, we need to encode the hygiene data last to ensure that we encode
627 // any `SyntaxContext`s that might be used.
629 let (syntax_contexts, expn_data) = self.encode_hygiene();
630 let hygiene_bytes = self.position() - i;
632 // Encode source_map. This needs to be done last,
633 // since encoding `Span`s tells us which `SourceFiles` we actually
636 let source_map = self.encode_source_map();
637 let source_map_bytes = self.position() - i;
639 let attrs = tcx.hir().krate_attrs();
640 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
642 let root = self.lazy(CrateRoot {
643 name: tcx.crate_name(LOCAL_CRATE),
644 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
645 triple: tcx.sess.opts.target_triple.clone(),
646 hash: tcx.crate_hash(LOCAL_CRATE),
647 disambiguator: tcx.sess.local_crate_disambiguator(),
648 panic_strategy: tcx.sess.panic_strategy(),
649 edition: tcx.sess.edition(),
650 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
651 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
652 has_default_lib_allocator,
653 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
654 proc_macro_decls_static: if is_proc_macro {
655 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
661 proc_macro_stability: if is_proc_macro {
662 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied()
666 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
667 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
668 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
669 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
670 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
671 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
672 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
675 dylib_dependency_formats,
686 interpret_alloc_index,
692 let total_bytes = self.position();
694 if tcx.sess.meta_stats() {
695 let mut zero_bytes = 0;
696 for e in self.opaque.data.iter() {
702 println!("metadata stats:");
703 println!(" dep bytes: {}", dep_bytes);
704 println!(" lib feature bytes: {}", lib_feature_bytes);
705 println!(" lang item bytes: {}", lang_item_bytes);
706 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
707 println!(" native bytes: {}", native_lib_bytes);
708 println!(" source_map bytes: {}", source_map_bytes);
709 println!(" impl bytes: {}", impl_bytes);
710 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
711 println!(" def-path table bytes: {}", def_path_table_bytes);
712 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
713 println!(" item bytes: {}", item_bytes);
714 println!(" table bytes: {}", tables_bytes);
715 println!(" hygiene bytes: {}", hygiene_bytes);
716 println!(" zero bytes: {}", zero_bytes);
717 println!(" total bytes: {}", total_bytes);
724 impl EncodeContext<'a, 'tcx> {
725 fn encode_variances_of(&mut self, def_id: DefId) {
726 debug!("EncodeContext::encode_variances_of({:?})", def_id);
727 record!(self.tables.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
730 fn encode_item_type(&mut self, def_id: DefId) {
731 debug!("EncodeContext::encode_item_type({:?})", def_id);
732 record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
735 fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
737 let variant = &def.variants[index];
738 let def_id = variant.def_id;
739 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
741 let data = VariantData {
742 ctor_kind: variant.ctor_kind,
743 discr: variant.discr,
744 ctor: variant.ctor_def_id.map(|did| did.index),
745 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
748 let enum_id = tcx.hir().as_local_hir_id(def.did.expect_local());
749 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
751 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
752 record!(self.tables.visibility[def_id] <-
753 ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
754 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
755 record!(self.tables.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
756 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
757 assert!(f.did.is_local());
760 self.encode_ident_span(def_id, variant.ident);
761 self.encode_stability(def_id);
762 self.encode_deprecation(def_id);
763 self.encode_item_type(def_id);
764 if variant.ctor_kind == CtorKind::Fn {
765 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
766 if let Some(ctor_def_id) = variant.ctor_def_id {
767 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
769 // FIXME(eddyb) is this ever used?
770 self.encode_variances_of(def_id);
772 self.encode_generics(def_id);
773 self.encode_explicit_predicates(def_id);
774 self.encode_inferred_outlives(def_id);
775 self.encode_optimized_mir(def_id.expect_local());
776 self.encode_promoted_mir(def_id.expect_local());
779 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
781 let variant = &def.variants[index];
782 let def_id = variant.ctor_def_id.unwrap();
783 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
785 // FIXME(eddyb) encode only the `CtorKind` for constructors.
786 let data = VariantData {
787 ctor_kind: variant.ctor_kind,
788 discr: variant.discr,
789 ctor: Some(def_id.index),
790 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
793 // Variant constructors have the same visibility as the parent enums, unless marked as
794 // non-exhaustive, in which case they are lowered to `pub(crate)`.
795 let enum_id = tcx.hir().as_local_hir_id(def.did.expect_local());
796 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
797 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
798 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
799 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
802 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
803 record!(self.tables.visibility[def_id] <- ctor_vis);
804 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
805 self.encode_stability(def_id);
806 self.encode_deprecation(def_id);
807 self.encode_item_type(def_id);
808 if variant.ctor_kind == CtorKind::Fn {
809 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
810 self.encode_variances_of(def_id);
812 self.encode_generics(def_id);
813 self.encode_explicit_predicates(def_id);
814 self.encode_inferred_outlives(def_id);
815 self.encode_optimized_mir(def_id.expect_local());
816 self.encode_promoted_mir(def_id.expect_local());
819 fn encode_info_for_mod(
823 attrs: &[ast::Attribute],
824 vis: &hir::Visibility<'_>,
827 let local_def_id = tcx.hir().local_def_id(id);
828 let def_id = local_def_id.to_def_id();
829 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
832 reexports: match tcx.module_exports(local_def_id) {
834 let hir_map = self.tcx.hir();
838 .map(|export| export.map_id(|id| hir_map.as_local_hir_id(id))),
843 expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
846 record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
847 record!(self.tables.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
848 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
849 record!(self.tables.attributes[def_id] <- attrs);
850 record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
851 tcx.hir().local_def_id(item_id.id).local_def_index
853 self.encode_stability(def_id);
854 self.encode_deprecation(def_id);
859 adt_def: &ty::AdtDef,
860 variant_index: VariantIdx,
864 let variant = &adt_def.variants[variant_index];
865 let field = &variant.fields[field_index];
867 let def_id = field.did;
868 debug!("EncodeContext::encode_field({:?})", def_id);
870 let variant_id = tcx.hir().as_local_hir_id(variant.def_id.expect_local());
871 let variant_data = tcx.hir().expect_variant_data(variant_id);
873 record!(self.tables.kind[def_id] <- EntryKind::Field);
874 record!(self.tables.visibility[def_id] <- field.vis);
875 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
876 record!(self.tables.attributes[def_id] <- variant_data.fields()[field_index].attrs);
877 self.encode_ident_span(def_id, field.ident);
878 self.encode_stability(def_id);
879 self.encode_deprecation(def_id);
880 self.encode_item_type(def_id);
881 self.encode_generics(def_id);
882 self.encode_explicit_predicates(def_id);
883 self.encode_inferred_outlives(def_id);
886 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
887 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
889 let variant = adt_def.non_enum_variant();
891 let data = VariantData {
892 ctor_kind: variant.ctor_kind,
893 discr: variant.discr,
894 ctor: Some(def_id.index),
895 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
898 let struct_id = tcx.hir().as_local_hir_id(adt_def.did.expect_local());
899 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
900 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
901 for field in &variant.fields {
902 if ctor_vis.is_at_least(field.vis, tcx) {
903 ctor_vis = field.vis;
907 // If the structure is marked as non_exhaustive then lower the visibility
908 // to within the crate.
909 if adt_def.non_enum_variant().is_field_list_non_exhaustive()
910 && ctor_vis == ty::Visibility::Public
912 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
915 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
916 record!(self.tables.visibility[def_id] <- ctor_vis);
917 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
918 self.encode_stability(def_id);
919 self.encode_deprecation(def_id);
920 self.encode_item_type(def_id);
921 if variant.ctor_kind == CtorKind::Fn {
922 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
923 self.encode_variances_of(def_id);
925 self.encode_generics(def_id);
926 self.encode_explicit_predicates(def_id);
927 self.encode_inferred_outlives(def_id);
928 self.encode_optimized_mir(def_id.expect_local());
929 self.encode_promoted_mir(def_id.expect_local());
932 fn encode_generics(&mut self, def_id: DefId) {
933 debug!("EncodeContext::encode_generics({:?})", def_id);
934 record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
937 fn encode_explicit_predicates(&mut self, def_id: DefId) {
938 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
939 record!(self.tables.explicit_predicates[def_id] <-
940 self.tcx.explicit_predicates_of(def_id));
943 fn encode_inferred_outlives(&mut self, def_id: DefId) {
944 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
945 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
946 if !inferred_outlives.is_empty() {
947 record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
951 fn encode_super_predicates(&mut self, def_id: DefId) {
952 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
953 record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
956 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
957 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
960 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
961 let ast_item = tcx.hir().expect_trait_item(hir_id);
962 let trait_item = tcx.associated_item(def_id);
964 let container = match trait_item.defaultness {
965 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
966 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
967 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
970 record!(self.tables.kind[def_id] <- match trait_item.kind {
971 ty::AssocKind::Const => {
972 let rendered = rustc_hir_pretty::to_string(
973 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
974 |s| s.print_trait_item(ast_item)
976 let rendered_const = self.lazy(RenderedConst(rendered));
978 EntryKind::AssocConst(
984 ty::AssocKind::Fn => {
985 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
986 let param_names = match *m {
987 hir::TraitFn::Required(ref names) => {
988 self.encode_fn_param_names(names)
990 hir::TraitFn::Provided(body) => {
991 self.encode_fn_param_names_for_body(body)
995 asyncness: m_sig.header.asyncness,
996 constness: hir::Constness::NotConst,
1002 EntryKind::AssocFn(self.lazy(AssocFnData {
1005 has_self: trait_item.fn_has_self_parameter,
1008 ty::AssocKind::Type => EntryKind::AssocType(container),
1010 record!(self.tables.visibility[def_id] <- trait_item.vis);
1011 record!(self.tables.span[def_id] <- ast_item.span);
1012 record!(self.tables.attributes[def_id] <- ast_item.attrs);
1013 self.encode_ident_span(def_id, ast_item.ident);
1014 self.encode_stability(def_id);
1015 self.encode_const_stability(def_id);
1016 self.encode_deprecation(def_id);
1017 match trait_item.kind {
1018 ty::AssocKind::Const | ty::AssocKind::Fn => {
1019 self.encode_item_type(def_id);
1021 ty::AssocKind::Type => {
1022 if trait_item.defaultness.has_value() {
1023 self.encode_item_type(def_id);
1027 if trait_item.kind == ty::AssocKind::Fn {
1028 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1029 self.encode_variances_of(def_id);
1031 self.encode_generics(def_id);
1032 self.encode_explicit_predicates(def_id);
1033 self.encode_inferred_outlives(def_id);
1035 // This should be kept in sync with `PrefetchVisitor.visit_trait_item`.
1036 self.encode_optimized_mir(def_id.expect_local());
1037 self.encode_promoted_mir(def_id.expect_local());
1040 fn metadata_output_only(&self) -> bool {
1041 // MIR optimisation can be skipped when we're just interested in the metadata.
1042 !self.tcx.sess.opts.output_types.should_codegen()
1045 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1046 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1049 let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local());
1050 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1051 let impl_item = self.tcx.associated_item(def_id);
1053 let container = match impl_item.defaultness {
1054 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1055 hir::Defaultness::Final => AssocContainer::ImplFinal,
1056 hir::Defaultness::Default { has_value: false } => {
1057 span_bug!(ast_item.span, "impl items always have values (currently)")
1061 record!(self.tables.kind[def_id] <- match impl_item.kind {
1062 ty::AssocKind::Const => {
1063 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1064 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1066 EntryKind::AssocConst(
1069 self.encode_rendered_const_for_body(body_id))
1074 ty::AssocKind::Fn => {
1075 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1077 asyncness: sig.header.asyncness,
1078 constness: sig.header.constness,
1079 param_names: self.encode_fn_param_names_for_body(body),
1084 EntryKind::AssocFn(self.lazy(AssocFnData {
1087 has_self: impl_item.fn_has_self_parameter,
1090 ty::AssocKind::Type => EntryKind::AssocType(container)
1092 record!(self.tables.visibility[def_id] <- impl_item.vis);
1093 record!(self.tables.span[def_id] <- ast_item.span);
1094 record!(self.tables.attributes[def_id] <- ast_item.attrs);
1095 self.encode_ident_span(def_id, impl_item.ident);
1096 self.encode_stability(def_id);
1097 self.encode_const_stability(def_id);
1098 self.encode_deprecation(def_id);
1099 self.encode_item_type(def_id);
1100 if impl_item.kind == ty::AssocKind::Fn {
1101 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1102 self.encode_variances_of(def_id);
1104 self.encode_generics(def_id);
1105 self.encode_explicit_predicates(def_id);
1106 self.encode_inferred_outlives(def_id);
1108 // The following part should be kept in sync with `PrefetchVisitor.visit_impl_item`.
1110 let mir = match ast_item.kind {
1111 hir::ImplItemKind::Const(..) => true,
1112 hir::ImplItemKind::Fn(ref sig, _) => {
1113 let generics = self.tcx.generics_of(def_id);
1114 let needs_inline = (generics.requires_monomorphization(self.tcx)
1115 || tcx.codegen_fn_attrs(def_id).requests_inline())
1116 && !self.metadata_output_only();
1117 let is_const_fn = sig.header.constness == hir::Constness::Const;
1118 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1119 needs_inline || is_const_fn || always_encode_mir
1121 hir::ImplItemKind::TyAlias(..) => false,
1124 self.encode_optimized_mir(def_id.expect_local());
1125 self.encode_promoted_mir(def_id.expect_local());
1129 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1130 self.tcx.dep_graph.with_ignore(|| self.lazy(self.tcx.hir().body_param_names(body_id)))
1133 fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1134 self.lazy(param_names.iter())
1137 fn encode_optimized_mir(&mut self, def_id: LocalDefId) {
1138 debug!("EntryBuilder::encode_mir({:?})", def_id);
1139 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1140 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1141 record!(self.tables.unused_generic_params[def_id.to_def_id()] <-
1142 self.tcx.unused_generic_params(def_id));
1146 fn encode_promoted_mir(&mut self, def_id: LocalDefId) {
1147 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1148 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1149 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1153 // Encodes the inherent implementations of a structure, enumeration, or trait.
1154 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1155 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1156 let implementations = self.tcx.inherent_impls(def_id);
1157 if !implementations.is_empty() {
1158 record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1159 assert!(def_id.is_local());
1165 fn encode_stability(&mut self, def_id: DefId) {
1166 debug!("EncodeContext::encode_stability({:?})", def_id);
1167 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1168 record!(self.tables.stability[def_id] <- stab)
1172 fn encode_const_stability(&mut self, def_id: DefId) {
1173 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1174 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1175 record!(self.tables.const_stability[def_id] <- stab)
1179 fn encode_deprecation(&mut self, def_id: DefId) {
1180 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1181 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1182 record!(self.tables.deprecation[def_id] <- depr);
1186 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1187 let hir = self.tcx.hir();
1188 let body = hir.body(body_id);
1189 let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1190 s.print_expr(&body.value)
1192 let rendered_const = &RenderedConst(rendered);
1193 self.lazy(rendered_const)
1196 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1199 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1201 self.encode_ident_span(def_id, item.ident);
1203 record!(self.tables.kind[def_id] <- match item.kind {
1204 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1205 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1206 hir::ItemKind::Const(_, body_id) => {
1207 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1210 self.encode_rendered_const_for_body(body_id)
1213 hir::ItemKind::Fn(ref sig, .., body) => {
1215 asyncness: sig.header.asyncness,
1216 constness: sig.header.constness,
1217 param_names: self.encode_fn_param_names_for_body(body),
1220 EntryKind::Fn(self.lazy(data))
1222 hir::ItemKind::Mod(ref m) => {
1223 return self.encode_info_for_mod(item.hir_id, m, &item.attrs, &item.vis);
1225 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1226 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1227 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1228 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1229 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1230 hir::ItemKind::Struct(ref struct_def, _) => {
1231 let adt_def = self.tcx.adt_def(def_id);
1232 let variant = adt_def.non_enum_variant();
1234 // Encode def_ids for each field and method
1235 // for methods, write all the stuff get_trait_method
1237 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1238 self.tcx.hir().local_def_id(ctor_hir_id).local_def_index
1241 EntryKind::Struct(self.lazy(VariantData {
1242 ctor_kind: variant.ctor_kind,
1243 discr: variant.discr,
1245 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1248 hir::ItemKind::Union(..) => {
1249 let adt_def = self.tcx.adt_def(def_id);
1250 let variant = adt_def.non_enum_variant();
1252 EntryKind::Union(self.lazy(VariantData {
1253 ctor_kind: variant.ctor_kind,
1254 discr: variant.discr,
1256 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1259 hir::ItemKind::Impl { defaultness, .. } => {
1260 let trait_ref = self.tcx.impl_trait_ref(def_id);
1261 let polarity = self.tcx.impl_polarity(def_id);
1262 let parent = if let Some(trait_ref) = trait_ref {
1263 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1264 trait_def.ancestors(self.tcx, def_id).ok()
1265 .and_then(|mut an| an.nth(1).and_then(|node| {
1267 specialization_graph::Node::Impl(parent) => Some(parent),
1275 // if this is an impl of `CoerceUnsized`, create its
1276 // "unsized info", else just store None
1277 let coerce_unsized_info =
1278 trait_ref.and_then(|t| {
1279 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1280 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1286 let data = ImplData {
1289 parent_impl: parent,
1290 coerce_unsized_info,
1293 EntryKind::Impl(self.lazy(data))
1295 hir::ItemKind::Trait(..) => {
1296 let trait_def = self.tcx.trait_def(def_id);
1297 let data = TraitData {
1298 unsafety: trait_def.unsafety,
1299 paren_sugar: trait_def.paren_sugar,
1300 has_auto_impl: self.tcx.trait_is_auto(def_id),
1301 is_marker: trait_def.is_marker,
1302 specialization_kind: trait_def.specialization_kind,
1305 EntryKind::Trait(self.lazy(data))
1307 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1308 hir::ItemKind::ExternCrate(_) |
1309 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1311 record!(self.tables.visibility[def_id] <-
1312 ty::Visibility::from_hir(&item.vis, item.hir_id, tcx));
1313 record!(self.tables.span[def_id] <- item.span);
1314 record!(self.tables.attributes[def_id] <- item.attrs);
1315 // FIXME(eddyb) there should be a nicer way to do this.
1317 hir::ItemKind::ForeignMod(ref fm) => record!(self.tables.children[def_id] <-
1320 .map(|foreign_item| tcx.hir().local_def_id(
1321 foreign_item.hir_id).local_def_index)
1323 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1324 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1325 assert!(v.def_id.is_local());
1329 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1330 record!(self.tables.children[def_id] <-
1331 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1332 assert!(f.did.is_local());
1337 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1338 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1339 record!(self.tables.children[def_id] <-
1340 associated_item_def_ids.iter().map(|&def_id| {
1341 assert!(def_id.is_local());
1348 self.encode_stability(def_id);
1349 self.encode_const_stability(def_id);
1350 self.encode_deprecation(def_id);
1352 hir::ItemKind::Static(..)
1353 | hir::ItemKind::Const(..)
1354 | hir::ItemKind::Fn(..)
1355 | hir::ItemKind::TyAlias(..)
1356 | hir::ItemKind::OpaqueTy(..)
1357 | hir::ItemKind::Enum(..)
1358 | hir::ItemKind::Struct(..)
1359 | hir::ItemKind::Union(..)
1360 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1363 if let hir::ItemKind::Fn(..) = item.kind {
1364 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1366 if let hir::ItemKind::Impl { .. } = item.kind {
1367 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1368 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1371 self.encode_inherent_implementations(def_id);
1373 hir::ItemKind::Enum(..)
1374 | hir::ItemKind::Struct(..)
1375 | hir::ItemKind::Union(..)
1376 | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1380 hir::ItemKind::Static(..)
1381 | hir::ItemKind::Const(..)
1382 | hir::ItemKind::Fn(..)
1383 | hir::ItemKind::TyAlias(..)
1384 | hir::ItemKind::Enum(..)
1385 | hir::ItemKind::Struct(..)
1386 | hir::ItemKind::Union(..)
1387 | hir::ItemKind::Impl { .. }
1388 | hir::ItemKind::OpaqueTy(..)
1389 | hir::ItemKind::Trait(..)
1390 | hir::ItemKind::TraitAlias(..) => {
1391 self.encode_generics(def_id);
1392 self.encode_explicit_predicates(def_id);
1393 self.encode_inferred_outlives(def_id);
1398 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1399 self.encode_super_predicates(def_id);
1404 // The following part should be kept in sync with `PrefetchVisitor.visit_item`.
1406 let mir = match item.kind {
1407 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1408 hir::ItemKind::Fn(ref sig, ..) => {
1409 let generics = tcx.generics_of(def_id);
1410 let needs_inline = (generics.requires_monomorphization(tcx)
1411 || tcx.codegen_fn_attrs(def_id).requests_inline())
1412 && !self.metadata_output_only();
1413 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1414 needs_inline || sig.header.constness == hir::Constness::Const || always_encode_mir
1419 self.encode_optimized_mir(def_id.expect_local());
1420 self.encode_promoted_mir(def_id.expect_local());
1424 /// Serialize the text of exported macros
1425 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1426 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id();
1427 record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1428 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1429 record!(self.tables.span[def_id] <- macro_def.span);
1430 record!(self.tables.attributes[def_id] <- macro_def.attrs);
1431 self.encode_ident_span(def_id, macro_def.ident);
1432 self.encode_stability(def_id);
1433 self.encode_deprecation(def_id);
1436 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1437 record!(self.tables.kind[def_id] <- kind);
1438 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1439 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1441 self.encode_item_type(def_id);
1445 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1446 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1448 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1449 // including on the signature, which is inferred in `typeck.
1450 let hir_id = self.tcx.hir().as_local_hir_id(def_id);
1451 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1453 record!(self.tables.kind[def_id.to_def_id()] <- match ty.kind {
1454 ty::Generator(..) => {
1455 let data = self.tcx.generator_kind(def_id).unwrap();
1456 EntryKind::Generator(data)
1459 ty::Closure(..) => EntryKind::Closure,
1461 _ => bug!("closure that is neither generator nor closure"),
1463 record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public);
1464 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1465 record!(self.tables.attributes[def_id.to_def_id()] <- &self.tcx.get_attrs(def_id.to_def_id())[..]);
1466 self.encode_item_type(def_id.to_def_id());
1467 if let ty::Closure(def_id, substs) = ty.kind {
1468 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1470 self.encode_generics(def_id.to_def_id());
1471 self.encode_optimized_mir(def_id);
1472 self.encode_promoted_mir(def_id);
1475 fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1476 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1477 let id = self.tcx.hir().as_local_hir_id(def_id);
1478 let body_id = self.tcx.hir().body_owned_by(id);
1479 let const_data = self.encode_rendered_const_for_body(body_id);
1480 let qualifs = self.tcx.mir_const_qualif(def_id);
1482 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1483 record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public);
1484 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1485 self.encode_item_type(def_id.to_def_id());
1486 self.encode_generics(def_id.to_def_id());
1487 self.encode_explicit_predicates(def_id.to_def_id());
1488 self.encode_inferred_outlives(def_id.to_def_id());
1489 self.encode_optimized_mir(def_id);
1490 self.encode_promoted_mir(def_id);
1493 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1494 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1495 self.lazy(used_libraries.iter().cloned())
1498 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1499 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1500 self.lazy(foreign_modules.iter().cloned())
1503 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) {
1504 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1505 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1507 let _: Result<(), !> = self.hygiene_ctxt.encode(
1508 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table),
1509 |(this, syntax_contexts, _), index, ctxt_data| {
1510 syntax_contexts.set(index, this.lazy(ctxt_data));
1513 |(this, _, expn_data_table), index, expn_data| {
1514 expn_data_table.set(index, this.lazy(expn_data));
1519 (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque))
1522 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1523 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1526 Some(self.lazy(tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index)))
1532 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1533 let crates = self.tcx.crates();
1535 let mut deps = crates
1538 let dep = CrateDep {
1539 name: self.tcx.original_crate_name(cnum),
1540 hash: self.tcx.crate_hash(cnum),
1541 host_hash: self.tcx.crate_host_hash(cnum),
1542 kind: self.tcx.dep_kind(cnum),
1543 extra_filename: self.tcx.extra_filename(cnum),
1547 .collect::<Vec<_>>();
1549 deps.sort_by_key(|&(cnum, _)| cnum);
1552 // Sanity-check the crate numbers
1553 let mut expected_cnum = 1;
1554 for &(n, _) in &deps {
1555 assert_eq!(n, CrateNum::new(expected_cnum));
1560 // We're just going to write a list of crate 'name-hash-version's, with
1561 // the assumption that they are numbered 1 to n.
1562 // FIXME (#2166): This is not nearly enough to support correct versioning
1563 // but is enough to get transitive crate dependencies working.
1564 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1567 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1569 let lib_features = tcx.lib_features();
1570 self.lazy(lib_features.to_vec())
1573 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1575 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1576 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1579 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1581 let lang_items = tcx.lang_items();
1582 let lang_items = lang_items.items().iter();
1583 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1584 if let Some(def_id) = opt_def_id {
1585 if def_id.is_local() {
1586 return Some((def_id.index, i));
1593 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1595 self.lazy(&tcx.lang_items().missing)
1598 /// Encodes an index, mapping each trait to its (local) implementations.
1599 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1600 debug!("EncodeContext::encode_impls()");
1602 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1603 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1605 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1607 // Bring everything into deterministic order for hashing
1608 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1610 let all_impls: Vec<_> = all_impls
1612 .map(|(trait_def_id, mut impls)| {
1613 // Bring everything into deterministic order for hashing
1614 impls.sort_by_cached_key(|&index| {
1615 tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1619 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1620 impls: self.lazy(&impls),
1625 self.lazy(&all_impls)
1628 // Encodes all symbols exported from this crate into the metadata.
1630 // This pass is seeded off the reachability list calculated in the
1631 // middle::reachable module but filters out items that either don't have a
1632 // symbol associated with them (they weren't translated) or if they're an FFI
1633 // definition (as that's not defined in this crate).
1634 fn encode_exported_symbols(
1636 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1637 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1638 // The metadata symbol name is special. It should not show up in
1639 // downstream crates.
1640 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1645 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1646 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1653 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1654 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1655 for (ty, arr) in formats.iter() {
1656 if *ty != CrateType::Dylib {
1659 return self.lazy(arr.iter().map(|slot| match *slot {
1660 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1662 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1663 Linkage::Static => Some(LinkagePreference::RequireStatic),
1669 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1672 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1674 record!(self.tables.kind[def_id] <- match nitem.kind {
1675 hir::ForeignItemKind::Fn(_, ref names, _) => {
1677 asyncness: hir::IsAsync::NotAsync,
1678 constness: if self.tcx.is_const_fn_raw(def_id) {
1679 hir::Constness::Const
1681 hir::Constness::NotConst
1683 param_names: self.encode_fn_param_names(names),
1685 EntryKind::ForeignFn(self.lazy(data))
1687 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1688 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1689 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1691 record!(self.tables.visibility[def_id] <-
1692 ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx));
1693 record!(self.tables.span[def_id] <- nitem.span);
1694 record!(self.tables.attributes[def_id] <- nitem.attrs);
1695 self.encode_ident_span(def_id, nitem.ident);
1696 self.encode_stability(def_id);
1697 self.encode_const_stability(def_id);
1698 self.encode_deprecation(def_id);
1699 self.encode_item_type(def_id);
1700 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1701 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1702 self.encode_variances_of(def_id);
1704 self.encode_generics(def_id);
1705 self.encode_explicit_predicates(def_id);
1706 self.encode_inferred_outlives(def_id);
1710 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1711 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1712 type Map = Map<'tcx>;
1714 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1715 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1717 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1718 intravisit::walk_expr(self, ex);
1719 self.encode_info_for_expr(ex);
1721 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1722 intravisit::walk_anon_const(self, c);
1723 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1724 self.encode_info_for_anon_const(def_id);
1726 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1727 intravisit::walk_item(self, item);
1728 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1730 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1731 _ => self.encode_info_for_item(def_id.to_def_id(), item),
1733 self.encode_addl_info_for_item(item);
1735 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1736 intravisit::walk_foreign_item(self, ni);
1737 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1738 self.encode_info_for_foreign_item(def_id.to_def_id(), ni);
1740 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1741 intravisit::walk_generics(self, generics);
1742 self.encode_info_for_generics(generics);
1744 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1745 self.encode_info_for_macro_def(macro_def);
1749 impl EncodeContext<'a, 'tcx> {
1750 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1751 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1752 for (field_index, _field) in variant.fields.iter().enumerate() {
1753 self.encode_field(adt_def, variant_index, field_index);
1758 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1759 for param in generics.params {
1760 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1762 GenericParamKind::Lifetime { .. } => continue,
1763 GenericParamKind::Type { ref default, .. } => {
1764 self.encode_info_for_generic_param(
1766 EntryKind::TypeParam,
1770 GenericParamKind::Const { .. } => {
1771 self.encode_info_for_generic_param(
1773 EntryKind::ConstParam,
1781 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1782 if let hir::ExprKind::Closure(..) = expr.kind {
1783 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1784 self.encode_info_for_closure(def_id);
1788 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1789 record!(self.tables.ident_span[def_id] <- ident.span);
1792 /// In some cases, along with the item itself, we also
1793 /// encode some sub-items. Usually we want some info from the item
1794 /// so it's easier to do that here then to wait until we would encounter
1795 /// normally in the visitor walk.
1796 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1797 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1799 hir::ItemKind::Static(..)
1800 | hir::ItemKind::Const(..)
1801 | hir::ItemKind::Fn(..)
1802 | hir::ItemKind::Mod(..)
1803 | hir::ItemKind::ForeignMod(..)
1804 | hir::ItemKind::GlobalAsm(..)
1805 | hir::ItemKind::ExternCrate(..)
1806 | hir::ItemKind::Use(..)
1807 | hir::ItemKind::TyAlias(..)
1808 | hir::ItemKind::OpaqueTy(..)
1809 | hir::ItemKind::TraitAlias(..) => {
1810 // no sub-item recording needed in these cases
1812 hir::ItemKind::Enum(..) => {
1813 let def = self.tcx.adt_def(def_id.to_def_id());
1814 self.encode_fields(def);
1816 for (i, variant) in def.variants.iter_enumerated() {
1817 self.encode_enum_variant_info(def, i);
1819 if let Some(_ctor_def_id) = variant.ctor_def_id {
1820 self.encode_enum_variant_ctor(def, i);
1824 hir::ItemKind::Struct(ref struct_def, _) => {
1825 let def = self.tcx.adt_def(def_id.to_def_id());
1826 self.encode_fields(def);
1828 // If the struct has a constructor, encode it.
1829 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1830 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1831 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1834 hir::ItemKind::Union(..) => {
1835 let def = self.tcx.adt_def(def_id.to_def_id());
1836 self.encode_fields(def);
1838 hir::ItemKind::Impl { .. } => {
1839 for &trait_item_def_id in
1840 self.tcx.associated_item_def_ids(def_id.to_def_id()).iter()
1842 self.encode_info_for_impl_item(trait_item_def_id);
1845 hir::ItemKind::Trait(..) => {
1846 for &item_def_id in self.tcx.associated_item_def_ids(def_id.to_def_id()).iter() {
1847 self.encode_info_for_trait_item(item_def_id);
1854 struct ImplVisitor<'tcx> {
1856 impls: FxHashMap<DefId, Vec<DefIndex>>,
1859 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1860 fn visit_item(&mut self, item: &hir::Item<'_>) {
1861 if let hir::ItemKind::Impl { .. } = item.kind {
1862 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1863 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id.to_def_id()) {
1864 self.impls.entry(trait_ref.def_id).or_default().push(impl_id.local_def_index);
1869 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1871 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1872 // handled in `visit_item` above
1876 /// Used to prefetch queries which will be needed later by metadata encoding.
1877 /// Only a subset of the queries are actually prefetched to keep this code smaller.
1878 struct PrefetchVisitor<'tcx> {
1880 mir_keys: &'tcx FxHashSet<LocalDefId>,
1883 impl<'tcx> PrefetchVisitor<'tcx> {
1884 fn prefetch_mir(&self, def_id: LocalDefId) {
1885 if self.mir_keys.contains(&def_id) {
1886 self.tcx.ensure().optimized_mir(def_id);
1887 self.tcx.ensure().promoted_mir(def_id);
1892 impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> {
1893 fn visit_item(&self, item: &hir::Item<'_>) {
1894 // This should be kept in sync with `encode_info_for_item`.
1897 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
1898 self.prefetch_mir(tcx.hir().local_def_id(item.hir_id))
1900 hir::ItemKind::Fn(ref sig, ..) => {
1901 let def_id = tcx.hir().local_def_id(item.hir_id);
1902 let generics = tcx.generics_of(def_id.to_def_id());
1903 let needs_inline = generics.requires_monomorphization(tcx)
1904 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1905 if needs_inline || sig.header.constness == hir::Constness::Const {
1906 self.prefetch_mir(def_id)
1913 fn visit_trait_item(&self, trait_item: &'v hir::TraitItem<'v>) {
1914 // This should be kept in sync with `encode_info_for_trait_item`.
1915 self.prefetch_mir(self.tcx.hir().local_def_id(trait_item.hir_id));
1918 fn visit_impl_item(&self, impl_item: &'v hir::ImplItem<'v>) {
1919 // This should be kept in sync with `encode_info_for_impl_item`.
1921 match impl_item.kind {
1922 hir::ImplItemKind::Const(..) => {
1923 self.prefetch_mir(tcx.hir().local_def_id(impl_item.hir_id))
1925 hir::ImplItemKind::Fn(ref sig, _) => {
1926 let def_id = tcx.hir().local_def_id(impl_item.hir_id);
1927 let generics = tcx.generics_of(def_id.to_def_id());
1928 let needs_inline = generics.requires_monomorphization(tcx)
1929 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1930 let is_const_fn = sig.header.constness == hir::Constness::Const;
1931 if needs_inline || is_const_fn {
1932 self.prefetch_mir(def_id)
1935 hir::ImplItemKind::TyAlias(..) => (),
1940 // NOTE(eddyb) The following comment was preserved for posterity, even
1941 // though it's no longer relevant as EBML (which uses nested & tagged
1942 // "documents") was replaced with a scheme that can't go out of bounds.
1944 // And here we run into yet another obscure archive bug: in which metadata
1945 // loaded from archives may have trailing garbage bytes. Awhile back one of
1946 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1947 // and opt) by having ebml generate an out-of-bounds panic when looking at
1950 // Upon investigation it turned out that the metadata file inside of an rlib
1951 // (and ar archive) was being corrupted. Some compilations would generate a
1952 // metadata file which would end in a few extra bytes, while other
1953 // compilations would not have these extra bytes appended to the end. These
1954 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1955 // being interpreted causing the out-of-bounds.
1957 // The root cause of why these extra bytes were appearing was never
1958 // discovered, and in the meantime the solution we're employing is to insert
1959 // the length of the metadata to the start of the metadata. Later on this
1960 // will allow us to slice the metadata to the precise length that we just
1961 // generated regardless of trailing bytes that end up in it.
1963 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1964 // Since encoding metadata is not in a query, and nothing is cached,
1965 // there's no need to do dep-graph tracking for any of it.
1966 tcx.dep_graph.assert_ignored();
1969 || encode_metadata_impl(tcx),
1971 if tcx.sess.threads() == 1 {
1974 // Prefetch some queries used by metadata encoding.
1975 // This is not necessary for correctness, but is only done for performance reasons.
1976 // It can be removed if it turns out to cause trouble or be detrimental to performance.
1979 if !tcx.sess.opts.output_types.should_codegen() {
1980 // We won't emit MIR, so don't prefetch it.
1983 tcx.hir().krate().par_visit_all_item_likes(&PrefetchVisitor {
1985 mir_keys: tcx.mir_keys(LOCAL_CRATE),
1988 || tcx.exported_symbols(LOCAL_CRATE),
1995 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
1996 let mut encoder = opaque::Encoder::new(vec![]);
1997 encoder.emit_raw_bytes(METADATA_HEADER);
1999 // Will be filled with the root position after encoding everything.
2000 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2002 let source_map_files = tcx.sess.source_map().files();
2003 let hygiene_ctxt = HygieneEncodeContext::default();
2005 let mut ecx = EncodeContext {
2008 tables: Default::default(),
2009 lazy_state: LazyState::NoNode,
2010 type_shorthands: Default::default(),
2011 predicate_shorthands: Default::default(),
2012 source_file_cache: (source_map_files[0].clone(), 0),
2013 interpret_allocs: Default::default(),
2014 interpret_allocs_inverse: Default::default(),
2015 required_source_files: Some(GrowableBitSet::with_capacity(source_map_files.len())),
2016 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2017 hygiene_ctxt: &hygiene_ctxt,
2019 drop(source_map_files);
2021 // Encode the rustc version string in a predictable location.
2022 rustc_version().encode(&mut ecx).unwrap();
2024 // Encode all the entries and extra information in the crate,
2025 // culminating in the `CrateRoot` which points to all of it.
2026 let root = ecx.encode_crate_root();
2028 let mut result = ecx.opaque.into_inner();
2030 // Encode the root position.
2031 let header = METADATA_HEADER.len();
2032 let pos = root.position.get();
2033 result[header + 0] = (pos >> 24) as u8;
2034 result[header + 1] = (pos >> 16) as u8;
2035 result[header + 2] = (pos >> 8) as u8;
2036 result[header + 3] = (pos >> 0) as u8;
2038 EncodedMetadata { raw_data: result }