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);
761 self.encode_optimized_mir(def_id.expect_local());
762 self.encode_promoted_mir(def_id.expect_local());
765 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
767 let variant = &def.variants[index];
768 let def_id = variant.ctor_def_id.unwrap();
769 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
771 // FIXME(eddyb) encode only the `CtorKind` for constructors.
772 let data = VariantData {
773 ctor_kind: variant.ctor_kind,
774 discr: variant.discr,
775 ctor: Some(def_id.index),
776 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
779 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
780 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
781 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
782 self.encode_stability(def_id);
783 self.encode_deprecation(def_id);
784 self.encode_item_type(def_id);
785 if variant.ctor_kind == CtorKind::Fn {
786 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
787 self.encode_variances_of(def_id);
789 self.encode_generics(def_id);
790 self.encode_explicit_predicates(def_id);
791 self.encode_inferred_outlives(def_id);
792 self.encode_optimized_mir(def_id.expect_local());
793 self.encode_promoted_mir(def_id.expect_local());
796 fn encode_info_for_mod(&mut self, id: hir::HirId, md: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
798 let local_def_id = tcx.hir().local_def_id(id);
799 let def_id = local_def_id.to_def_id();
800 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
802 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
803 // only ever get called for the crate root. We still want to encode
804 // the crate root for consistency with other crates (some of the resolver
805 // code uses it). However, we skip encoding anything relating to child
806 // items - we encode information about proc-macros later on.
807 let reexports = if !self.is_proc_macro {
808 match tcx.module_exports(local_def_id) {
810 let hir = self.tcx.hir();
814 .map(|export| export.map_id(|id| hir.local_def_id_to_hir_id(id))),
825 expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
828 record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
829 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
830 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
831 record!(self.tables.attributes[def_id] <- attrs);
832 if self.is_proc_macro {
833 record!(self.tables.children[def_id] <- &[]);
835 record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
836 tcx.hir().local_def_id(item_id.id).local_def_index
839 self.encode_stability(def_id);
840 self.encode_deprecation(def_id);
845 adt_def: &ty::AdtDef,
846 variant_index: VariantIdx,
850 let variant = &adt_def.variants[variant_index];
851 let field = &variant.fields[field_index];
853 let def_id = field.did;
854 debug!("EncodeContext::encode_field({:?})", def_id);
856 let variant_id = tcx.hir().local_def_id_to_hir_id(variant.def_id.expect_local());
857 let variant_data = tcx.hir().expect_variant_data(variant_id);
859 record!(self.tables.kind[def_id] <- EntryKind::Field);
860 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
861 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
862 record!(self.tables.attributes[def_id] <- variant_data.fields()[field_index].attrs);
863 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
864 self.encode_ident_span(def_id, field.ident);
865 self.encode_stability(def_id);
866 self.encode_deprecation(def_id);
867 self.encode_item_type(def_id);
868 self.encode_generics(def_id);
869 self.encode_explicit_predicates(def_id);
870 self.encode_inferred_outlives(def_id);
873 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
874 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
876 let variant = adt_def.non_enum_variant();
878 let data = VariantData {
879 ctor_kind: variant.ctor_kind,
880 discr: variant.discr,
881 ctor: Some(def_id.index),
882 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
885 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
886 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
887 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
888 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
889 self.encode_stability(def_id);
890 self.encode_deprecation(def_id);
891 self.encode_item_type(def_id);
892 if variant.ctor_kind == CtorKind::Fn {
893 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
894 self.encode_variances_of(def_id);
896 self.encode_generics(def_id);
897 self.encode_explicit_predicates(def_id);
898 self.encode_inferred_outlives(def_id);
899 self.encode_optimized_mir(def_id.expect_local());
900 self.encode_promoted_mir(def_id.expect_local());
903 fn encode_generics(&mut self, def_id: DefId) {
904 debug!("EncodeContext::encode_generics({:?})", def_id);
905 record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
908 fn encode_explicit_predicates(&mut self, def_id: DefId) {
909 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
910 record!(self.tables.explicit_predicates[def_id] <-
911 self.tcx.explicit_predicates_of(def_id));
914 fn encode_inferred_outlives(&mut self, def_id: DefId) {
915 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
916 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
917 if !inferred_outlives.is_empty() {
918 record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
922 fn encode_super_predicates(&mut self, def_id: DefId) {
923 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
924 record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
927 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
928 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
929 let bounds = self.tcx.explicit_item_bounds(def_id);
930 if !bounds.is_empty() {
931 record!(self.tables.explicit_item_bounds[def_id] <- bounds);
935 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
936 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
939 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
940 let ast_item = tcx.hir().expect_trait_item(hir_id);
941 let trait_item = tcx.associated_item(def_id);
943 let container = match trait_item.defaultness {
944 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
945 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
946 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
949 record!(self.tables.kind[def_id] <- match trait_item.kind {
950 ty::AssocKind::Const => {
951 let rendered = rustc_hir_pretty::to_string(
952 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
953 |s| s.print_trait_item(ast_item)
955 let rendered_const = self.lazy(RenderedConst(rendered));
957 EntryKind::AssocConst(
963 ty::AssocKind::Fn => {
964 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
965 let param_names = match *m {
966 hir::TraitFn::Required(ref names) => {
967 self.encode_fn_param_names(names)
969 hir::TraitFn::Provided(body) => {
970 self.encode_fn_param_names_for_body(body)
974 asyncness: m_sig.header.asyncness,
975 constness: hir::Constness::NotConst,
981 EntryKind::AssocFn(self.lazy(AssocFnData {
984 has_self: trait_item.fn_has_self_parameter,
987 ty::AssocKind::Type => {
988 self.encode_explicit_item_bounds(def_id);
989 EntryKind::AssocType(container)
992 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
993 record!(self.tables.span[def_id] <- ast_item.span);
994 record!(self.tables.attributes[def_id] <- ast_item.attrs);
995 self.encode_ident_span(def_id, ast_item.ident);
996 self.encode_stability(def_id);
997 self.encode_const_stability(def_id);
998 self.encode_deprecation(def_id);
999 match trait_item.kind {
1000 ty::AssocKind::Const | ty::AssocKind::Fn => {
1001 self.encode_item_type(def_id);
1003 ty::AssocKind::Type => {
1004 if trait_item.defaultness.has_value() {
1005 self.encode_item_type(def_id);
1009 if trait_item.kind == ty::AssocKind::Fn {
1010 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1011 self.encode_variances_of(def_id);
1013 self.encode_generics(def_id);
1014 self.encode_explicit_predicates(def_id);
1015 self.encode_inferred_outlives(def_id);
1017 // This should be kept in sync with `PrefetchVisitor.visit_trait_item`.
1018 self.encode_optimized_mir(def_id.expect_local());
1019 self.encode_promoted_mir(def_id.expect_local());
1022 fn metadata_output_only(&self) -> bool {
1023 // MIR optimisation can be skipped when we're just interested in the metadata.
1024 !self.tcx.sess.opts.output_types.should_codegen()
1027 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1028 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1031 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1032 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1033 let impl_item = self.tcx.associated_item(def_id);
1035 let container = match impl_item.defaultness {
1036 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1037 hir::Defaultness::Final => AssocContainer::ImplFinal,
1038 hir::Defaultness::Default { has_value: false } => {
1039 span_bug!(ast_item.span, "impl items always have values (currently)")
1043 record!(self.tables.kind[def_id] <- match impl_item.kind {
1044 ty::AssocKind::Const => {
1045 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1046 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1048 EntryKind::AssocConst(
1051 self.encode_rendered_const_for_body(body_id))
1056 ty::AssocKind::Fn => {
1057 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1059 asyncness: sig.header.asyncness,
1060 constness: sig.header.constness,
1061 param_names: self.encode_fn_param_names_for_body(body),
1066 EntryKind::AssocFn(self.lazy(AssocFnData {
1069 has_self: impl_item.fn_has_self_parameter,
1072 ty::AssocKind::Type => EntryKind::AssocType(container)
1074 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1075 record!(self.tables.span[def_id] <- ast_item.span);
1076 record!(self.tables.attributes[def_id] <- ast_item.attrs);
1077 self.encode_ident_span(def_id, impl_item.ident);
1078 self.encode_stability(def_id);
1079 self.encode_const_stability(def_id);
1080 self.encode_deprecation(def_id);
1081 self.encode_item_type(def_id);
1082 if impl_item.kind == ty::AssocKind::Fn {
1083 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1084 self.encode_variances_of(def_id);
1086 self.encode_generics(def_id);
1087 self.encode_explicit_predicates(def_id);
1088 self.encode_inferred_outlives(def_id);
1090 // The following part should be kept in sync with `PrefetchVisitor.visit_impl_item`.
1092 let mir = match ast_item.kind {
1093 hir::ImplItemKind::Const(..) => true,
1094 hir::ImplItemKind::Fn(ref sig, _) => {
1095 let generics = self.tcx.generics_of(def_id);
1096 let needs_inline = (generics.requires_monomorphization(self.tcx)
1097 || tcx.codegen_fn_attrs(def_id).requests_inline())
1098 && !self.metadata_output_only();
1099 let is_const_fn = sig.header.constness == hir::Constness::Const;
1100 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1101 needs_inline || is_const_fn || always_encode_mir
1103 hir::ImplItemKind::TyAlias(..) => false,
1106 self.encode_optimized_mir(def_id.expect_local());
1107 self.encode_promoted_mir(def_id.expect_local());
1111 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1112 self.lazy(self.tcx.hir().body_param_names(body_id))
1115 fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1116 self.lazy(param_names.iter())
1119 fn encode_optimized_mir(&mut self, def_id: LocalDefId) {
1120 debug!("EntryBuilder::encode_mir({:?})", def_id);
1121 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1123 let unused = self.tcx.unused_generic_params(def_id);
1124 if !unused.is_empty() {
1125 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1128 let abstract_const = self.tcx.mir_abstract_const(def_id);
1129 if let Ok(Some(abstract_const)) = abstract_const {
1130 record!(self.tables.mir_abstract_consts[def_id.to_def_id()] <- abstract_const);
1134 fn encode_promoted_mir(&mut self, def_id: LocalDefId) {
1135 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1136 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1137 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1141 // Encodes the inherent implementations of a structure, enumeration, or trait.
1142 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1143 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1144 let implementations = self.tcx.inherent_impls(def_id);
1145 if !implementations.is_empty() {
1146 record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1147 assert!(def_id.is_local());
1153 fn encode_stability(&mut self, def_id: DefId) {
1154 debug!("EncodeContext::encode_stability({:?})", def_id);
1156 // The query lookup can take a measurable amount of time in crates with many items. Check if
1157 // the stability attributes are even enabled before using their queries.
1158 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1159 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1160 record!(self.tables.stability[def_id] <- stab)
1165 fn encode_const_stability(&mut self, def_id: DefId) {
1166 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1168 // The query lookup can take a measurable amount of time in crates with many items. Check if
1169 // the stability attributes are even enabled before using their queries.
1170 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1171 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1172 record!(self.tables.const_stability[def_id] <- stab)
1177 fn encode_deprecation(&mut self, def_id: DefId) {
1178 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1179 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1180 record!(self.tables.deprecation[def_id] <- depr);
1184 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1185 let hir = self.tcx.hir();
1186 let body = hir.body(body_id);
1187 let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1188 s.print_expr(&body.value)
1190 let rendered_const = &RenderedConst(rendered);
1191 self.lazy(rendered_const)
1194 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1197 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1199 self.encode_ident_span(def_id, item.ident);
1201 record!(self.tables.kind[def_id] <- match item.kind {
1202 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1203 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1204 hir::ItemKind::Const(_, body_id) => {
1205 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1208 self.encode_rendered_const_for_body(body_id)
1211 hir::ItemKind::Fn(ref sig, .., body) => {
1213 asyncness: sig.header.asyncness,
1214 constness: sig.header.constness,
1215 param_names: self.encode_fn_param_names_for_body(body),
1218 EntryKind::Fn(self.lazy(data))
1220 hir::ItemKind::Mod(ref m) => {
1221 return self.encode_info_for_mod(item.hir_id, m, &item.attrs);
1223 hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1224 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1225 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1226 hir::ItemKind::OpaqueTy(..) => {
1227 self.encode_explicit_item_bounds(def_id);
1230 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1231 hir::ItemKind::Struct(ref struct_def, _) => {
1232 let adt_def = self.tcx.adt_def(def_id);
1233 let variant = adt_def.non_enum_variant();
1235 // Encode def_ids for each field and method
1236 // for methods, write all the stuff get_trait_method
1238 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1239 self.tcx.hir().local_def_id(ctor_hir_id).local_def_index
1242 EntryKind::Struct(self.lazy(VariantData {
1243 ctor_kind: variant.ctor_kind,
1244 discr: variant.discr,
1246 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1249 hir::ItemKind::Union(..) => {
1250 let adt_def = self.tcx.adt_def(def_id);
1251 let variant = adt_def.non_enum_variant();
1253 EntryKind::Union(self.lazy(VariantData {
1254 ctor_kind: variant.ctor_kind,
1255 discr: variant.discr,
1257 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1260 hir::ItemKind::Impl { defaultness, .. } => {
1261 let trait_ref = self.tcx.impl_trait_ref(def_id);
1262 let polarity = self.tcx.impl_polarity(def_id);
1263 let parent = if let Some(trait_ref) = trait_ref {
1264 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1265 trait_def.ancestors(self.tcx, def_id).ok()
1266 .and_then(|mut an| an.nth(1).and_then(|node| {
1268 specialization_graph::Node::Impl(parent) => Some(parent),
1276 // if this is an impl of `CoerceUnsized`, create its
1277 // "unsized info", else just store None
1278 let coerce_unsized_info =
1279 trait_ref.and_then(|t| {
1280 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1281 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1287 let data = ImplData {
1290 parent_impl: parent,
1291 coerce_unsized_info,
1294 EntryKind::Impl(self.lazy(data))
1296 hir::ItemKind::Trait(..) => {
1297 let trait_def = self.tcx.trait_def(def_id);
1298 let data = TraitData {
1299 unsafety: trait_def.unsafety,
1300 paren_sugar: trait_def.paren_sugar,
1301 has_auto_impl: self.tcx.trait_is_auto(def_id),
1302 is_marker: trait_def.is_marker,
1303 specialization_kind: trait_def.specialization_kind,
1306 EntryKind::Trait(self.lazy(data))
1308 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1309 hir::ItemKind::ExternCrate(_) |
1310 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1312 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1313 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1314 record!(self.tables.attributes[def_id] <- item.attrs);
1315 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
1316 // FIXME(eddyb) there should be a nicer way to do this.
1318 hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <-
1321 .map(|foreign_item| tcx.hir().local_def_id(
1322 foreign_item.id.hir_id).local_def_index)
1324 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1325 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1326 assert!(v.def_id.is_local());
1330 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1331 record!(self.tables.children[def_id] <-
1332 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1333 assert!(f.did.is_local());
1338 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1339 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1340 record!(self.tables.children[def_id] <-
1341 associated_item_def_ids.iter().map(|&def_id| {
1342 assert!(def_id.is_local());
1349 self.encode_stability(def_id);
1350 self.encode_const_stability(def_id);
1351 self.encode_deprecation(def_id);
1353 hir::ItemKind::Static(..)
1354 | hir::ItemKind::Const(..)
1355 | hir::ItemKind::Fn(..)
1356 | hir::ItemKind::TyAlias(..)
1357 | hir::ItemKind::OpaqueTy(..)
1358 | hir::ItemKind::Enum(..)
1359 | hir::ItemKind::Struct(..)
1360 | hir::ItemKind::Union(..)
1361 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1364 if let hir::ItemKind::Fn(..) = item.kind {
1365 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1367 if let hir::ItemKind::Impl { .. } = item.kind {
1368 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1369 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1372 self.encode_inherent_implementations(def_id);
1374 hir::ItemKind::Enum(..)
1375 | hir::ItemKind::Struct(..)
1376 | hir::ItemKind::Union(..)
1377 | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1381 hir::ItemKind::Static(..)
1382 | hir::ItemKind::Const(..)
1383 | hir::ItemKind::Fn(..)
1384 | hir::ItemKind::TyAlias(..)
1385 | hir::ItemKind::Enum(..)
1386 | hir::ItemKind::Struct(..)
1387 | hir::ItemKind::Union(..)
1388 | hir::ItemKind::Impl { .. }
1389 | hir::ItemKind::OpaqueTy(..)
1390 | hir::ItemKind::Trait(..)
1391 | hir::ItemKind::TraitAlias(..) => {
1392 self.encode_generics(def_id);
1393 self.encode_explicit_predicates(def_id);
1394 self.encode_inferred_outlives(def_id);
1399 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1400 self.encode_super_predicates(def_id);
1405 // The following part should be kept in sync with `PrefetchVisitor.visit_item`.
1407 let mir = match item.kind {
1408 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1409 hir::ItemKind::Fn(ref sig, ..) => {
1410 let generics = tcx.generics_of(def_id);
1411 let needs_inline = (generics.requires_monomorphization(tcx)
1412 || tcx.codegen_fn_attrs(def_id).requests_inline())
1413 && !self.metadata_output_only();
1415 let is_const_fn = sig.header.constness == hir::Constness::Const;
1416 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1417 needs_inline || is_const_fn || always_encode_mir
1422 self.encode_optimized_mir(def_id.expect_local());
1423 self.encode_promoted_mir(def_id.expect_local());
1427 /// Serialize the text of exported macros
1428 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1429 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id();
1430 record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1431 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1432 record!(self.tables.span[def_id] <- macro_def.span);
1433 record!(self.tables.attributes[def_id] <- macro_def.attrs);
1434 self.encode_ident_span(def_id, macro_def.ident);
1435 self.encode_stability(def_id);
1436 self.encode_deprecation(def_id);
1439 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1440 record!(self.tables.kind[def_id] <- kind);
1441 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1443 self.encode_item_type(def_id);
1447 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1448 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1450 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1451 // including on the signature, which is inferred in `typeck.
1452 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1453 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1455 record!(self.tables.kind[def_id.to_def_id()] <- match ty.kind() {
1456 ty::Generator(..) => {
1457 let data = self.tcx.generator_kind(def_id).unwrap();
1458 EntryKind::Generator(data)
1461 ty::Closure(..) => EntryKind::Closure,
1463 _ => bug!("closure that is neither generator nor closure"),
1465 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1466 record!(self.tables.attributes[def_id.to_def_id()] <- &self.tcx.get_attrs(def_id.to_def_id())[..]);
1467 self.encode_item_type(def_id.to_def_id());
1468 if let ty::Closure(def_id, substs) = *ty.kind() {
1469 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1471 self.encode_generics(def_id.to_def_id());
1472 self.encode_optimized_mir(def_id);
1473 self.encode_promoted_mir(def_id);
1476 fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1477 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1478 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1479 let body_id = self.tcx.hir().body_owned_by(id);
1480 let const_data = self.encode_rendered_const_for_body(body_id);
1481 let qualifs = self.tcx.mir_const_qualif(def_id);
1483 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1484 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1485 self.encode_item_type(def_id.to_def_id());
1486 self.encode_generics(def_id.to_def_id());
1487 self.encode_explicit_predicates(def_id.to_def_id());
1488 self.encode_inferred_outlives(def_id.to_def_id());
1489 self.encode_optimized_mir(def_id);
1490 self.encode_promoted_mir(def_id);
1493 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1494 empty_proc_macro!(self);
1495 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1496 self.lazy(used_libraries.iter().cloned())
1499 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1500 empty_proc_macro!(self);
1501 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1502 self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1505 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) {
1506 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1507 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1509 let _: Result<(), !> = self.hygiene_ctxt.encode(
1510 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table),
1511 |(this, syntax_contexts, _), index, ctxt_data| {
1512 syntax_contexts.set(index, this.lazy(ctxt_data));
1515 |(this, _, expn_data_table), index, expn_data| {
1516 expn_data_table.set(index, this.lazy(expn_data));
1521 (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque))
1524 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1525 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1528 let hir = tcx.hir();
1530 let proc_macro_decls_static = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap().index;
1531 let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1532 let macros = self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.local_def_index));
1534 // Normally, this information is encoded when we walk the items
1535 // defined in this crate. However, we skip doing that for proc-macro crates,
1536 // so we manually encode just the information that we need
1537 for proc_macro in &hir.krate().proc_macros {
1538 let id = proc_macro.owner.local_def_index;
1539 let mut name = hir.name(*proc_macro);
1540 let span = hir.span(*proc_macro);
1541 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1542 // so downstream crates need access to them.
1543 let attrs = hir.attrs(*proc_macro);
1544 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1546 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1548 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1549 // This unwrap chain should have been checked by the proc-macro harness.
1550 name = attr.meta_item_list().unwrap()[0]
1558 bug!("Unknown proc-macro type for item {:?}", id);
1561 let mut def_key = self.tcx.hir().def_key(proc_macro.owner);
1562 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1564 let def_id = DefId::local(id);
1565 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1566 record!(self.tables.attributes[def_id] <- attrs);
1567 record!(self.tables.def_keys[def_id] <- def_key);
1568 record!(self.tables.ident_span[def_id] <- span);
1569 record!(self.tables.span[def_id] <- span);
1570 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1571 if let Some(stability) = stability {
1572 record!(self.tables.stability[def_id] <- stability);
1576 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1582 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1583 empty_proc_macro!(self);
1584 let crates = self.tcx.crates();
1586 let mut deps = crates
1589 let dep = CrateDep {
1590 name: self.tcx.original_crate_name(cnum),
1591 hash: self.tcx.crate_hash(cnum),
1592 host_hash: self.tcx.crate_host_hash(cnum),
1593 kind: self.tcx.dep_kind(cnum),
1594 extra_filename: self.tcx.extra_filename(cnum),
1598 .collect::<Vec<_>>();
1600 deps.sort_by_key(|&(cnum, _)| cnum);
1603 // Sanity-check the crate numbers
1604 let mut expected_cnum = 1;
1605 for &(n, _) in &deps {
1606 assert_eq!(n, CrateNum::new(expected_cnum));
1611 // We're just going to write a list of crate 'name-hash-version's, with
1612 // the assumption that they are numbered 1 to n.
1613 // FIXME (#2166): This is not nearly enough to support correct versioning
1614 // but is enough to get transitive crate dependencies working.
1615 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1618 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1619 empty_proc_macro!(self);
1621 let lib_features = tcx.lib_features();
1622 self.lazy(lib_features.to_vec())
1625 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1626 empty_proc_macro!(self);
1628 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1629 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1632 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1633 empty_proc_macro!(self);
1635 let lang_items = tcx.lang_items();
1636 let lang_items = lang_items.items().iter();
1637 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1638 if let Some(def_id) = opt_def_id {
1639 if def_id.is_local() {
1640 return Some((def_id.index, i));
1647 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1648 empty_proc_macro!(self);
1650 self.lazy(&tcx.lang_items().missing)
1653 /// Encodes an index, mapping each trait to its (local) implementations.
1654 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1655 empty_proc_macro!(self);
1656 debug!("EncodeContext::encode_impls()");
1658 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1659 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1661 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1663 // Bring everything into deterministic order for hashing
1664 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1666 let all_impls: Vec<_> = all_impls
1668 .map(|(trait_def_id, mut impls)| {
1669 // Bring everything into deterministic order for hashing
1670 impls.sort_by_cached_key(|&(index, _)| {
1671 tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1675 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1676 impls: self.lazy(&impls),
1681 self.lazy(&all_impls)
1684 // Encodes all symbols exported from this crate into the metadata.
1686 // This pass is seeded off the reachability list calculated in the
1687 // middle::reachable module but filters out items that either don't have a
1688 // symbol associated with them (they weren't translated) or if they're an FFI
1689 // definition (as that's not defined in this crate).
1690 fn encode_exported_symbols(
1692 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1693 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1694 empty_proc_macro!(self);
1695 // The metadata symbol name is special. It should not show up in
1696 // downstream crates.
1697 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1702 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1703 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1710 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1711 empty_proc_macro!(self);
1712 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1713 for (ty, arr) in formats.iter() {
1714 if *ty != CrateType::Dylib {
1717 return self.lazy(arr.iter().map(|slot| match *slot {
1718 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1720 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1721 Linkage::Static => Some(LinkagePreference::RequireStatic),
1727 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1730 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1732 record!(self.tables.kind[def_id] <- match nitem.kind {
1733 hir::ForeignItemKind::Fn(_, ref names, _) => {
1735 asyncness: hir::IsAsync::NotAsync,
1736 constness: if self.tcx.is_const_fn_raw(def_id) {
1737 hir::Constness::Const
1739 hir::Constness::NotConst
1741 param_names: self.encode_fn_param_names(names),
1743 EntryKind::ForeignFn(self.lazy(data))
1745 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1746 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1747 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1749 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1750 record!(self.tables.span[def_id] <- nitem.span);
1751 record!(self.tables.attributes[def_id] <- nitem.attrs);
1752 self.encode_ident_span(def_id, nitem.ident);
1753 self.encode_stability(def_id);
1754 self.encode_const_stability(def_id);
1755 self.encode_deprecation(def_id);
1756 self.encode_item_type(def_id);
1757 self.encode_inherent_implementations(def_id);
1758 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1759 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1760 self.encode_variances_of(def_id);
1762 self.encode_generics(def_id);
1763 self.encode_explicit_predicates(def_id);
1764 self.encode_inferred_outlives(def_id);
1768 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1769 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1770 type Map = Map<'tcx>;
1772 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1773 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1775 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1776 intravisit::walk_expr(self, ex);
1777 self.encode_info_for_expr(ex);
1779 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1780 intravisit::walk_anon_const(self, c);
1781 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1782 self.encode_info_for_anon_const(def_id);
1784 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1785 intravisit::walk_item(self, item);
1786 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1788 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1789 _ => self.encode_info_for_item(def_id.to_def_id(), item),
1791 self.encode_addl_info_for_item(item);
1793 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1794 intravisit::walk_foreign_item(self, ni);
1795 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1796 self.encode_info_for_foreign_item(def_id.to_def_id(), ni);
1798 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1799 intravisit::walk_generics(self, generics);
1800 self.encode_info_for_generics(generics);
1802 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1803 self.encode_info_for_macro_def(macro_def);
1807 impl EncodeContext<'a, 'tcx> {
1808 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1809 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1810 for (field_index, _field) in variant.fields.iter().enumerate() {
1811 self.encode_field(adt_def, variant_index, field_index);
1816 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1817 for param in generics.params {
1818 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1820 GenericParamKind::Lifetime { .. } => continue,
1821 GenericParamKind::Type { ref default, .. } => {
1822 self.encode_info_for_generic_param(
1824 EntryKind::TypeParam,
1827 if default.is_some() {
1828 self.encode_stability(def_id.to_def_id());
1831 GenericParamKind::Const { .. } => {
1832 self.encode_info_for_generic_param(
1834 EntryKind::ConstParam,
1837 // FIXME(const_generics_defaults)
1843 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1844 if let hir::ExprKind::Closure(..) = expr.kind {
1845 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1846 self.encode_info_for_closure(def_id);
1850 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1851 record!(self.tables.ident_span[def_id] <- ident.span);
1854 /// In some cases, along with the item itself, we also
1855 /// encode some sub-items. Usually we want some info from the item
1856 /// so it's easier to do that here then to wait until we would encounter
1857 /// normally in the visitor walk.
1858 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1859 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1861 hir::ItemKind::Static(..)
1862 | hir::ItemKind::Const(..)
1863 | hir::ItemKind::Fn(..)
1864 | hir::ItemKind::Mod(..)
1865 | hir::ItemKind::ForeignMod { .. }
1866 | hir::ItemKind::GlobalAsm(..)
1867 | hir::ItemKind::ExternCrate(..)
1868 | hir::ItemKind::Use(..)
1869 | hir::ItemKind::TyAlias(..)
1870 | hir::ItemKind::OpaqueTy(..)
1871 | hir::ItemKind::TraitAlias(..) => {
1872 // no sub-item recording needed in these cases
1874 hir::ItemKind::Enum(..) => {
1875 let def = self.tcx.adt_def(def_id.to_def_id());
1876 self.encode_fields(def);
1878 for (i, variant) in def.variants.iter_enumerated() {
1879 self.encode_enum_variant_info(def, i);
1881 if let Some(_ctor_def_id) = variant.ctor_def_id {
1882 self.encode_enum_variant_ctor(def, i);
1886 hir::ItemKind::Struct(ref struct_def, _) => {
1887 let def = self.tcx.adt_def(def_id.to_def_id());
1888 self.encode_fields(def);
1890 // If the struct has a constructor, encode it.
1891 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1892 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1893 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1896 hir::ItemKind::Union(..) => {
1897 let def = self.tcx.adt_def(def_id.to_def_id());
1898 self.encode_fields(def);
1900 hir::ItemKind::Impl { .. } => {
1901 for &trait_item_def_id in
1902 self.tcx.associated_item_def_ids(def_id.to_def_id()).iter()
1904 self.encode_info_for_impl_item(trait_item_def_id);
1907 hir::ItemKind::Trait(..) => {
1908 for &item_def_id in self.tcx.associated_item_def_ids(def_id.to_def_id()).iter() {
1909 self.encode_info_for_trait_item(item_def_id);
1916 struct ImplVisitor<'tcx> {
1918 impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
1921 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1922 fn visit_item(&mut self, item: &hir::Item<'_>) {
1923 if let hir::ItemKind::Impl { .. } = item.kind {
1924 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1925 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id.to_def_id()) {
1926 let simplified_self_ty =
1927 ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
1930 .entry(trait_ref.def_id)
1932 .push((impl_id.local_def_index, simplified_self_ty));
1937 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1939 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1940 // handled in `visit_item` above
1943 fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
1946 /// Used to prefetch queries which will be needed later by metadata encoding.
1947 /// Only a subset of the queries are actually prefetched to keep this code smaller.
1948 struct PrefetchVisitor<'tcx> {
1950 mir_keys: &'tcx FxHashSet<LocalDefId>,
1953 impl<'tcx> PrefetchVisitor<'tcx> {
1954 fn prefetch_mir(&self, def_id: LocalDefId) {
1955 if self.mir_keys.contains(&def_id) {
1956 self.tcx.ensure().optimized_mir(def_id);
1957 self.tcx.ensure().promoted_mir(def_id);
1962 impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> {
1963 fn visit_item(&self, item: &hir::Item<'_>) {
1964 // This should be kept in sync with `encode_info_for_item`.
1967 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
1968 self.prefetch_mir(tcx.hir().local_def_id(item.hir_id))
1970 hir::ItemKind::Fn(ref sig, ..) => {
1971 let def_id = tcx.hir().local_def_id(item.hir_id);
1972 let generics = tcx.generics_of(def_id.to_def_id());
1973 let needs_inline = generics.requires_monomorphization(tcx)
1974 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1975 if needs_inline || sig.header.constness == hir::Constness::Const {
1976 self.prefetch_mir(def_id)
1983 fn visit_trait_item(&self, trait_item: &'v hir::TraitItem<'v>) {
1984 // This should be kept in sync with `encode_info_for_trait_item`.
1985 self.prefetch_mir(self.tcx.hir().local_def_id(trait_item.hir_id));
1988 fn visit_impl_item(&self, impl_item: &'v hir::ImplItem<'v>) {
1989 // This should be kept in sync with `encode_info_for_impl_item`.
1991 match impl_item.kind {
1992 hir::ImplItemKind::Const(..) => {
1993 self.prefetch_mir(tcx.hir().local_def_id(impl_item.hir_id))
1995 hir::ImplItemKind::Fn(ref sig, _) => {
1996 let def_id = tcx.hir().local_def_id(impl_item.hir_id);
1997 let generics = tcx.generics_of(def_id.to_def_id());
1998 let needs_inline = generics.requires_monomorphization(tcx)
1999 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
2000 let is_const_fn = sig.header.constness == hir::Constness::Const;
2001 if needs_inline || is_const_fn {
2002 self.prefetch_mir(def_id)
2005 hir::ImplItemKind::TyAlias(..) => (),
2009 fn visit_foreign_item(&self, _foreign_item: &'v hir::ForeignItem<'v>) {
2010 // This should be kept in sync with `encode_info_for_foreign_item`.
2011 // Foreign items contain no MIR.
2015 // NOTE(eddyb) The following comment was preserved for posterity, even
2016 // though it's no longer relevant as EBML (which uses nested & tagged
2017 // "documents") was replaced with a scheme that can't go out of bounds.
2019 // And here we run into yet another obscure archive bug: in which metadata
2020 // loaded from archives may have trailing garbage bytes. Awhile back one of
2021 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2022 // and opt) by having ebml generate an out-of-bounds panic when looking at
2025 // Upon investigation it turned out that the metadata file inside of an rlib
2026 // (and ar archive) was being corrupted. Some compilations would generate a
2027 // metadata file which would end in a few extra bytes, while other
2028 // compilations would not have these extra bytes appended to the end. These
2029 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2030 // being interpreted causing the out-of-bounds.
2032 // The root cause of why these extra bytes were appearing was never
2033 // discovered, and in the meantime the solution we're employing is to insert
2034 // the length of the metadata to the start of the metadata. Later on this
2035 // will allow us to slice the metadata to the precise length that we just
2036 // generated regardless of trailing bytes that end up in it.
2038 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2039 // Since encoding metadata is not in a query, and nothing is cached,
2040 // there's no need to do dep-graph tracking for any of it.
2041 tcx.dep_graph.assert_ignored();
2044 || encode_metadata_impl(tcx),
2046 if tcx.sess.threads() == 1 {
2049 // Prefetch some queries used by metadata encoding.
2050 // This is not necessary for correctness, but is only done for performance reasons.
2051 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2054 if !tcx.sess.opts.output_types.should_codegen() {
2055 // We won't emit MIR, so don't prefetch it.
2058 tcx.hir().krate().par_visit_all_item_likes(&PrefetchVisitor {
2060 mir_keys: tcx.mir_keys(LOCAL_CRATE),
2063 || tcx.exported_symbols(LOCAL_CRATE),
2070 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2071 let mut encoder = opaque::Encoder::new(vec![]);
2072 encoder.emit_raw_bytes(METADATA_HEADER);
2074 // Will be filled with the root position after encoding everything.
2075 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2077 let source_map_files = tcx.sess.source_map().files();
2078 let source_file_cache = (source_map_files[0].clone(), 0);
2079 let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2080 drop(source_map_files);
2082 let hygiene_ctxt = HygieneEncodeContext::default();
2084 let mut ecx = EncodeContext {
2087 feat: tcx.features(),
2088 tables: Default::default(),
2089 lazy_state: LazyState::NoNode,
2090 type_shorthands: Default::default(),
2091 predicate_shorthands: Default::default(),
2093 interpret_allocs: Default::default(),
2094 required_source_files,
2095 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2096 hygiene_ctxt: &hygiene_ctxt,
2099 // Encode the rustc version string in a predictable location.
2100 rustc_version().encode(&mut ecx).unwrap();
2102 // Encode all the entries and extra information in the crate,
2103 // culminating in the `CrateRoot` which points to all of it.
2104 let root = ecx.encode_crate_root();
2106 let mut result = ecx.opaque.into_inner();
2108 // Encode the root position.
2109 let header = METADATA_HEADER.len();
2110 let pos = root.position.get();
2111 result[header + 0] = (pos >> 24) as u8;
2112 result[header + 1] = (pos >> 16) as u8;
2113 result[header + 2] = (pos >> 8) as u8;
2114 result[header + 3] = (pos >> 0) as u8;
2116 EncodedMetadata { raw_data: result }