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.
283 if self.is_proc_macro {
284 SyntaxContext::root().encode(self)?;
286 span.ctxt.encode(self)?;
289 if tag == TAG_VALID_SPAN_FOREIGN {
290 // This needs to be two lines to avoid holding the `self.source_file_cache`
291 // while calling `cnum.encode(self)`
292 let cnum = self.source_file_cache.0.cnum;
300 impl<'a, 'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'a, 'tcx> {
302 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
303 self.specialized_encode(&def_id.to_def_id())
307 impl<'a, 'b, 'c, 'tcx> SpecializedEncoder<&'a ty::TyS<'b>> for EncodeContext<'c, 'tcx>
309 &'a ty::TyS<'b>: UseSpecializedEncodable,
311 fn specialized_encode(&mut self, ty: &&'a ty::TyS<'b>) -> Result<(), Self::Error> {
312 debug_assert!(self.tcx.lift(ty).is_some());
313 let ty = unsafe { std::mem::transmute::<&&'a ty::TyS<'b>, &&'tcx ty::TyS<'tcx>>(ty) };
314 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
318 impl<'a, 'b, 'tcx> SpecializedEncoder<ty::Predicate<'b>> for EncodeContext<'a, 'tcx> {
319 fn specialized_encode(&mut self, predicate: &ty::Predicate<'b>) -> Result<(), Self::Error> {
320 debug_assert!(self.tcx.lift(predicate).is_some());
322 unsafe { std::mem::transmute::<&ty::Predicate<'b>, &ty::Predicate<'tcx>>(predicate) };
323 ty_codec::encode_with_shorthand(self, predicate, |encoder| {
324 &mut encoder.predicate_shorthands
329 impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> {
330 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
331 use std::collections::hash_map::Entry;
332 let index = match self.interpret_allocs.entry(*alloc_id) {
333 Entry::Occupied(e) => *e.get(),
334 Entry::Vacant(e) => {
335 let idx = self.interpret_allocs_inverse.len();
336 self.interpret_allocs_inverse.push(*alloc_id);
346 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
347 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
348 f.encode_opaque(&mut self.opaque)
352 impl<'a, 'tcx, T> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'a, 'tcx>
354 mir::ClearCrossCrate<T>: UseSpecializedEncodable,
356 fn specialized_encode(&mut self, _: &mir::ClearCrossCrate<T>) -> Result<(), Self::Error> {
361 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
362 fn position(&self) -> usize {
363 self.opaque.position()
367 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
368 trait EncodeContentsForLazy<T: ?Sized + LazyMeta> {
369 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
372 impl<T: Encodable> EncodeContentsForLazy<T> for &T {
373 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
374 self.encode(ecx).unwrap()
378 impl<T: Encodable> EncodeContentsForLazy<T> for T {
379 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
380 self.encode(ecx).unwrap()
384 impl<I, T: Encodable> EncodeContentsForLazy<[T]> for I
387 I::Item: EncodeContentsForLazy<T>,
389 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
390 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
394 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
395 // normally need extra variables to avoid errors about multiple mutable borrows.
396 macro_rules! record {
397 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
400 let lazy = $self.lazy(value);
401 $self.$tables.$table.set($def_id.index, lazy);
406 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
407 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
410 ) -> Result<(), <Self as Encoder>::Error> {
411 let min_end = lazy.position.get() + T::min_size(lazy.meta);
412 let distance = match self.lazy_state {
413 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
414 LazyState::NodeStart(start) => {
415 let start = start.get();
416 assert!(min_end <= start);
419 LazyState::Previous(last_min_end) => {
421 last_min_end <= lazy.position,
422 "make sure that the calls to `lazy*` \
423 are in the same order as the metadata fields",
425 lazy.position.get() - last_min_end.get()
428 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
429 self.emit_usize(distance)
432 fn lazy<T: ?Sized + LazyMeta>(&mut self, value: impl EncodeContentsForLazy<T>) -> Lazy<T> {
433 let pos = NonZeroUsize::new(self.position()).unwrap();
435 assert_eq!(self.lazy_state, LazyState::NoNode);
436 self.lazy_state = LazyState::NodeStart(pos);
437 let meta = value.encode_contents_for_lazy(self);
438 self.lazy_state = LazyState::NoNode;
440 assert!(pos.get() + <T>::min_size(meta) <= self.position());
442 Lazy::from_position_and_meta(pos, meta)
445 fn encode_info_for_items(&mut self) {
446 let krate = self.tcx.hir().krate();
447 let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public };
448 self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.item.module, &krate.item.attrs, &vis);
449 krate.visit_all_item_likes(&mut self.as_deep_visitor());
450 for macro_def in krate.exported_macros {
451 self.visit_macro_def(macro_def);
455 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
456 let definitions = self.tcx.hir().definitions();
457 self.lazy(definitions.def_path_table())
460 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
461 let source_map = self.tcx.sess.source_map();
462 let all_source_files = source_map.files();
464 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
465 // By replacing the `Option` with `None`, we ensure that we can't
466 // accidentally serialize any more `Span`s after the source map encoding
468 let required_source_files = self.required_source_files.take().unwrap();
470 let adapted = all_source_files
473 .filter(|(idx, source_file)| {
474 // Only serialize `SourceFile`s that were used
475 // during the encoding of a `Span`
476 required_source_files.contains(*idx) &&
477 // Don't serialize imported `SourceFile`s, unless
478 // we're in a proc-macro crate.
479 (!source_file.is_imported() || self.is_proc_macro)
481 .map(|(_, source_file)| {
482 let mut adapted = match source_file.name {
483 // This path of this SourceFile has been modified by
484 // path-remapping, so we use it verbatim (and avoid
485 // cloning the whole map in the process).
486 _ if source_file.name_was_remapped => source_file.clone(),
488 // Otherwise expand all paths to absolute paths because
489 // any relative paths are potentially relative to a
491 FileName::Real(ref name) => {
492 let name = name.stable_name();
493 let mut adapted = (**source_file).clone();
494 adapted.name = Path::new(&working_dir).join(name).into();
495 adapted.name_hash = {
496 let mut hasher: StableHasher = StableHasher::new();
497 adapted.name.hash(&mut hasher);
498 hasher.finish::<u128>()
503 // expanded code, not from a file
504 _ => source_file.clone(),
507 // We're serializing this `SourceFile` into our crate metadata,
508 // so mark it as coming from this crate.
509 // This also ensures that we don't try to deserialize the
510 // `CrateNum` for a proc-macro dependency - since proc macro
511 // dependencies aren't loaded when we deserialize a proc-macro,
512 // trying to remap the `CrateNum` would fail.
513 if self.is_proc_macro {
514 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
518 .collect::<Vec<_>>();
520 self.lazy(adapted.iter().map(|rc| &**rc))
523 fn is_proc_macro(&self) -> bool {
524 self.tcx.sess.crate_types().contains(&CrateType::ProcMacro)
527 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
528 let is_proc_macro = self.is_proc_macro();
530 let mut i = self.position();
532 // Encode the crate deps
533 let crate_deps = self.encode_crate_deps();
534 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
535 let dep_bytes = self.position() - i;
537 // Encode the lib features.
539 let lib_features = self.encode_lib_features();
540 let lib_feature_bytes = self.position() - i;
542 // Encode the language items.
544 let lang_items = self.encode_lang_items();
545 let lang_items_missing = self.encode_lang_items_missing();
546 let lang_item_bytes = self.position() - i;
548 // Encode the diagnostic items.
550 let diagnostic_items = self.encode_diagnostic_items();
551 let diagnostic_item_bytes = self.position() - i;
553 // Encode the native libraries used
555 let native_libraries = self.encode_native_libraries();
556 let native_lib_bytes = self.position() - i;
558 let foreign_modules = self.encode_foreign_modules();
560 // Encode DefPathTable
562 let def_path_table = self.encode_def_path_table();
563 let def_path_table_bytes = self.position() - i;
565 // Encode the def IDs of impls, for coherence checking.
567 let impls = self.encode_impls();
568 let impl_bytes = self.position() - i;
574 self.encode_info_for_items();
575 let item_bytes = self.position() - i;
577 // Encode the allocation index
578 let interpret_alloc_index = {
579 let mut interpret_alloc_index = Vec::new();
581 trace!("beginning to encode alloc ids");
583 let new_n = self.interpret_allocs_inverse.len();
584 // if we have found new ids, serialize those, too
589 trace!("encoding {} further alloc ids", new_n - n);
590 for idx in n..new_n {
591 let id = self.interpret_allocs_inverse[idx];
592 let pos = self.position() as u32;
593 interpret_alloc_index.push(pos);
594 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
598 self.lazy(interpret_alloc_index)
602 let tables = self.tables.encode(&mut self.opaque);
603 let tables_bytes = self.position() - i;
605 // Encode the proc macro data
607 let proc_macro_data = self.encode_proc_macros();
608 let proc_macro_data_bytes = self.position() - i;
610 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
611 // this as late as possible to give the prefetching as much time as possible to complete.
613 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
614 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
615 let exported_symbols_bytes = self.position() - i;
617 // Encode the hygiene data,
618 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
619 // of encoding other items (e.g. `optimized_mir`) may cause us to load
620 // data from the incremental cache. If this causes us to deserialize a `Span`,
621 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
622 // Therefore, we need to encode the hygiene data last to ensure that we encode
623 // any `SyntaxContext`s that might be used.
625 let (syntax_contexts, expn_data) = self.encode_hygiene();
626 let hygiene_bytes = self.position() - i;
628 // Encode source_map. This needs to be done last,
629 // since encoding `Span`s tells us which `SourceFiles` we actually
632 let source_map = self.encode_source_map();
633 let source_map_bytes = self.position() - i;
635 let attrs = tcx.hir().krate_attrs();
636 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
638 let root = self.lazy(CrateRoot {
639 name: tcx.crate_name(LOCAL_CRATE),
640 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
641 triple: tcx.sess.opts.target_triple.clone(),
642 hash: tcx.crate_hash(LOCAL_CRATE),
643 disambiguator: tcx.sess.local_crate_disambiguator(),
644 panic_strategy: tcx.sess.panic_strategy(),
645 edition: tcx.sess.edition(),
646 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
647 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
648 has_default_lib_allocator,
649 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
650 proc_macro_decls_static: if is_proc_macro {
651 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
657 proc_macro_stability: if is_proc_macro {
658 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied()
662 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
663 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
664 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
665 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
666 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
667 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
668 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
671 dylib_dependency_formats,
682 interpret_alloc_index,
688 let total_bytes = self.position();
690 if tcx.sess.meta_stats() {
691 let mut zero_bytes = 0;
692 for e in self.opaque.data.iter() {
698 println!("metadata stats:");
699 println!(" dep bytes: {}", dep_bytes);
700 println!(" lib feature bytes: {}", lib_feature_bytes);
701 println!(" lang item bytes: {}", lang_item_bytes);
702 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
703 println!(" native bytes: {}", native_lib_bytes);
704 println!(" source_map bytes: {}", source_map_bytes);
705 println!(" impl bytes: {}", impl_bytes);
706 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
707 println!(" def-path table bytes: {}", def_path_table_bytes);
708 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
709 println!(" item bytes: {}", item_bytes);
710 println!(" table bytes: {}", tables_bytes);
711 println!(" hygiene bytes: {}", hygiene_bytes);
712 println!(" zero bytes: {}", zero_bytes);
713 println!(" total bytes: {}", total_bytes);
720 impl EncodeContext<'a, 'tcx> {
721 fn encode_variances_of(&mut self, def_id: DefId) {
722 debug!("EncodeContext::encode_variances_of({:?})", def_id);
723 record!(self.tables.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
726 fn encode_item_type(&mut self, def_id: DefId) {
727 debug!("EncodeContext::encode_item_type({:?})", def_id);
728 record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
731 fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
733 let variant = &def.variants[index];
734 let def_id = variant.def_id;
735 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
737 let data = VariantData {
738 ctor_kind: variant.ctor_kind,
739 discr: variant.discr,
740 ctor: variant.ctor_def_id.map(|did| did.index),
741 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
744 let enum_id = tcx.hir().as_local_hir_id(def.did.expect_local());
745 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
747 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
748 record!(self.tables.visibility[def_id] <-
749 ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
750 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
751 record!(self.tables.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
752 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
753 assert!(f.did.is_local());
756 self.encode_ident_span(def_id, variant.ident);
757 self.encode_stability(def_id);
758 self.encode_deprecation(def_id);
759 self.encode_item_type(def_id);
760 if variant.ctor_kind == CtorKind::Fn {
761 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
762 if let Some(ctor_def_id) = variant.ctor_def_id {
763 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
765 // FIXME(eddyb) is this ever used?
766 self.encode_variances_of(def_id);
768 self.encode_generics(def_id);
769 self.encode_explicit_predicates(def_id);
770 self.encode_inferred_outlives(def_id);
771 self.encode_optimized_mir(def_id.expect_local());
772 self.encode_promoted_mir(def_id.expect_local());
775 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
777 let variant = &def.variants[index];
778 let def_id = variant.ctor_def_id.unwrap();
779 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
781 // FIXME(eddyb) encode only the `CtorKind` for constructors.
782 let data = VariantData {
783 ctor_kind: variant.ctor_kind,
784 discr: variant.discr,
785 ctor: Some(def_id.index),
786 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
789 // Variant constructors have the same visibility as the parent enums, unless marked as
790 // non-exhaustive, in which case they are lowered to `pub(crate)`.
791 let enum_id = tcx.hir().as_local_hir_id(def.did.expect_local());
792 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
793 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
794 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
795 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
798 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
799 record!(self.tables.visibility[def_id] <- ctor_vis);
800 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
801 self.encode_stability(def_id);
802 self.encode_deprecation(def_id);
803 self.encode_item_type(def_id);
804 if variant.ctor_kind == CtorKind::Fn {
805 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
806 self.encode_variances_of(def_id);
808 self.encode_generics(def_id);
809 self.encode_explicit_predicates(def_id);
810 self.encode_inferred_outlives(def_id);
811 self.encode_optimized_mir(def_id.expect_local());
812 self.encode_promoted_mir(def_id.expect_local());
815 fn encode_info_for_mod(
819 attrs: &[ast::Attribute],
820 vis: &hir::Visibility<'_>,
823 let local_def_id = tcx.hir().local_def_id(id);
824 let def_id = local_def_id.to_def_id();
825 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
828 reexports: match tcx.module_exports(local_def_id) {
830 let hir_map = self.tcx.hir();
834 .map(|export| export.map_id(|id| hir_map.as_local_hir_id(id))),
839 expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
842 record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
843 record!(self.tables.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
844 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
845 record!(self.tables.attributes[def_id] <- attrs);
846 record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
847 tcx.hir().local_def_id(item_id.id).local_def_index
849 self.encode_stability(def_id);
850 self.encode_deprecation(def_id);
855 adt_def: &ty::AdtDef,
856 variant_index: VariantIdx,
860 let variant = &adt_def.variants[variant_index];
861 let field = &variant.fields[field_index];
863 let def_id = field.did;
864 debug!("EncodeContext::encode_field({:?})", def_id);
866 let variant_id = tcx.hir().as_local_hir_id(variant.def_id.expect_local());
867 let variant_data = tcx.hir().expect_variant_data(variant_id);
869 record!(self.tables.kind[def_id] <- EntryKind::Field);
870 record!(self.tables.visibility[def_id] <- field.vis);
871 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
872 record!(self.tables.attributes[def_id] <- variant_data.fields()[field_index].attrs);
873 self.encode_ident_span(def_id, field.ident);
874 self.encode_stability(def_id);
875 self.encode_deprecation(def_id);
876 self.encode_item_type(def_id);
877 self.encode_generics(def_id);
878 self.encode_explicit_predicates(def_id);
879 self.encode_inferred_outlives(def_id);
882 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
883 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
885 let variant = adt_def.non_enum_variant();
887 let data = VariantData {
888 ctor_kind: variant.ctor_kind,
889 discr: variant.discr,
890 ctor: Some(def_id.index),
891 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
894 let struct_id = tcx.hir().as_local_hir_id(adt_def.did.expect_local());
895 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
896 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
897 for field in &variant.fields {
898 if ctor_vis.is_at_least(field.vis, tcx) {
899 ctor_vis = field.vis;
903 // If the structure is marked as non_exhaustive then lower the visibility
904 // to within the crate.
905 if adt_def.non_enum_variant().is_field_list_non_exhaustive()
906 && ctor_vis == ty::Visibility::Public
908 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
911 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
912 record!(self.tables.visibility[def_id] <- ctor_vis);
913 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
914 self.encode_stability(def_id);
915 self.encode_deprecation(def_id);
916 self.encode_item_type(def_id);
917 if variant.ctor_kind == CtorKind::Fn {
918 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
919 self.encode_variances_of(def_id);
921 self.encode_generics(def_id);
922 self.encode_explicit_predicates(def_id);
923 self.encode_inferred_outlives(def_id);
924 self.encode_optimized_mir(def_id.expect_local());
925 self.encode_promoted_mir(def_id.expect_local());
928 fn encode_generics(&mut self, def_id: DefId) {
929 debug!("EncodeContext::encode_generics({:?})", def_id);
930 record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
933 fn encode_explicit_predicates(&mut self, def_id: DefId) {
934 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
935 record!(self.tables.explicit_predicates[def_id] <-
936 self.tcx.explicit_predicates_of(def_id));
939 fn encode_inferred_outlives(&mut self, def_id: DefId) {
940 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
941 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
942 if !inferred_outlives.is_empty() {
943 record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
947 fn encode_super_predicates(&mut self, def_id: DefId) {
948 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
949 record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
952 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
953 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
956 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
957 let ast_item = tcx.hir().expect_trait_item(hir_id);
958 let trait_item = tcx.associated_item(def_id);
960 let container = match trait_item.defaultness {
961 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
962 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
963 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
966 record!(self.tables.kind[def_id] <- match trait_item.kind {
967 ty::AssocKind::Const => {
968 let rendered = rustc_hir_pretty::to_string(
969 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
970 |s| s.print_trait_item(ast_item)
972 let rendered_const = self.lazy(RenderedConst(rendered));
974 EntryKind::AssocConst(
980 ty::AssocKind::Fn => {
981 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
982 let param_names = match *m {
983 hir::TraitFn::Required(ref names) => {
984 self.encode_fn_param_names(names)
986 hir::TraitFn::Provided(body) => {
987 self.encode_fn_param_names_for_body(body)
991 asyncness: m_sig.header.asyncness,
992 constness: hir::Constness::NotConst,
998 EntryKind::AssocFn(self.lazy(AssocFnData {
1001 has_self: trait_item.fn_has_self_parameter,
1004 ty::AssocKind::Type => EntryKind::AssocType(container),
1006 record!(self.tables.visibility[def_id] <- trait_item.vis);
1007 record!(self.tables.span[def_id] <- ast_item.span);
1008 record!(self.tables.attributes[def_id] <- ast_item.attrs);
1009 self.encode_ident_span(def_id, ast_item.ident);
1010 self.encode_stability(def_id);
1011 self.encode_const_stability(def_id);
1012 self.encode_deprecation(def_id);
1013 match trait_item.kind {
1014 ty::AssocKind::Const | ty::AssocKind::Fn => {
1015 self.encode_item_type(def_id);
1017 ty::AssocKind::Type => {
1018 if trait_item.defaultness.has_value() {
1019 self.encode_item_type(def_id);
1023 if trait_item.kind == ty::AssocKind::Fn {
1024 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1025 self.encode_variances_of(def_id);
1027 self.encode_generics(def_id);
1028 self.encode_explicit_predicates(def_id);
1029 self.encode_inferred_outlives(def_id);
1031 // This should be kept in sync with `PrefetchVisitor.visit_trait_item`.
1032 self.encode_optimized_mir(def_id.expect_local());
1033 self.encode_promoted_mir(def_id.expect_local());
1036 fn metadata_output_only(&self) -> bool {
1037 // MIR optimisation can be skipped when we're just interested in the metadata.
1038 !self.tcx.sess.opts.output_types.should_codegen()
1041 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1042 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1045 let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local());
1046 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1047 let impl_item = self.tcx.associated_item(def_id);
1049 let container = match impl_item.defaultness {
1050 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1051 hir::Defaultness::Final => AssocContainer::ImplFinal,
1052 hir::Defaultness::Default { has_value: false } => {
1053 span_bug!(ast_item.span, "impl items always have values (currently)")
1057 record!(self.tables.kind[def_id] <- match impl_item.kind {
1058 ty::AssocKind::Const => {
1059 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1060 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1062 EntryKind::AssocConst(
1065 self.encode_rendered_const_for_body(body_id))
1070 ty::AssocKind::Fn => {
1071 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1073 asyncness: sig.header.asyncness,
1074 constness: sig.header.constness,
1075 param_names: self.encode_fn_param_names_for_body(body),
1080 EntryKind::AssocFn(self.lazy(AssocFnData {
1083 has_self: impl_item.fn_has_self_parameter,
1086 ty::AssocKind::Type => EntryKind::AssocType(container)
1088 record!(self.tables.visibility[def_id] <- impl_item.vis);
1089 record!(self.tables.span[def_id] <- ast_item.span);
1090 record!(self.tables.attributes[def_id] <- ast_item.attrs);
1091 self.encode_ident_span(def_id, impl_item.ident);
1092 self.encode_stability(def_id);
1093 self.encode_const_stability(def_id);
1094 self.encode_deprecation(def_id);
1095 self.encode_item_type(def_id);
1096 if impl_item.kind == ty::AssocKind::Fn {
1097 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1098 self.encode_variances_of(def_id);
1100 self.encode_generics(def_id);
1101 self.encode_explicit_predicates(def_id);
1102 self.encode_inferred_outlives(def_id);
1104 // The following part should be kept in sync with `PrefetchVisitor.visit_impl_item`.
1106 let mir = match ast_item.kind {
1107 hir::ImplItemKind::Const(..) => true,
1108 hir::ImplItemKind::Fn(ref sig, _) => {
1109 let generics = self.tcx.generics_of(def_id);
1110 let needs_inline = (generics.requires_monomorphization(self.tcx)
1111 || tcx.codegen_fn_attrs(def_id).requests_inline())
1112 && !self.metadata_output_only();
1113 let is_const_fn = sig.header.constness == hir::Constness::Const;
1114 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1115 needs_inline || is_const_fn || always_encode_mir
1117 hir::ImplItemKind::TyAlias(..) => false,
1120 self.encode_optimized_mir(def_id.expect_local());
1121 self.encode_promoted_mir(def_id.expect_local());
1125 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1126 self.tcx.dep_graph.with_ignore(|| self.lazy(self.tcx.hir().body_param_names(body_id)))
1129 fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1130 self.lazy(param_names.iter())
1133 fn encode_optimized_mir(&mut self, def_id: LocalDefId) {
1134 debug!("EntryBuilder::encode_mir({:?})", def_id);
1135 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1136 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1138 let unused = self.tcx.unused_generic_params(def_id);
1139 if !unused.is_empty() {
1140 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1145 fn encode_promoted_mir(&mut self, def_id: LocalDefId) {
1146 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1147 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1148 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1152 // Encodes the inherent implementations of a structure, enumeration, or trait.
1153 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1154 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1155 let implementations = self.tcx.inherent_impls(def_id);
1156 if !implementations.is_empty() {
1157 record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1158 assert!(def_id.is_local());
1164 fn encode_stability(&mut self, def_id: DefId) {
1165 debug!("EncodeContext::encode_stability({:?})", def_id);
1166 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1167 record!(self.tables.stability[def_id] <- stab)
1171 fn encode_const_stability(&mut self, def_id: DefId) {
1172 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1173 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1174 record!(self.tables.const_stability[def_id] <- stab)
1178 fn encode_deprecation(&mut self, def_id: DefId) {
1179 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1180 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1181 record!(self.tables.deprecation[def_id] <- depr);
1185 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1186 let hir = self.tcx.hir();
1187 let body = hir.body(body_id);
1188 let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1189 s.print_expr(&body.value)
1191 let rendered_const = &RenderedConst(rendered);
1192 self.lazy(rendered_const)
1195 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1198 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1200 self.encode_ident_span(def_id, item.ident);
1202 record!(self.tables.kind[def_id] <- match item.kind {
1203 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1204 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1205 hir::ItemKind::Const(_, body_id) => {
1206 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1209 self.encode_rendered_const_for_body(body_id)
1212 hir::ItemKind::Fn(ref sig, .., body) => {
1214 asyncness: sig.header.asyncness,
1215 constness: sig.header.constness,
1216 param_names: self.encode_fn_param_names_for_body(body),
1219 EntryKind::Fn(self.lazy(data))
1221 hir::ItemKind::Mod(ref m) => {
1222 return self.encode_info_for_mod(item.hir_id, m, &item.attrs, &item.vis);
1224 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1225 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1226 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1227 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1228 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1229 hir::ItemKind::Struct(ref struct_def, _) => {
1230 let adt_def = self.tcx.adt_def(def_id);
1231 let variant = adt_def.non_enum_variant();
1233 // Encode def_ids for each field and method
1234 // for methods, write all the stuff get_trait_method
1236 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1237 self.tcx.hir().local_def_id(ctor_hir_id).local_def_index
1240 EntryKind::Struct(self.lazy(VariantData {
1241 ctor_kind: variant.ctor_kind,
1242 discr: variant.discr,
1244 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1247 hir::ItemKind::Union(..) => {
1248 let adt_def = self.tcx.adt_def(def_id);
1249 let variant = adt_def.non_enum_variant();
1251 EntryKind::Union(self.lazy(VariantData {
1252 ctor_kind: variant.ctor_kind,
1253 discr: variant.discr,
1255 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1258 hir::ItemKind::Impl { defaultness, .. } => {
1259 let trait_ref = self.tcx.impl_trait_ref(def_id);
1260 let polarity = self.tcx.impl_polarity(def_id);
1261 let parent = if let Some(trait_ref) = trait_ref {
1262 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1263 trait_def.ancestors(self.tcx, def_id).ok()
1264 .and_then(|mut an| an.nth(1).and_then(|node| {
1266 specialization_graph::Node::Impl(parent) => Some(parent),
1274 // if this is an impl of `CoerceUnsized`, create its
1275 // "unsized info", else just store None
1276 let coerce_unsized_info =
1277 trait_ref.and_then(|t| {
1278 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1279 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1285 let data = ImplData {
1288 parent_impl: parent,
1289 coerce_unsized_info,
1292 EntryKind::Impl(self.lazy(data))
1294 hir::ItemKind::Trait(..) => {
1295 let trait_def = self.tcx.trait_def(def_id);
1296 let data = TraitData {
1297 unsafety: trait_def.unsafety,
1298 paren_sugar: trait_def.paren_sugar,
1299 has_auto_impl: self.tcx.trait_is_auto(def_id),
1300 is_marker: trait_def.is_marker,
1301 specialization_kind: trait_def.specialization_kind,
1304 EntryKind::Trait(self.lazy(data))
1306 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1307 hir::ItemKind::ExternCrate(_) |
1308 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1310 record!(self.tables.visibility[def_id] <-
1311 ty::Visibility::from_hir(&item.vis, item.hir_id, tcx));
1312 record!(self.tables.span[def_id] <- item.span);
1313 record!(self.tables.attributes[def_id] <- item.attrs);
1314 // FIXME(eddyb) there should be a nicer way to do this.
1316 hir::ItemKind::ForeignMod(ref fm) => record!(self.tables.children[def_id] <-
1319 .map(|foreign_item| tcx.hir().local_def_id(
1320 foreign_item.hir_id).local_def_index)
1322 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1323 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1324 assert!(v.def_id.is_local());
1328 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1329 record!(self.tables.children[def_id] <-
1330 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1331 assert!(f.did.is_local());
1336 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1337 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1338 record!(self.tables.children[def_id] <-
1339 associated_item_def_ids.iter().map(|&def_id| {
1340 assert!(def_id.is_local());
1347 self.encode_stability(def_id);
1348 self.encode_const_stability(def_id);
1349 self.encode_deprecation(def_id);
1351 hir::ItemKind::Static(..)
1352 | hir::ItemKind::Const(..)
1353 | hir::ItemKind::Fn(..)
1354 | hir::ItemKind::TyAlias(..)
1355 | hir::ItemKind::OpaqueTy(..)
1356 | hir::ItemKind::Enum(..)
1357 | hir::ItemKind::Struct(..)
1358 | hir::ItemKind::Union(..)
1359 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1362 if let hir::ItemKind::Fn(..) = item.kind {
1363 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1365 if let hir::ItemKind::Impl { .. } = item.kind {
1366 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1367 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1370 self.encode_inherent_implementations(def_id);
1372 hir::ItemKind::Enum(..)
1373 | hir::ItemKind::Struct(..)
1374 | hir::ItemKind::Union(..)
1375 | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1379 hir::ItemKind::Static(..)
1380 | hir::ItemKind::Const(..)
1381 | hir::ItemKind::Fn(..)
1382 | hir::ItemKind::TyAlias(..)
1383 | hir::ItemKind::Enum(..)
1384 | hir::ItemKind::Struct(..)
1385 | hir::ItemKind::Union(..)
1386 | hir::ItemKind::Impl { .. }
1387 | hir::ItemKind::OpaqueTy(..)
1388 | hir::ItemKind::Trait(..)
1389 | hir::ItemKind::TraitAlias(..) => {
1390 self.encode_generics(def_id);
1391 self.encode_explicit_predicates(def_id);
1392 self.encode_inferred_outlives(def_id);
1397 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1398 self.encode_super_predicates(def_id);
1403 // The following part should be kept in sync with `PrefetchVisitor.visit_item`.
1405 let mir = match item.kind {
1406 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1407 hir::ItemKind::Fn(ref sig, ..) => {
1408 let generics = tcx.generics_of(def_id);
1409 let needs_inline = (generics.requires_monomorphization(tcx)
1410 || tcx.codegen_fn_attrs(def_id).requests_inline())
1411 && !self.metadata_output_only();
1412 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1413 needs_inline || sig.header.constness == hir::Constness::Const || always_encode_mir
1418 self.encode_optimized_mir(def_id.expect_local());
1419 self.encode_promoted_mir(def_id.expect_local());
1423 /// Serialize the text of exported macros
1424 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1425 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id();
1426 record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1427 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1428 record!(self.tables.span[def_id] <- macro_def.span);
1429 record!(self.tables.attributes[def_id] <- macro_def.attrs);
1430 self.encode_ident_span(def_id, macro_def.ident);
1431 self.encode_stability(def_id);
1432 self.encode_deprecation(def_id);
1435 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1436 record!(self.tables.kind[def_id] <- kind);
1437 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1438 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1440 self.encode_item_type(def_id);
1444 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1445 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1447 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1448 // including on the signature, which is inferred in `typeck.
1449 let hir_id = self.tcx.hir().as_local_hir_id(def_id);
1450 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1452 record!(self.tables.kind[def_id.to_def_id()] <- match ty.kind {
1453 ty::Generator(..) => {
1454 let data = self.tcx.generator_kind(def_id).unwrap();
1455 EntryKind::Generator(data)
1458 ty::Closure(..) => EntryKind::Closure,
1460 _ => bug!("closure that is neither generator nor closure"),
1462 record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public);
1463 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1464 record!(self.tables.attributes[def_id.to_def_id()] <- &self.tcx.get_attrs(def_id.to_def_id())[..]);
1465 self.encode_item_type(def_id.to_def_id());
1466 if let ty::Closure(def_id, substs) = ty.kind {
1467 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1469 self.encode_generics(def_id.to_def_id());
1470 self.encode_optimized_mir(def_id);
1471 self.encode_promoted_mir(def_id);
1474 fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1475 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1476 let id = self.tcx.hir().as_local_hir_id(def_id);
1477 let body_id = self.tcx.hir().body_owned_by(id);
1478 let const_data = self.encode_rendered_const_for_body(body_id);
1479 let qualifs = self.tcx.mir_const_qualif(def_id);
1481 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1482 record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public);
1483 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1484 self.encode_item_type(def_id.to_def_id());
1485 self.encode_generics(def_id.to_def_id());
1486 self.encode_explicit_predicates(def_id.to_def_id());
1487 self.encode_inferred_outlives(def_id.to_def_id());
1488 self.encode_optimized_mir(def_id);
1489 self.encode_promoted_mir(def_id);
1492 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1493 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1494 self.lazy(used_libraries.iter().cloned())
1497 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1498 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1499 self.lazy(foreign_modules.iter().cloned())
1502 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) {
1503 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1504 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1506 let _: Result<(), !> = self.hygiene_ctxt.encode(
1507 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table),
1508 |(this, syntax_contexts, _), index, ctxt_data| {
1509 syntax_contexts.set(index, this.lazy(ctxt_data));
1512 |(this, _, expn_data_table), index, expn_data| {
1513 expn_data_table.set(index, this.lazy(expn_data));
1518 (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque))
1521 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1522 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1525 Some(self.lazy(tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index)))
1531 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1532 let crates = self.tcx.crates();
1534 let mut deps = crates
1537 let dep = CrateDep {
1538 name: self.tcx.original_crate_name(cnum),
1539 hash: self.tcx.crate_hash(cnum),
1540 host_hash: self.tcx.crate_host_hash(cnum),
1541 kind: self.tcx.dep_kind(cnum),
1542 extra_filename: self.tcx.extra_filename(cnum),
1546 .collect::<Vec<_>>();
1548 deps.sort_by_key(|&(cnum, _)| cnum);
1551 // Sanity-check the crate numbers
1552 let mut expected_cnum = 1;
1553 for &(n, _) in &deps {
1554 assert_eq!(n, CrateNum::new(expected_cnum));
1559 // We're just going to write a list of crate 'name-hash-version's, with
1560 // the assumption that they are numbered 1 to n.
1561 // FIXME (#2166): This is not nearly enough to support correct versioning
1562 // but is enough to get transitive crate dependencies working.
1563 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1566 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1568 let lib_features = tcx.lib_features();
1569 self.lazy(lib_features.to_vec())
1572 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1574 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1575 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1578 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1580 let lang_items = tcx.lang_items();
1581 let lang_items = lang_items.items().iter();
1582 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1583 if let Some(def_id) = opt_def_id {
1584 if def_id.is_local() {
1585 return Some((def_id.index, i));
1592 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1594 self.lazy(&tcx.lang_items().missing)
1597 /// Encodes an index, mapping each trait to its (local) implementations.
1598 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1599 debug!("EncodeContext::encode_impls()");
1601 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1602 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1604 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1606 // Bring everything into deterministic order for hashing
1607 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1609 let all_impls: Vec<_> = all_impls
1611 .map(|(trait_def_id, mut impls)| {
1612 // Bring everything into deterministic order for hashing
1613 impls.sort_by_cached_key(|&index| {
1614 tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1618 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1619 impls: self.lazy(&impls),
1624 self.lazy(&all_impls)
1627 // Encodes all symbols exported from this crate into the metadata.
1629 // This pass is seeded off the reachability list calculated in the
1630 // middle::reachable module but filters out items that either don't have a
1631 // symbol associated with them (they weren't translated) or if they're an FFI
1632 // definition (as that's not defined in this crate).
1633 fn encode_exported_symbols(
1635 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1636 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1637 // The metadata symbol name is special. It should not show up in
1638 // downstream crates.
1639 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1644 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1645 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1652 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1653 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1654 for (ty, arr) in formats.iter() {
1655 if *ty != CrateType::Dylib {
1658 return self.lazy(arr.iter().map(|slot| match *slot {
1659 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1661 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1662 Linkage::Static => Some(LinkagePreference::RequireStatic),
1668 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1671 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1673 record!(self.tables.kind[def_id] <- match nitem.kind {
1674 hir::ForeignItemKind::Fn(_, ref names, _) => {
1676 asyncness: hir::IsAsync::NotAsync,
1677 constness: if self.tcx.is_const_fn_raw(def_id) {
1678 hir::Constness::Const
1680 hir::Constness::NotConst
1682 param_names: self.encode_fn_param_names(names),
1684 EntryKind::ForeignFn(self.lazy(data))
1686 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1687 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1688 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1690 record!(self.tables.visibility[def_id] <-
1691 ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx));
1692 record!(self.tables.span[def_id] <- nitem.span);
1693 record!(self.tables.attributes[def_id] <- nitem.attrs);
1694 self.encode_ident_span(def_id, nitem.ident);
1695 self.encode_stability(def_id);
1696 self.encode_const_stability(def_id);
1697 self.encode_deprecation(def_id);
1698 self.encode_item_type(def_id);
1699 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1700 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1701 self.encode_variances_of(def_id);
1703 self.encode_generics(def_id);
1704 self.encode_explicit_predicates(def_id);
1705 self.encode_inferred_outlives(def_id);
1709 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1710 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1711 type Map = Map<'tcx>;
1713 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1714 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1716 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1717 intravisit::walk_expr(self, ex);
1718 self.encode_info_for_expr(ex);
1720 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1721 intravisit::walk_anon_const(self, c);
1722 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1723 self.encode_info_for_anon_const(def_id);
1725 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1726 intravisit::walk_item(self, item);
1727 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1729 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1730 _ => self.encode_info_for_item(def_id.to_def_id(), item),
1732 self.encode_addl_info_for_item(item);
1734 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1735 intravisit::walk_foreign_item(self, ni);
1736 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1737 self.encode_info_for_foreign_item(def_id.to_def_id(), ni);
1739 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1740 intravisit::walk_generics(self, generics);
1741 self.encode_info_for_generics(generics);
1743 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1744 self.encode_info_for_macro_def(macro_def);
1748 impl EncodeContext<'a, 'tcx> {
1749 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1750 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1751 for (field_index, _field) in variant.fields.iter().enumerate() {
1752 self.encode_field(adt_def, variant_index, field_index);
1757 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1758 for param in generics.params {
1759 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1761 GenericParamKind::Lifetime { .. } => continue,
1762 GenericParamKind::Type { ref default, .. } => {
1763 self.encode_info_for_generic_param(
1765 EntryKind::TypeParam,
1769 GenericParamKind::Const { .. } => {
1770 self.encode_info_for_generic_param(
1772 EntryKind::ConstParam,
1780 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1781 if let hir::ExprKind::Closure(..) = expr.kind {
1782 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1783 self.encode_info_for_closure(def_id);
1787 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1788 record!(self.tables.ident_span[def_id] <- ident.span);
1791 /// In some cases, along with the item itself, we also
1792 /// encode some sub-items. Usually we want some info from the item
1793 /// so it's easier to do that here then to wait until we would encounter
1794 /// normally in the visitor walk.
1795 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1796 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1798 hir::ItemKind::Static(..)
1799 | hir::ItemKind::Const(..)
1800 | hir::ItemKind::Fn(..)
1801 | hir::ItemKind::Mod(..)
1802 | hir::ItemKind::ForeignMod(..)
1803 | hir::ItemKind::GlobalAsm(..)
1804 | hir::ItemKind::ExternCrate(..)
1805 | hir::ItemKind::Use(..)
1806 | hir::ItemKind::TyAlias(..)
1807 | hir::ItemKind::OpaqueTy(..)
1808 | hir::ItemKind::TraitAlias(..) => {
1809 // no sub-item recording needed in these cases
1811 hir::ItemKind::Enum(..) => {
1812 let def = self.tcx.adt_def(def_id.to_def_id());
1813 self.encode_fields(def);
1815 for (i, variant) in def.variants.iter_enumerated() {
1816 self.encode_enum_variant_info(def, i);
1818 if let Some(_ctor_def_id) = variant.ctor_def_id {
1819 self.encode_enum_variant_ctor(def, i);
1823 hir::ItemKind::Struct(ref struct_def, _) => {
1824 let def = self.tcx.adt_def(def_id.to_def_id());
1825 self.encode_fields(def);
1827 // If the struct has a constructor, encode it.
1828 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1829 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1830 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1833 hir::ItemKind::Union(..) => {
1834 let def = self.tcx.adt_def(def_id.to_def_id());
1835 self.encode_fields(def);
1837 hir::ItemKind::Impl { .. } => {
1838 for &trait_item_def_id in
1839 self.tcx.associated_item_def_ids(def_id.to_def_id()).iter()
1841 self.encode_info_for_impl_item(trait_item_def_id);
1844 hir::ItemKind::Trait(..) => {
1845 for &item_def_id in self.tcx.associated_item_def_ids(def_id.to_def_id()).iter() {
1846 self.encode_info_for_trait_item(item_def_id);
1853 struct ImplVisitor<'tcx> {
1855 impls: FxHashMap<DefId, Vec<DefIndex>>,
1858 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1859 fn visit_item(&mut self, item: &hir::Item<'_>) {
1860 if let hir::ItemKind::Impl { .. } = item.kind {
1861 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1862 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id.to_def_id()) {
1863 self.impls.entry(trait_ref.def_id).or_default().push(impl_id.local_def_index);
1868 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1870 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1871 // handled in `visit_item` above
1875 /// Used to prefetch queries which will be needed later by metadata encoding.
1876 /// Only a subset of the queries are actually prefetched to keep this code smaller.
1877 struct PrefetchVisitor<'tcx> {
1879 mir_keys: &'tcx FxHashSet<LocalDefId>,
1882 impl<'tcx> PrefetchVisitor<'tcx> {
1883 fn prefetch_mir(&self, def_id: LocalDefId) {
1884 if self.mir_keys.contains(&def_id) {
1885 self.tcx.ensure().optimized_mir(def_id);
1886 self.tcx.ensure().promoted_mir(def_id);
1891 impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> {
1892 fn visit_item(&self, item: &hir::Item<'_>) {
1893 // This should be kept in sync with `encode_info_for_item`.
1896 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
1897 self.prefetch_mir(tcx.hir().local_def_id(item.hir_id))
1899 hir::ItemKind::Fn(ref sig, ..) => {
1900 let def_id = tcx.hir().local_def_id(item.hir_id);
1901 let generics = tcx.generics_of(def_id.to_def_id());
1902 let needs_inline = generics.requires_monomorphization(tcx)
1903 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1904 if needs_inline || sig.header.constness == hir::Constness::Const {
1905 self.prefetch_mir(def_id)
1912 fn visit_trait_item(&self, trait_item: &'v hir::TraitItem<'v>) {
1913 // This should be kept in sync with `encode_info_for_trait_item`.
1914 self.prefetch_mir(self.tcx.hir().local_def_id(trait_item.hir_id));
1917 fn visit_impl_item(&self, impl_item: &'v hir::ImplItem<'v>) {
1918 // This should be kept in sync with `encode_info_for_impl_item`.
1920 match impl_item.kind {
1921 hir::ImplItemKind::Const(..) => {
1922 self.prefetch_mir(tcx.hir().local_def_id(impl_item.hir_id))
1924 hir::ImplItemKind::Fn(ref sig, _) => {
1925 let def_id = tcx.hir().local_def_id(impl_item.hir_id);
1926 let generics = tcx.generics_of(def_id.to_def_id());
1927 let needs_inline = generics.requires_monomorphization(tcx)
1928 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1929 let is_const_fn = sig.header.constness == hir::Constness::Const;
1930 if needs_inline || is_const_fn {
1931 self.prefetch_mir(def_id)
1934 hir::ImplItemKind::TyAlias(..) => (),
1939 // NOTE(eddyb) The following comment was preserved for posterity, even
1940 // though it's no longer relevant as EBML (which uses nested & tagged
1941 // "documents") was replaced with a scheme that can't go out of bounds.
1943 // And here we run into yet another obscure archive bug: in which metadata
1944 // loaded from archives may have trailing garbage bytes. Awhile back one of
1945 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1946 // and opt) by having ebml generate an out-of-bounds panic when looking at
1949 // Upon investigation it turned out that the metadata file inside of an rlib
1950 // (and ar archive) was being corrupted. Some compilations would generate a
1951 // metadata file which would end in a few extra bytes, while other
1952 // compilations would not have these extra bytes appended to the end. These
1953 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1954 // being interpreted causing the out-of-bounds.
1956 // The root cause of why these extra bytes were appearing was never
1957 // discovered, and in the meantime the solution we're employing is to insert
1958 // the length of the metadata to the start of the metadata. Later on this
1959 // will allow us to slice the metadata to the precise length that we just
1960 // generated regardless of trailing bytes that end up in it.
1962 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1963 // Since encoding metadata is not in a query, and nothing is cached,
1964 // there's no need to do dep-graph tracking for any of it.
1965 tcx.dep_graph.assert_ignored();
1968 || encode_metadata_impl(tcx),
1970 if tcx.sess.threads() == 1 {
1973 // Prefetch some queries used by metadata encoding.
1974 // This is not necessary for correctness, but is only done for performance reasons.
1975 // It can be removed if it turns out to cause trouble or be detrimental to performance.
1978 if !tcx.sess.opts.output_types.should_codegen() {
1979 // We won't emit MIR, so don't prefetch it.
1982 tcx.hir().krate().par_visit_all_item_likes(&PrefetchVisitor {
1984 mir_keys: tcx.mir_keys(LOCAL_CRATE),
1987 || tcx.exported_symbols(LOCAL_CRATE),
1994 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
1995 let mut encoder = opaque::Encoder::new(vec![]);
1996 encoder.emit_raw_bytes(METADATA_HEADER);
1998 // Will be filled with the root position after encoding everything.
1999 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2001 let source_map_files = tcx.sess.source_map().files();
2002 let hygiene_ctxt = HygieneEncodeContext::default();
2004 let mut ecx = EncodeContext {
2007 tables: Default::default(),
2008 lazy_state: LazyState::NoNode,
2009 type_shorthands: Default::default(),
2010 predicate_shorthands: Default::default(),
2011 source_file_cache: (source_map_files[0].clone(), 0),
2012 interpret_allocs: Default::default(),
2013 interpret_allocs_inverse: Default::default(),
2014 required_source_files: Some(GrowableBitSet::with_capacity(source_map_files.len())),
2015 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2016 hygiene_ctxt: &hygiene_ctxt,
2018 drop(source_map_files);
2020 // Encode the rustc version string in a predictable location.
2021 rustc_version().encode(&mut ecx).unwrap();
2023 // Encode all the entries and extra information in the crate,
2024 // culminating in the `CrateRoot` which points to all of it.
2025 let root = ecx.encode_crate_root();
2027 let mut result = ecx.opaque.into_inner();
2029 // Encode the root position.
2030 let header = METADATA_HEADER.len();
2031 let pos = root.position.get();
2032 result[header + 0] = (pos >> 24) as u8;
2033 result[header + 1] = (pos >> 16) as u8;
2034 result[header + 2] = (pos >> 8) as u8;
2035 result[header + 3] = (pos >> 0) as u8;
2037 EncodedMetadata { raw_data: result }