1 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
5 use rustc_data_structures::fingerprint::{Fingerprint, FingerprintEncoder};
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
7 use rustc_data_structures::stable_hasher::StableHasher;
8 use rustc_data_structures::sync::{join, Lrc};
10 use rustc_hir::def::CtorKind;
11 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::definitions::DefPathData;
13 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
14 use rustc_hir::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor};
15 use rustc_hir::lang_items;
16 use rustc_hir::{AnonConst, GenericParamKind};
17 use rustc_index::bit_set::GrowableBitSet;
18 use rustc_index::vec::Idx;
19 use rustc_middle::hir::map::Map;
20 use rustc_middle::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLib};
21 use rustc_middle::middle::dependency_format::Linkage;
22 use rustc_middle::middle::exported_symbols::{
23 metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
25 use rustc_middle::mir::interpret;
26 use rustc_middle::traits::specialization_graph;
27 use rustc_middle::ty::codec::TyEncoder;
28 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
29 use rustc_serialize::{opaque, Encodable, Encoder};
30 use rustc_session::config::CrateType;
31 use rustc_span::hygiene::{ExpnDataEncodeMode, HygieneEncodeContext, MacroKind};
32 use rustc_span::symbol::{sym, Ident, Symbol};
33 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
34 use rustc_target::abi::VariantIdx;
36 use std::num::NonZeroUsize;
38 use tracing::{debug, trace};
40 pub(super) struct EncodeContext<'a, 'tcx> {
41 opaque: opaque::Encoder,
43 feat: &'tcx rustc_feature::Features,
45 tables: TableBuilders<'tcx>,
47 lazy_state: LazyState,
48 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
49 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
51 interpret_allocs: FxIndexSet<interpret::AllocId>,
53 // This is used to speed up Span encoding.
54 // The `usize` is an index into the `MonotonicVec`
55 // that stores the `SourceFile`
56 source_file_cache: (Lrc<SourceFile>, usize),
57 // The indices (into the `SourceMap`'s `MonotonicVec`)
58 // of all of the `SourceFiles` that we need to serialize.
59 // When we serialize a `Span`, we insert the index of its
60 // `SourceFile` into the `GrowableBitSet`.
62 // This needs to be a `GrowableBitSet` and not a
63 // regular `BitSet` because we may actually import new `SourceFiles`
64 // during metadata encoding, due to executing a query
65 // with a result containing a foreign `Span`.
66 required_source_files: Option<GrowableBitSet<usize>>,
68 hygiene_ctxt: &'a HygieneEncodeContext,
71 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
72 /// This is useful for skipping the encoding of things that aren't needed
73 /// for proc-macro crates.
74 macro_rules! empty_proc_macro {
76 if $self.is_proc_macro {
82 macro_rules! encoder_methods {
83 ($($name:ident($ty:ty);)*) => {
84 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
85 self.opaque.$name(value)
90 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
91 type Error = <opaque::Encoder as Encoder>::Error;
94 fn emit_unit(&mut self) -> Result<(), Self::Error> {
121 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
124 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
125 e.emit_lazy_distance(*self)
129 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
132 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
133 e.emit_usize(self.meta)?;
137 e.emit_lazy_distance(*self)
141 impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
142 for Lazy<Table<I, T>>
144 Option<T>: FixedSizeEncoding,
146 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
147 e.emit_usize(self.meta)?;
148 e.emit_lazy_distance(*self)
152 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
153 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
154 if *self != LOCAL_CRATE && s.is_proc_macro {
155 panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
157 s.emit_u32(self.as_u32())
161 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
162 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
163 s.emit_u32(self.as_u32())
167 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
168 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
169 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
173 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
174 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
175 rustc_span::hygiene::raw_encode_expn_id(
178 ExpnDataEncodeMode::Metadata,
184 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
185 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
186 if *self == rustc_span::DUMMY_SP {
187 return TAG_INVALID_SPAN.encode(s);
190 let span = self.data();
192 // The Span infrastructure should make sure that this invariant holds:
193 debug_assert!(span.lo <= span.hi);
195 if !s.source_file_cache.0.contains(span.lo) {
196 let source_map = s.tcx.sess.source_map();
197 let source_file_index = source_map.lookup_source_file_idx(span.lo);
198 s.source_file_cache =
199 (source_map.files()[source_file_index].clone(), source_file_index);
202 if !s.source_file_cache.0.contains(span.hi) {
203 // Unfortunately, macro expansion still sometimes generates Spans
204 // that malformed in this way.
205 return TAG_INVALID_SPAN.encode(s);
208 let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
209 // Record the fact that we need to encode the data for this `SourceFile`
210 source_files.insert(s.source_file_cache.1);
212 // There are two possible cases here:
213 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
214 // crate we are writing metadata for. When the metadata for *this* crate gets
215 // deserialized, the deserializer will need to know which crate it originally came
216 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
217 // be deserialized after the rest of the span data, which tells the deserializer
218 // which crate contains the source map information.
219 // 2. This span comes from our own crate. No special hamdling is needed - we just
220 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
221 // our own source map information.
223 // If we're a proc-macro crate, we always treat this as a local `Span`.
224 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
225 // if we're a proc-macro crate.
226 // This allows us to avoid loading the dependencies of proc-macro crates: all of
227 // the information we need to decode `Span`s is stored in the proc-macro crate.
228 let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
229 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
230 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
231 // are relative to the source map information for the 'foreign' crate whose CrateNum
232 // we write into the metadata. This allows `imported_source_files` to binary
233 // search through the 'foreign' crate's source map information, using the
234 // deserialized 'lo' and 'hi' values directly.
236 // All of this logic ensures that the final result of deserialization is a 'normal'
237 // Span that can be used without any additional trouble.
238 let external_start_pos = {
239 // Introduce a new scope so that we drop the 'lock()' temporary
240 match &*s.source_file_cache.0.external_src.lock() {
241 ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
242 src => panic!("Unexpected external source {:?}", src),
245 let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
246 let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
248 (TAG_VALID_SPAN_FOREIGN, lo, hi)
250 (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
256 // Encode length which is usually less than span.hi and profits more
257 // from the variable-length integer encoding that we use.
261 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
262 // since we don't load proc-macro dependencies during serialization.
263 // This means that any hygiene information from macros used *within*
264 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
265 // definition) will be lost.
267 // This can show up in two ways:
269 // 1. Any hygiene information associated with identifier of
270 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
271 // Since proc-macros can only be invoked from a different crate,
272 // real code should never need to care about this.
274 // 2. Using `Span::def_site` or `Span::mixed_site` will not
275 // include any hygiene information associated with the definition
276 // site. This means that a proc-macro cannot emit a `$crate`
277 // identifier which resolves to one of its dependencies,
278 // which also should never come up in practice.
280 // Additionally, this affects `Span::parent`, and any other
281 // span inspection APIs that would otherwise allow traversing
282 // the `SyntaxContexts` associated with a span.
284 // None of these user-visible effects should result in any
285 // cross-crate inconsistencies (getting one behavior in the same
286 // crate, and a different behavior in another crate) due to the
287 // limited surface that proc-macros can expose.
289 // IMPORTANT: If this is ever changed, be sure to update
290 // `rustc_span::hygiene::raw_encode_expn_id` to handle
291 // encoding `ExpnData` for proc-macro crates.
293 SyntaxContext::root().encode(s)?;
295 span.ctxt.encode(s)?;
298 if tag == TAG_VALID_SPAN_FOREIGN {
299 // This needs to be two lines to avoid holding the `s.source_file_cache`
300 // while calling `cnum.encode(s)`
301 let cnum = s.source_file_cache.0.cnum;
309 impl<'a, 'tcx> FingerprintEncoder for EncodeContext<'a, 'tcx> {
310 fn encode_fingerprint(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
311 f.encode_opaque(&mut self.opaque)
315 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
316 const CLEAR_CROSS_CRATE: bool = true;
318 fn position(&self) -> usize {
319 self.opaque.position()
322 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
323 &mut self.type_shorthands
326 fn predicate_shorthands(&mut self) -> &mut FxHashMap<rustc_middle::ty::Predicate<'tcx>, usize> {
327 &mut self.predicate_shorthands
332 alloc_id: &rustc_middle::mir::interpret::AllocId,
333 ) -> Result<(), Self::Error> {
334 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
340 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] {
341 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
346 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
347 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
352 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
353 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
354 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
357 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
358 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
359 self.encode(ecx).unwrap()
363 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
364 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
365 self.encode(ecx).unwrap()
369 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
372 I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
374 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
375 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
379 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
380 // normally need extra variables to avoid errors about multiple mutable borrows.
381 macro_rules! record {
382 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
385 let lazy = $self.lazy(value);
386 $self.$tables.$table.set($def_id.index, lazy);
391 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
392 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
395 ) -> Result<(), <Self as Encoder>::Error> {
396 let min_end = lazy.position.get() + T::min_size(lazy.meta);
397 let distance = match self.lazy_state {
398 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
399 LazyState::NodeStart(start) => {
400 let start = start.get();
401 assert!(min_end <= start);
404 LazyState::Previous(last_min_end) => {
406 last_min_end <= lazy.position,
407 "make sure that the calls to `lazy*` \
408 are in the same order as the metadata fields",
410 lazy.position.get() - last_min_end.get()
413 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
414 self.emit_usize(distance)
417 fn lazy<T: ?Sized + LazyMeta>(
419 value: impl EncodeContentsForLazy<'a, 'tcx, T>,
421 let pos = NonZeroUsize::new(self.position()).unwrap();
423 assert_eq!(self.lazy_state, LazyState::NoNode);
424 self.lazy_state = LazyState::NodeStart(pos);
425 let meta = value.encode_contents_for_lazy(self);
426 self.lazy_state = LazyState::NoNode;
428 assert!(pos.get() + <T>::min_size(meta) <= self.position());
430 Lazy::from_position_and_meta(pos, meta)
433 fn encode_info_for_items(&mut self) {
434 let krate = self.tcx.hir().krate();
435 self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.item.module, &krate.item.attrs);
437 // Proc-macro crates only export proc-macro items, which are looked
438 // up using `proc_macro_data`
439 if self.is_proc_macro {
443 krate.visit_all_item_likes(&mut self.as_deep_visitor());
444 for macro_def in krate.exported_macros {
445 self.visit_macro_def(macro_def);
449 fn encode_def_path_table(&mut self) {
450 let table = self.tcx.hir().definitions().def_path_table();
451 if self.is_proc_macro {
452 for def_index in std::iter::once(CRATE_DEF_INDEX)
453 .chain(self.tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index))
455 let def_key = self.lazy(table.def_key(def_index));
456 let def_path_hash = self.lazy(table.def_path_hash(def_index));
457 self.tables.def_keys.set(def_index, def_key);
458 self.tables.def_path_hashes.set(def_index, def_path_hash);
461 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
462 let def_key = self.lazy(def_key);
463 let def_path_hash = self.lazy(def_path_hash);
464 self.tables.def_keys.set(def_index, def_key);
465 self.tables.def_path_hashes.set(def_index, def_path_hash);
470 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
471 let source_map = self.tcx.sess.source_map();
472 let all_source_files = source_map.files();
474 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
475 // By replacing the `Option` with `None`, we ensure that we can't
476 // accidentally serialize any more `Span`s after the source map encoding
478 let required_source_files = self.required_source_files.take().unwrap();
480 let adapted = all_source_files
483 .filter(|(idx, source_file)| {
484 // Only serialize `SourceFile`s that were used
485 // during the encoding of a `Span`
486 required_source_files.contains(*idx) &&
487 // Don't serialize imported `SourceFile`s, unless
488 // we're in a proc-macro crate.
489 (!source_file.is_imported() || self.is_proc_macro)
491 .map(|(_, source_file)| {
492 let mut adapted = match source_file.name {
493 // This path of this SourceFile has been modified by
494 // path-remapping, so we use it verbatim (and avoid
495 // cloning the whole map in the process).
496 _ if source_file.name_was_remapped => source_file.clone(),
498 // Otherwise expand all paths to absolute paths because
499 // any relative paths are potentially relative to a
501 FileName::Real(ref name) => {
502 let name = name.stable_name();
503 let mut adapted = (**source_file).clone();
504 adapted.name = Path::new(&working_dir).join(name).into();
505 adapted.name_hash = {
506 let mut hasher: StableHasher = StableHasher::new();
507 adapted.name.hash(&mut hasher);
508 hasher.finish::<u128>()
513 // expanded code, not from a file
514 _ => source_file.clone(),
517 // We're serializing this `SourceFile` into our crate metadata,
518 // so mark it as coming from this crate.
519 // This also ensures that we don't try to deserialize the
520 // `CrateNum` for a proc-macro dependency - since proc macro
521 // dependencies aren't loaded when we deserialize a proc-macro,
522 // trying to remap the `CrateNum` would fail.
523 if self.is_proc_macro {
524 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
528 .collect::<Vec<_>>();
530 self.lazy(adapted.iter().map(|rc| &**rc))
533 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
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 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.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[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)
605 // Encode the proc macro data. This affects 'tables',
606 // so we need to do this before we encode the tables
608 let proc_macro_data = self.encode_proc_macros();
609 let proc_macro_data_bytes = self.position() - i;
612 let tables = self.tables.encode(&mut self.opaque);
613 let tables_bytes = self.position() - i;
615 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
616 // this as late as possible to give the prefetching as much time as possible to complete.
618 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
619 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
620 let exported_symbols_bytes = self.position() - i;
622 // Encode the hygiene data,
623 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
624 // of encoding other items (e.g. `optimized_mir`) may cause us to load
625 // data from the incremental cache. If this causes us to deserialize a `Span`,
626 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
627 // Therefore, we need to encode the hygiene data last to ensure that we encode
628 // any `SyntaxContext`s that might be used.
630 let (syntax_contexts, expn_data) = self.encode_hygiene();
631 let hygiene_bytes = self.position() - i;
633 // Encode source_map. This needs to be done last,
634 // since encoding `Span`s tells us which `SourceFiles` we actually
637 let source_map = self.encode_source_map();
638 let source_map_bytes = self.position() - i;
640 let attrs = tcx.hir().krate_attrs();
641 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
643 let root = self.lazy(CrateRoot {
644 name: tcx.crate_name(LOCAL_CRATE),
645 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
646 triple: tcx.sess.opts.target_triple.clone(),
647 hash: tcx.crate_hash(LOCAL_CRATE),
648 disambiguator: tcx.sess.local_crate_disambiguator(),
649 panic_strategy: tcx.sess.panic_strategy(),
650 edition: tcx.sess.edition(),
651 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
652 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
653 has_default_lib_allocator,
654 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
656 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
657 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
658 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
659 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
660 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
661 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
662 symbol_mangling_version: tcx.sess.opts.debugging_opts.get_symbol_mangling_version(),
665 dylib_dependency_formats,
675 interpret_alloc_index,
681 let total_bytes = self.position();
683 if tcx.sess.meta_stats() {
684 let mut zero_bytes = 0;
685 for e in self.opaque.data.iter() {
691 println!("metadata stats:");
692 println!(" dep bytes: {}", dep_bytes);
693 println!(" lib feature bytes: {}", lib_feature_bytes);
694 println!(" lang item bytes: {}", lang_item_bytes);
695 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
696 println!(" native bytes: {}", native_lib_bytes);
697 println!(" source_map bytes: {}", source_map_bytes);
698 println!(" impl bytes: {}", impl_bytes);
699 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
700 println!(" def-path table bytes: {}", def_path_table_bytes);
701 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
702 println!(" item bytes: {}", item_bytes);
703 println!(" table bytes: {}", tables_bytes);
704 println!(" hygiene bytes: {}", hygiene_bytes);
705 println!(" zero bytes: {}", zero_bytes);
706 println!(" total bytes: {}", total_bytes);
713 impl EncodeContext<'a, 'tcx> {
714 fn encode_variances_of(&mut self, def_id: DefId) {
715 debug!("EncodeContext::encode_variances_of({:?})", def_id);
716 record!(self.tables.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
719 fn encode_item_type(&mut self, def_id: DefId) {
720 debug!("EncodeContext::encode_item_type({:?})", def_id);
721 record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
724 fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
726 let variant = &def.variants[index];
727 let def_id = variant.def_id;
728 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
730 let data = VariantData {
731 ctor_kind: variant.ctor_kind,
732 discr: variant.discr,
733 ctor: variant.ctor_def_id.map(|did| did.index),
734 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
737 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
738 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
739 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
740 record!(self.tables.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
741 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
742 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
743 assert!(f.did.is_local());
746 self.encode_ident_span(def_id, variant.ident);
747 self.encode_stability(def_id);
748 self.encode_deprecation(def_id);
749 self.encode_item_type(def_id);
750 if variant.ctor_kind == CtorKind::Fn {
751 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
752 if let Some(ctor_def_id) = variant.ctor_def_id {
753 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
755 // FIXME(eddyb) is this ever used?
756 self.encode_variances_of(def_id);
758 self.encode_generics(def_id);
759 self.encode_explicit_predicates(def_id);
760 self.encode_inferred_outlives(def_id);
763 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
765 let variant = &def.variants[index];
766 let def_id = variant.ctor_def_id.unwrap();
767 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
769 // FIXME(eddyb) encode only the `CtorKind` for constructors.
770 let data = VariantData {
771 ctor_kind: variant.ctor_kind,
772 discr: variant.discr,
773 ctor: Some(def_id.index),
774 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
777 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
778 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
779 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
780 self.encode_stability(def_id);
781 self.encode_deprecation(def_id);
782 self.encode_item_type(def_id);
783 if variant.ctor_kind == CtorKind::Fn {
784 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
785 self.encode_variances_of(def_id);
787 self.encode_generics(def_id);
788 self.encode_explicit_predicates(def_id);
789 self.encode_inferred_outlives(def_id);
790 self.encode_optimized_mir(def_id.expect_local());
791 self.encode_promoted_mir(def_id.expect_local());
794 fn encode_info_for_mod(&mut self, id: hir::HirId, md: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
796 let local_def_id = tcx.hir().local_def_id(id);
797 let def_id = local_def_id.to_def_id();
798 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
800 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
801 // only ever get called for the crate root. We still want to encode
802 // the crate root for consistency with other crates (some of the resolver
803 // code uses it). However, we skip encoding anything relating to child
804 // items - we encode information about proc-macros later on.
805 let reexports = if !self.is_proc_macro {
806 match tcx.module_exports(local_def_id) {
808 let hir = self.tcx.hir();
812 .map(|export| export.map_id(|id| hir.local_def_id_to_hir_id(id))),
823 expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
826 record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
827 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
828 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
829 record!(self.tables.attributes[def_id] <- attrs);
830 if self.is_proc_macro {
831 record!(self.tables.children[def_id] <- &[]);
833 record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
834 tcx.hir().local_def_id(item_id.id).local_def_index
837 self.encode_stability(def_id);
838 self.encode_deprecation(def_id);
843 adt_def: &ty::AdtDef,
844 variant_index: VariantIdx,
848 let variant = &adt_def.variants[variant_index];
849 let field = &variant.fields[field_index];
851 let def_id = field.did;
852 debug!("EncodeContext::encode_field({:?})", def_id);
854 let variant_id = tcx.hir().local_def_id_to_hir_id(variant.def_id.expect_local());
855 let variant_data = tcx.hir().expect_variant_data(variant_id);
857 record!(self.tables.kind[def_id] <- EntryKind::Field);
858 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
859 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
860 record!(self.tables.attributes[def_id] <- variant_data.fields()[field_index].attrs);
861 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
862 self.encode_ident_span(def_id, field.ident);
863 self.encode_stability(def_id);
864 self.encode_deprecation(def_id);
865 self.encode_item_type(def_id);
866 self.encode_generics(def_id);
867 self.encode_explicit_predicates(def_id);
868 self.encode_inferred_outlives(def_id);
871 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
872 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
874 let variant = adt_def.non_enum_variant();
876 let data = VariantData {
877 ctor_kind: variant.ctor_kind,
878 discr: variant.discr,
879 ctor: Some(def_id.index),
880 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
883 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
884 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
885 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
886 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
887 self.encode_stability(def_id);
888 self.encode_deprecation(def_id);
889 self.encode_item_type(def_id);
890 if variant.ctor_kind == CtorKind::Fn {
891 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
892 self.encode_variances_of(def_id);
894 self.encode_generics(def_id);
895 self.encode_explicit_predicates(def_id);
896 self.encode_inferred_outlives(def_id);
897 self.encode_optimized_mir(def_id.expect_local());
898 self.encode_promoted_mir(def_id.expect_local());
901 fn encode_generics(&mut self, def_id: DefId) {
902 debug!("EncodeContext::encode_generics({:?})", def_id);
903 record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
906 fn encode_explicit_predicates(&mut self, def_id: DefId) {
907 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
908 record!(self.tables.explicit_predicates[def_id] <-
909 self.tcx.explicit_predicates_of(def_id));
912 fn encode_inferred_outlives(&mut self, def_id: DefId) {
913 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
914 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
915 if !inferred_outlives.is_empty() {
916 record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
920 fn encode_super_predicates(&mut self, def_id: DefId) {
921 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
922 record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
925 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
926 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
927 let bounds = self.tcx.explicit_item_bounds(def_id);
928 if !bounds.is_empty() {
929 record!(self.tables.explicit_item_bounds[def_id] <- bounds);
933 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
934 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
937 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
938 let ast_item = tcx.hir().expect_trait_item(hir_id);
939 let trait_item = tcx.associated_item(def_id);
941 let container = match trait_item.defaultness {
942 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
943 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
944 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
947 record!(self.tables.kind[def_id] <- match trait_item.kind {
948 ty::AssocKind::Const => {
949 let rendered = rustc_hir_pretty::to_string(
950 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
951 |s| s.print_trait_item(ast_item)
953 let rendered_const = self.lazy(RenderedConst(rendered));
955 EntryKind::AssocConst(
961 ty::AssocKind::Fn => {
962 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
963 let param_names = match *m {
964 hir::TraitFn::Required(ref names) => {
965 self.encode_fn_param_names(names)
967 hir::TraitFn::Provided(body) => {
968 self.encode_fn_param_names_for_body(body)
972 asyncness: m_sig.header.asyncness,
973 constness: hir::Constness::NotConst,
979 EntryKind::AssocFn(self.lazy(AssocFnData {
982 has_self: trait_item.fn_has_self_parameter,
985 ty::AssocKind::Type => {
986 self.encode_explicit_item_bounds(def_id);
987 EntryKind::AssocType(container)
990 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
991 record!(self.tables.span[def_id] <- ast_item.span);
992 record!(self.tables.attributes[def_id] <- ast_item.attrs);
993 self.encode_ident_span(def_id, ast_item.ident);
994 self.encode_stability(def_id);
995 self.encode_const_stability(def_id);
996 self.encode_deprecation(def_id);
997 match trait_item.kind {
998 ty::AssocKind::Const | ty::AssocKind::Fn => {
999 self.encode_item_type(def_id);
1001 ty::AssocKind::Type => {
1002 if trait_item.defaultness.has_value() {
1003 self.encode_item_type(def_id);
1007 if trait_item.kind == ty::AssocKind::Fn {
1008 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1009 self.encode_variances_of(def_id);
1011 self.encode_generics(def_id);
1012 self.encode_explicit_predicates(def_id);
1013 self.encode_inferred_outlives(def_id);
1015 // This should be kept in sync with `PrefetchVisitor.visit_trait_item`.
1016 self.encode_optimized_mir(def_id.expect_local());
1017 self.encode_promoted_mir(def_id.expect_local());
1020 fn metadata_output_only(&self) -> bool {
1021 // MIR optimisation can be skipped when we're just interested in the metadata.
1022 !self.tcx.sess.opts.output_types.should_codegen()
1025 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1026 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1029 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1030 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1031 let impl_item = self.tcx.associated_item(def_id);
1033 let container = match impl_item.defaultness {
1034 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1035 hir::Defaultness::Final => AssocContainer::ImplFinal,
1036 hir::Defaultness::Default { has_value: false } => {
1037 span_bug!(ast_item.span, "impl items always have values (currently)")
1041 record!(self.tables.kind[def_id] <- match impl_item.kind {
1042 ty::AssocKind::Const => {
1043 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1044 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1046 EntryKind::AssocConst(
1049 self.encode_rendered_const_for_body(body_id))
1054 ty::AssocKind::Fn => {
1055 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1057 asyncness: sig.header.asyncness,
1058 constness: sig.header.constness,
1059 param_names: self.encode_fn_param_names_for_body(body),
1064 EntryKind::AssocFn(self.lazy(AssocFnData {
1067 has_self: impl_item.fn_has_self_parameter,
1070 ty::AssocKind::Type => EntryKind::AssocType(container)
1072 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1073 record!(self.tables.span[def_id] <- ast_item.span);
1074 record!(self.tables.attributes[def_id] <- ast_item.attrs);
1075 self.encode_ident_span(def_id, impl_item.ident);
1076 self.encode_stability(def_id);
1077 self.encode_const_stability(def_id);
1078 self.encode_deprecation(def_id);
1079 self.encode_item_type(def_id);
1080 if impl_item.kind == ty::AssocKind::Fn {
1081 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1082 self.encode_variances_of(def_id);
1084 self.encode_generics(def_id);
1085 self.encode_explicit_predicates(def_id);
1086 self.encode_inferred_outlives(def_id);
1088 // The following part should be kept in sync with `PrefetchVisitor.visit_impl_item`.
1090 let mir = match ast_item.kind {
1091 hir::ImplItemKind::Const(..) => true,
1092 hir::ImplItemKind::Fn(ref sig, _) => {
1093 let generics = self.tcx.generics_of(def_id);
1094 let needs_inline = (generics.requires_monomorphization(self.tcx)
1095 || tcx.codegen_fn_attrs(def_id).requests_inline())
1096 && !self.metadata_output_only();
1097 let is_const_fn = sig.header.constness == hir::Constness::Const;
1098 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1099 needs_inline || is_const_fn || always_encode_mir
1101 hir::ImplItemKind::TyAlias(..) => false,
1104 self.encode_optimized_mir(def_id.expect_local());
1105 self.encode_promoted_mir(def_id.expect_local());
1109 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1110 self.lazy(self.tcx.hir().body_param_names(body_id))
1113 fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1114 self.lazy(param_names.iter())
1117 fn encode_optimized_mir(&mut self, def_id: LocalDefId) {
1118 debug!("EntryBuilder::encode_mir({:?})", def_id);
1119 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1121 let unused = self.tcx.unused_generic_params(def_id);
1122 if !unused.is_empty() {
1123 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1126 let abstract_const = self.tcx.mir_abstract_const(def_id);
1127 if let Ok(Some(abstract_const)) = abstract_const {
1128 record!(self.tables.mir_abstract_consts[def_id.to_def_id()] <- abstract_const);
1132 fn encode_promoted_mir(&mut self, def_id: LocalDefId) {
1133 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1134 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1135 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1139 // Encodes the inherent implementations of a structure, enumeration, or trait.
1140 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1141 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1142 let implementations = self.tcx.inherent_impls(def_id);
1143 if !implementations.is_empty() {
1144 record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1145 assert!(def_id.is_local());
1151 fn encode_stability(&mut self, def_id: DefId) {
1152 debug!("EncodeContext::encode_stability({:?})", def_id);
1154 // The query lookup can take a measurable amount of time in crates with many items. Check if
1155 // the stability attributes are even enabled before using their queries.
1156 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1157 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1158 record!(self.tables.stability[def_id] <- stab)
1163 fn encode_const_stability(&mut self, def_id: DefId) {
1164 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1166 // The query lookup can take a measurable amount of time in crates with many items. Check if
1167 // the stability attributes are even enabled before using their queries.
1168 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1169 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1170 record!(self.tables.const_stability[def_id] <- stab)
1175 fn encode_deprecation(&mut self, def_id: DefId) {
1176 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1177 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1178 record!(self.tables.deprecation[def_id] <- depr);
1182 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1183 let hir = self.tcx.hir();
1184 let body = hir.body(body_id);
1185 let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1186 s.print_expr(&body.value)
1188 let rendered_const = &RenderedConst(rendered);
1189 self.lazy(rendered_const)
1192 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1195 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1197 self.encode_ident_span(def_id, item.ident);
1199 record!(self.tables.kind[def_id] <- match item.kind {
1200 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1201 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1202 hir::ItemKind::Const(_, body_id) => {
1203 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1206 self.encode_rendered_const_for_body(body_id)
1209 hir::ItemKind::Fn(ref sig, .., body) => {
1211 asyncness: sig.header.asyncness,
1212 constness: sig.header.constness,
1213 param_names: self.encode_fn_param_names_for_body(body),
1216 EntryKind::Fn(self.lazy(data))
1218 hir::ItemKind::Mod(ref m) => {
1219 return self.encode_info_for_mod(item.hir_id, m, &item.attrs);
1221 hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1222 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1223 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1224 hir::ItemKind::OpaqueTy(..) => {
1225 self.encode_explicit_item_bounds(def_id);
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] <- self.tcx.visibility(def_id));
1311 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1312 record!(self.tables.attributes[def_id] <- item.attrs);
1313 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
1314 // FIXME(eddyb) there should be a nicer way to do this.
1316 hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <-
1319 .map(|foreign_item| tcx.hir().local_def_id(
1320 foreign_item.id.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();
1413 let is_const_fn = sig.header.constness == hir::Constness::Const;
1414 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1415 needs_inline || is_const_fn || always_encode_mir
1420 self.encode_optimized_mir(def_id.expect_local());
1421 self.encode_promoted_mir(def_id.expect_local());
1425 /// Serialize the text of exported macros
1426 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1427 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id();
1428 record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1429 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1430 record!(self.tables.span[def_id] <- macro_def.span);
1431 record!(self.tables.attributes[def_id] <- macro_def.attrs);
1432 self.encode_ident_span(def_id, macro_def.ident);
1433 self.encode_stability(def_id);
1434 self.encode_deprecation(def_id);
1437 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1438 record!(self.tables.kind[def_id] <- kind);
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().local_def_id_to_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.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().local_def_id_to_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.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1483 self.encode_item_type(def_id.to_def_id());
1484 self.encode_generics(def_id.to_def_id());
1485 self.encode_explicit_predicates(def_id.to_def_id());
1486 self.encode_inferred_outlives(def_id.to_def_id());
1487 self.encode_optimized_mir(def_id);
1488 self.encode_promoted_mir(def_id);
1491 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1492 empty_proc_macro!(self);
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 empty_proc_macro!(self);
1499 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1500 self.lazy(foreign_modules.iter().map(|(_, m)| m).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<ProcMacroData> {
1523 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1526 let hir = tcx.hir();
1528 let proc_macro_decls_static = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap().index;
1529 let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1530 let macros = self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.local_def_index));
1532 // Normally, this information is encoded when we walk the items
1533 // defined in this crate. However, we skip doing that for proc-macro crates,
1534 // so we manually encode just the information that we need
1535 for proc_macro in &hir.krate().proc_macros {
1536 let id = proc_macro.owner.local_def_index;
1537 let mut name = hir.name(*proc_macro);
1538 let span = hir.span(*proc_macro);
1539 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1540 // so downstream crates need access to them.
1541 let attrs = hir.attrs(*proc_macro);
1542 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1544 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1546 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1547 // This unwrap chain should have been checked by the proc-macro harness.
1548 name = attr.meta_item_list().unwrap()[0]
1556 bug!("Unknown proc-macro type for item {:?}", id);
1559 let mut def_key = self.tcx.hir().def_key(proc_macro.owner);
1560 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1562 let def_id = DefId::local(id);
1563 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1564 record!(self.tables.attributes[def_id] <- attrs);
1565 record!(self.tables.def_keys[def_id] <- def_key);
1566 record!(self.tables.ident_span[def_id] <- span);
1567 record!(self.tables.span[def_id] <- span);
1568 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1569 if let Some(stability) = stability {
1570 record!(self.tables.stability[def_id] <- stability);
1574 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1580 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1581 empty_proc_macro!(self);
1582 let crates = self.tcx.crates();
1584 let mut deps = crates
1587 let dep = CrateDep {
1588 name: self.tcx.original_crate_name(cnum),
1589 hash: self.tcx.crate_hash(cnum),
1590 host_hash: self.tcx.crate_host_hash(cnum),
1591 kind: self.tcx.dep_kind(cnum),
1592 extra_filename: self.tcx.extra_filename(cnum),
1596 .collect::<Vec<_>>();
1598 deps.sort_by_key(|&(cnum, _)| cnum);
1601 // Sanity-check the crate numbers
1602 let mut expected_cnum = 1;
1603 for &(n, _) in &deps {
1604 assert_eq!(n, CrateNum::new(expected_cnum));
1609 // We're just going to write a list of crate 'name-hash-version's, with
1610 // the assumption that they are numbered 1 to n.
1611 // FIXME (#2166): This is not nearly enough to support correct versioning
1612 // but is enough to get transitive crate dependencies working.
1613 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1616 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1617 empty_proc_macro!(self);
1619 let lib_features = tcx.lib_features();
1620 self.lazy(lib_features.to_vec())
1623 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1624 empty_proc_macro!(self);
1626 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1627 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1630 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1631 empty_proc_macro!(self);
1633 let lang_items = tcx.lang_items();
1634 let lang_items = lang_items.items().iter();
1635 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1636 if let Some(def_id) = opt_def_id {
1637 if def_id.is_local() {
1638 return Some((def_id.index, i));
1645 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1646 empty_proc_macro!(self);
1648 self.lazy(&tcx.lang_items().missing)
1651 /// Encodes an index, mapping each trait to its (local) implementations.
1652 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1653 empty_proc_macro!(self);
1654 debug!("EncodeContext::encode_impls()");
1656 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1657 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1659 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1661 // Bring everything into deterministic order for hashing
1662 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1664 let all_impls: Vec<_> = all_impls
1666 .map(|(trait_def_id, mut impls)| {
1667 // Bring everything into deterministic order for hashing
1668 impls.sort_by_cached_key(|&(index, _)| {
1669 tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1673 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1674 impls: self.lazy(&impls),
1679 self.lazy(&all_impls)
1682 // Encodes all symbols exported from this crate into the metadata.
1684 // This pass is seeded off the reachability list calculated in the
1685 // middle::reachable module but filters out items that either don't have a
1686 // symbol associated with them (they weren't translated) or if they're an FFI
1687 // definition (as that's not defined in this crate).
1688 fn encode_exported_symbols(
1690 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1691 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1692 empty_proc_macro!(self);
1693 // The metadata symbol name is special. It should not show up in
1694 // downstream crates.
1695 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1700 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1701 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1708 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1709 empty_proc_macro!(self);
1710 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1711 for (ty, arr) in formats.iter() {
1712 if *ty != CrateType::Dylib {
1715 return self.lazy(arr.iter().map(|slot| match *slot {
1716 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1718 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1719 Linkage::Static => Some(LinkagePreference::RequireStatic),
1725 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1728 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1730 record!(self.tables.kind[def_id] <- match nitem.kind {
1731 hir::ForeignItemKind::Fn(_, ref names, _) => {
1733 asyncness: hir::IsAsync::NotAsync,
1734 constness: if self.tcx.is_const_fn_raw(def_id) {
1735 hir::Constness::Const
1737 hir::Constness::NotConst
1739 param_names: self.encode_fn_param_names(names),
1741 EntryKind::ForeignFn(self.lazy(data))
1743 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1744 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1745 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1747 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1748 record!(self.tables.span[def_id] <- nitem.span);
1749 record!(self.tables.attributes[def_id] <- nitem.attrs);
1750 self.encode_ident_span(def_id, nitem.ident);
1751 self.encode_stability(def_id);
1752 self.encode_const_stability(def_id);
1753 self.encode_deprecation(def_id);
1754 self.encode_item_type(def_id);
1755 self.encode_inherent_implementations(def_id);
1756 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1757 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1758 self.encode_variances_of(def_id);
1760 self.encode_generics(def_id);
1761 self.encode_explicit_predicates(def_id);
1762 self.encode_inferred_outlives(def_id);
1766 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1767 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1768 type Map = Map<'tcx>;
1770 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1771 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1773 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1774 intravisit::walk_expr(self, ex);
1775 self.encode_info_for_expr(ex);
1777 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1778 intravisit::walk_anon_const(self, c);
1779 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1780 self.encode_info_for_anon_const(def_id);
1782 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1783 intravisit::walk_item(self, item);
1784 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1786 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1787 _ => self.encode_info_for_item(def_id.to_def_id(), item),
1789 self.encode_addl_info_for_item(item);
1791 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1792 intravisit::walk_foreign_item(self, ni);
1793 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1794 self.encode_info_for_foreign_item(def_id.to_def_id(), ni);
1796 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1797 intravisit::walk_generics(self, generics);
1798 self.encode_info_for_generics(generics);
1800 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1801 self.encode_info_for_macro_def(macro_def);
1805 impl EncodeContext<'a, 'tcx> {
1806 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1807 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1808 for (field_index, _field) in variant.fields.iter().enumerate() {
1809 self.encode_field(adt_def, variant_index, field_index);
1814 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1815 for param in generics.params {
1816 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1818 GenericParamKind::Lifetime { .. } => continue,
1819 GenericParamKind::Type { ref default, .. } => {
1820 self.encode_info_for_generic_param(
1822 EntryKind::TypeParam,
1825 if default.is_some() {
1826 self.encode_stability(def_id.to_def_id());
1829 GenericParamKind::Const { .. } => {
1830 self.encode_info_for_generic_param(
1832 EntryKind::ConstParam,
1835 // FIXME(const_generics_defaults)
1841 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1842 if let hir::ExprKind::Closure(..) = expr.kind {
1843 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1844 self.encode_info_for_closure(def_id);
1848 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1849 record!(self.tables.ident_span[def_id] <- ident.span);
1852 /// In some cases, along with the item itself, we also
1853 /// encode some sub-items. Usually we want some info from the item
1854 /// so it's easier to do that here then to wait until we would encounter
1855 /// normally in the visitor walk.
1856 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1857 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1859 hir::ItemKind::Static(..)
1860 | hir::ItemKind::Const(..)
1861 | hir::ItemKind::Fn(..)
1862 | hir::ItemKind::Mod(..)
1863 | hir::ItemKind::ForeignMod { .. }
1864 | hir::ItemKind::GlobalAsm(..)
1865 | hir::ItemKind::ExternCrate(..)
1866 | hir::ItemKind::Use(..)
1867 | hir::ItemKind::TyAlias(..)
1868 | hir::ItemKind::OpaqueTy(..)
1869 | hir::ItemKind::TraitAlias(..) => {
1870 // no sub-item recording needed in these cases
1872 hir::ItemKind::Enum(..) => {
1873 let def = self.tcx.adt_def(def_id.to_def_id());
1874 self.encode_fields(def);
1876 for (i, variant) in def.variants.iter_enumerated() {
1877 self.encode_enum_variant_info(def, i);
1879 if let Some(_ctor_def_id) = variant.ctor_def_id {
1880 self.encode_enum_variant_ctor(def, i);
1884 hir::ItemKind::Struct(ref struct_def, _) => {
1885 let def = self.tcx.adt_def(def_id.to_def_id());
1886 self.encode_fields(def);
1888 // If the struct has a constructor, encode it.
1889 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1890 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1891 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1894 hir::ItemKind::Union(..) => {
1895 let def = self.tcx.adt_def(def_id.to_def_id());
1896 self.encode_fields(def);
1898 hir::ItemKind::Impl { .. } => {
1899 for &trait_item_def_id in
1900 self.tcx.associated_item_def_ids(def_id.to_def_id()).iter()
1902 self.encode_info_for_impl_item(trait_item_def_id);
1905 hir::ItemKind::Trait(..) => {
1906 for &item_def_id in self.tcx.associated_item_def_ids(def_id.to_def_id()).iter() {
1907 self.encode_info_for_trait_item(item_def_id);
1914 struct ImplVisitor<'tcx> {
1916 impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
1919 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1920 fn visit_item(&mut self, item: &hir::Item<'_>) {
1921 if let hir::ItemKind::Impl { .. } = item.kind {
1922 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1923 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id.to_def_id()) {
1924 let simplified_self_ty =
1925 ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
1928 .entry(trait_ref.def_id)
1930 .push((impl_id.local_def_index, simplified_self_ty));
1935 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1937 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1938 // handled in `visit_item` above
1941 fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
1944 /// Used to prefetch queries which will be needed later by metadata encoding.
1945 /// Only a subset of the queries are actually prefetched to keep this code smaller.
1946 struct PrefetchVisitor<'tcx> {
1948 mir_keys: &'tcx FxHashSet<LocalDefId>,
1951 impl<'tcx> PrefetchVisitor<'tcx> {
1952 fn prefetch_mir(&self, def_id: LocalDefId) {
1953 if self.mir_keys.contains(&def_id) {
1954 self.tcx.ensure().optimized_mir(def_id);
1955 self.tcx.ensure().promoted_mir(def_id);
1960 impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> {
1961 fn visit_item(&self, item: &hir::Item<'_>) {
1962 // This should be kept in sync with `encode_info_for_item`.
1965 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
1966 self.prefetch_mir(tcx.hir().local_def_id(item.hir_id))
1968 hir::ItemKind::Fn(ref sig, ..) => {
1969 let def_id = tcx.hir().local_def_id(item.hir_id);
1970 let generics = tcx.generics_of(def_id.to_def_id());
1971 let needs_inline = generics.requires_monomorphization(tcx)
1972 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1973 if needs_inline || sig.header.constness == hir::Constness::Const {
1974 self.prefetch_mir(def_id)
1981 fn visit_trait_item(&self, trait_item: &'v hir::TraitItem<'v>) {
1982 // This should be kept in sync with `encode_info_for_trait_item`.
1983 self.prefetch_mir(self.tcx.hir().local_def_id(trait_item.hir_id));
1986 fn visit_impl_item(&self, impl_item: &'v hir::ImplItem<'v>) {
1987 // This should be kept in sync with `encode_info_for_impl_item`.
1989 match impl_item.kind {
1990 hir::ImplItemKind::Const(..) => {
1991 self.prefetch_mir(tcx.hir().local_def_id(impl_item.hir_id))
1993 hir::ImplItemKind::Fn(ref sig, _) => {
1994 let def_id = tcx.hir().local_def_id(impl_item.hir_id);
1995 let generics = tcx.generics_of(def_id.to_def_id());
1996 let needs_inline = generics.requires_monomorphization(tcx)
1997 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1998 let is_const_fn = sig.header.constness == hir::Constness::Const;
1999 if needs_inline || is_const_fn {
2000 self.prefetch_mir(def_id)
2003 hir::ImplItemKind::TyAlias(..) => (),
2007 fn visit_foreign_item(&self, _foreign_item: &'v hir::ForeignItem<'v>) {
2008 // This should be kept in sync with `encode_info_for_foreign_item`.
2009 // Foreign items contain no MIR.
2013 // NOTE(eddyb) The following comment was preserved for posterity, even
2014 // though it's no longer relevant as EBML (which uses nested & tagged
2015 // "documents") was replaced with a scheme that can't go out of bounds.
2017 // And here we run into yet another obscure archive bug: in which metadata
2018 // loaded from archives may have trailing garbage bytes. Awhile back one of
2019 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2020 // and opt) by having ebml generate an out-of-bounds panic when looking at
2023 // Upon investigation it turned out that the metadata file inside of an rlib
2024 // (and ar archive) was being corrupted. Some compilations would generate a
2025 // metadata file which would end in a few extra bytes, while other
2026 // compilations would not have these extra bytes appended to the end. These
2027 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2028 // being interpreted causing the out-of-bounds.
2030 // The root cause of why these extra bytes were appearing was never
2031 // discovered, and in the meantime the solution we're employing is to insert
2032 // the length of the metadata to the start of the metadata. Later on this
2033 // will allow us to slice the metadata to the precise length that we just
2034 // generated regardless of trailing bytes that end up in it.
2036 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2037 // Since encoding metadata is not in a query, and nothing is cached,
2038 // there's no need to do dep-graph tracking for any of it.
2039 tcx.dep_graph.assert_ignored();
2042 || encode_metadata_impl(tcx),
2044 if tcx.sess.threads() == 1 {
2047 // Prefetch some queries used by metadata encoding.
2048 // This is not necessary for correctness, but is only done for performance reasons.
2049 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2052 if !tcx.sess.opts.output_types.should_codegen() {
2053 // We won't emit MIR, so don't prefetch it.
2056 tcx.hir().krate().par_visit_all_item_likes(&PrefetchVisitor {
2058 mir_keys: tcx.mir_keys(LOCAL_CRATE),
2061 || tcx.exported_symbols(LOCAL_CRATE),
2068 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2069 let mut encoder = opaque::Encoder::new(vec![]);
2070 encoder.emit_raw_bytes(METADATA_HEADER);
2072 // Will be filled with the root position after encoding everything.
2073 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2075 let source_map_files = tcx.sess.source_map().files();
2076 let source_file_cache = (source_map_files[0].clone(), 0);
2077 let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2078 drop(source_map_files);
2080 let hygiene_ctxt = HygieneEncodeContext::default();
2082 let mut ecx = EncodeContext {
2085 feat: tcx.features(),
2086 tables: Default::default(),
2087 lazy_state: LazyState::NoNode,
2088 type_shorthands: Default::default(),
2089 predicate_shorthands: Default::default(),
2091 interpret_allocs: Default::default(),
2092 required_source_files,
2093 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2094 hygiene_ctxt: &hygiene_ctxt,
2097 // Encode the rustc version string in a predictable location.
2098 rustc_version().encode(&mut ecx).unwrap();
2100 // Encode all the entries and extra information in the crate,
2101 // culminating in the `CrateRoot` which points to all of it.
2102 let root = ecx.encode_crate_root();
2104 let mut result = ecx.opaque.into_inner();
2106 // Encode the root position.
2107 let header = METADATA_HEADER.len();
2108 let pos = root.position.get();
2109 result[header + 0] = (pos >> 24) as u8;
2110 result[header + 1] = (pos >> 16) as u8;
2111 result[header + 2] = (pos >> 8) as u8;
2112 result[header + 3] = (pos >> 0) as u8;
2114 EncodedMetadata { raw_data: result }