1 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
2 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
5 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
6 use rustc_data_structures::stable_hasher::StableHasher;
7 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
9 use rustc_hir::def::DefKind;
10 use rustc_hir::def_id::{
11 CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
13 use rustc_hir::definitions::DefPathData;
14 use rustc_hir::intravisit::{self, Visitor};
15 use rustc_hir::itemlikevisit::ItemLikeVisitor;
16 use rustc_hir::lang_items;
17 use rustc_hir::{AnonConst, GenericParamKind};
18 use rustc_index::bit_set::GrowableBitSet;
19 use rustc_index::vec::Idx;
20 use rustc_middle::hir::nested_filter;
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::thir;
27 use rustc_middle::traits::specialization_graph;
28 use rustc_middle::ty::codec::TyEncoder;
29 use rustc_middle::ty::fast_reject::{self, SimplifiedType, SimplifyParams};
30 use rustc_middle::ty::query::Providers;
31 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
32 use rustc_serialize::{opaque, Encodable, Encoder};
33 use rustc_session::config::CrateType;
34 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
35 use rustc_span::symbol::{sym, Ident, Symbol};
36 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
38 hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind},
41 use rustc_target::abi::VariantIdx;
43 use std::num::NonZeroUsize;
45 use tracing::{debug, trace};
47 pub(super) struct EncodeContext<'a, 'tcx> {
48 opaque: opaque::Encoder,
50 feat: &'tcx rustc_feature::Features,
52 tables: TableBuilders<'tcx>,
54 lazy_state: LazyState,
55 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
56 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
58 interpret_allocs: FxIndexSet<interpret::AllocId>,
60 // This is used to speed up Span encoding.
61 // The `usize` is an index into the `MonotonicVec`
62 // that stores the `SourceFile`
63 source_file_cache: (Lrc<SourceFile>, usize),
64 // The indices (into the `SourceMap`'s `MonotonicVec`)
65 // of all of the `SourceFiles` that we need to serialize.
66 // When we serialize a `Span`, we insert the index of its
67 // `SourceFile` into the `GrowableBitSet`.
69 // This needs to be a `GrowableBitSet` and not a
70 // regular `BitSet` because we may actually import new `SourceFiles`
71 // during metadata encoding, due to executing a query
72 // with a result containing a foreign `Span`.
73 required_source_files: Option<GrowableBitSet<usize>>,
75 hygiene_ctxt: &'a HygieneEncodeContext,
78 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
79 /// This is useful for skipping the encoding of things that aren't needed
80 /// for proc-macro crates.
81 macro_rules! empty_proc_macro {
83 if $self.is_proc_macro {
89 macro_rules! encoder_methods {
90 ($($name:ident($ty:ty);)*) => {
91 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
92 self.opaque.$name(value)
97 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
98 type Error = <opaque::Encoder as Encoder>::Error;
101 fn emit_unit(&mut self) -> Result<(), Self::Error> {
125 emit_raw_bytes(&[u8]);
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_lazy_distance(*self)
137 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
140 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
141 e.emit_usize(self.meta)?;
145 e.emit_lazy_distance(*self)
149 impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
150 for Lazy<Table<I, T>>
152 Option<T>: FixedSizeEncoding,
154 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
155 e.emit_usize(self.meta)?;
156 e.emit_lazy_distance(*self)
160 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
161 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
162 if *self != LOCAL_CRATE && s.is_proc_macro {
163 panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
165 s.emit_u32(self.as_u32())
169 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
170 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
171 s.emit_u32(self.as_u32())
175 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
176 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
177 s.emit_u32(self.as_u32())
181 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
182 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
183 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
187 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
188 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
189 if self.krate == LOCAL_CRATE {
190 // We will only write details for local expansions. Non-local expansions will fetch
191 // data from the corresponding crate's metadata.
192 // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
193 // metadata from proc-macro crates.
194 s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
196 self.krate.encode(s)?;
197 self.local_id.encode(s)
201 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
202 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
203 let span = self.data();
205 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
206 // since we don't load proc-macro dependencies during serialization.
207 // This means that any hygiene information from macros used *within*
208 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
209 // definition) will be lost.
211 // This can show up in two ways:
213 // 1. Any hygiene information associated with identifier of
214 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
215 // Since proc-macros can only be invoked from a different crate,
216 // real code should never need to care about this.
218 // 2. Using `Span::def_site` or `Span::mixed_site` will not
219 // include any hygiene information associated with the definition
220 // site. This means that a proc-macro cannot emit a `$crate`
221 // identifier which resolves to one of its dependencies,
222 // which also should never come up in practice.
224 // Additionally, this affects `Span::parent`, and any other
225 // span inspection APIs that would otherwise allow traversing
226 // the `SyntaxContexts` associated with a span.
228 // None of these user-visible effects should result in any
229 // cross-crate inconsistencies (getting one behavior in the same
230 // crate, and a different behavior in another crate) due to the
231 // limited surface that proc-macros can expose.
233 // IMPORTANT: If this is ever changed, be sure to update
234 // `rustc_span::hygiene::raw_encode_expn_id` to handle
235 // encoding `ExpnData` for proc-macro crates.
237 SyntaxContext::root().encode(s)?;
239 span.ctxt.encode(s)?;
243 return TAG_PARTIAL_SPAN.encode(s);
246 // The Span infrastructure should make sure that this invariant holds:
247 debug_assert!(span.lo <= span.hi);
249 if !s.source_file_cache.0.contains(span.lo) {
250 let source_map = s.tcx.sess.source_map();
251 let source_file_index = source_map.lookup_source_file_idx(span.lo);
252 s.source_file_cache =
253 (source_map.files()[source_file_index].clone(), source_file_index);
256 if !s.source_file_cache.0.contains(span.hi) {
257 // Unfortunately, macro expansion still sometimes generates Spans
258 // that malformed in this way.
259 return TAG_PARTIAL_SPAN.encode(s);
262 let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
263 // Record the fact that we need to encode the data for this `SourceFile`
264 source_files.insert(s.source_file_cache.1);
266 // There are two possible cases here:
267 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
268 // crate we are writing metadata for. When the metadata for *this* crate gets
269 // deserialized, the deserializer will need to know which crate it originally came
270 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
271 // be deserialized after the rest of the span data, which tells the deserializer
272 // which crate contains the source map information.
273 // 2. This span comes from our own crate. No special hamdling is needed - we just
274 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
275 // our own source map information.
277 // If we're a proc-macro crate, we always treat this as a local `Span`.
278 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
279 // if we're a proc-macro crate.
280 // This allows us to avoid loading the dependencies of proc-macro crates: all of
281 // the information we need to decode `Span`s is stored in the proc-macro crate.
282 let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
283 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
284 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
285 // are relative to the source map information for the 'foreign' crate whose CrateNum
286 // we write into the metadata. This allows `imported_source_files` to binary
287 // search through the 'foreign' crate's source map information, using the
288 // deserialized 'lo' and 'hi' values directly.
290 // All of this logic ensures that the final result of deserialization is a 'normal'
291 // Span that can be used without any additional trouble.
292 let external_start_pos = {
293 // Introduce a new scope so that we drop the 'lock()' temporary
294 match &*s.source_file_cache.0.external_src.lock() {
295 ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
296 src => panic!("Unexpected external source {:?}", src),
299 let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
300 let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
302 (TAG_VALID_SPAN_FOREIGN, lo, hi)
304 (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
310 // Encode length which is usually less than span.hi and profits more
311 // from the variable-length integer encoding that we use.
315 if tag == TAG_VALID_SPAN_FOREIGN {
316 // This needs to be two lines to avoid holding the `s.source_file_cache`
317 // while calling `cnum.encode(s)`
318 let cnum = s.source_file_cache.0.cnum;
326 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
327 const CLEAR_CROSS_CRATE: bool = true;
329 fn position(&self) -> usize {
330 self.opaque.position()
333 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
334 &mut self.type_shorthands
337 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
338 &mut self.predicate_shorthands
343 alloc_id: &rustc_middle::mir::interpret::AllocId,
344 ) -> Result<(), Self::Error> {
345 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
351 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [thir::abstract_const::Node<'tcx>] {
352 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
357 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
358 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
363 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
364 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
365 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
368 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
369 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
370 self.encode(ecx).unwrap()
374 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
375 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
376 self.encode(ecx).unwrap()
380 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
383 I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
385 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
386 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
390 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
391 // normally need extra variables to avoid errors about multiple mutable borrows.
392 macro_rules! record {
393 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
396 let lazy = $self.lazy(value);
397 $self.$tables.$table.set($def_id.index, lazy);
402 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
403 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
406 ) -> Result<(), <Self as Encoder>::Error> {
407 let pos = lazy.position.get();
408 let distance = match self.lazy_state {
409 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
410 LazyState::NodeStart(start) => {
411 let start = start.get();
412 assert!(pos <= start);
415 LazyState::Previous(last_pos) => {
417 last_pos <= lazy.position,
418 "make sure that the calls to `lazy*` \
419 are in the same order as the metadata fields",
421 lazy.position.get() - last_pos.get()
424 self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap());
425 self.emit_usize(distance)
428 fn lazy<T: ?Sized + LazyMeta>(
430 value: impl EncodeContentsForLazy<'a, 'tcx, T>,
432 let pos = NonZeroUsize::new(self.position()).unwrap();
434 assert_eq!(self.lazy_state, LazyState::NoNode);
435 self.lazy_state = LazyState::NodeStart(pos);
436 let meta = value.encode_contents_for_lazy(self);
437 self.lazy_state = LazyState::NoNode;
439 assert!(pos.get() <= self.position());
441 Lazy::from_position_and_meta(pos, meta)
444 fn encode_info_for_items(&mut self) {
445 self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
447 // Proc-macro crates only export proc-macro items, which are looked
448 // up using `proc_macro_data`
449 if self.is_proc_macro {
453 self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor());
456 fn encode_def_path_table(&mut self) {
457 let table = self.tcx.resolutions(()).definitions.def_path_table();
458 if self.is_proc_macro {
459 for def_index in std::iter::once(CRATE_DEF_INDEX)
460 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
462 let def_key = self.lazy(table.def_key(def_index));
463 let def_path_hash = self.lazy(table.def_path_hash(def_index));
464 self.tables.def_keys.set(def_index, def_key);
465 self.tables.def_path_hashes.set(def_index, def_path_hash);
468 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
469 let def_key = self.lazy(def_key);
470 let def_path_hash = self.lazy(def_path_hash);
471 self.tables.def_keys.set(def_index, def_key);
472 self.tables.def_path_hashes.set(def_index, def_path_hash);
477 fn encode_def_path_hash_map(&mut self) -> Lazy<DefPathHashMapRef<'tcx>> {
478 self.lazy(DefPathHashMapRef::BorrowedFromTcx(
479 self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(),
483 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
484 let source_map = self.tcx.sess.source_map();
485 let all_source_files = source_map.files();
487 // By replacing the `Option` with `None`, we ensure that we can't
488 // accidentally serialize any more `Span`s after the source map encoding
490 let required_source_files = self.required_source_files.take().unwrap();
492 let adapted = all_source_files
495 .filter(|(idx, source_file)| {
496 // Only serialize `SourceFile`s that were used
497 // during the encoding of a `Span`
498 required_source_files.contains(*idx) &&
499 // Don't serialize imported `SourceFile`s, unless
500 // we're in a proc-macro crate.
501 (!source_file.is_imported() || self.is_proc_macro)
503 .map(|(_, source_file)| {
504 let mut adapted = match source_file.name {
505 FileName::Real(ref realname) => {
506 let mut adapted = (**source_file).clone();
507 adapted.name = FileName::Real(match realname {
508 RealFileName::LocalPath(path_to_file) => {
509 // Prepend path of working directory onto potentially
510 // relative paths, because they could become relative
511 // to a wrong directory.
512 // We include `working_dir` as part of the crate hash,
513 // so it's okay for us to use it as part of the encoded
515 let working_dir = &self.tcx.sess.opts.working_dir;
517 RealFileName::LocalPath(absolute) => {
518 // Although neither working_dir or the file name were subject
519 // to path remapping, the concatenation between the two may
520 // be. Hence we need to do a remapping here.
521 let joined = Path::new(absolute).join(path_to_file);
522 let (joined, remapped) =
523 source_map.path_mapping().map_prefix(joined);
525 RealFileName::Remapped {
527 virtual_name: joined,
530 RealFileName::LocalPath(joined)
533 RealFileName::Remapped { local_path: _, virtual_name } => {
534 // If working_dir has been remapped, then we emit
535 // Remapped variant as the expanded path won't be valid
536 RealFileName::Remapped {
538 virtual_name: Path::new(virtual_name)
544 RealFileName::Remapped { local_path: _, virtual_name } => {
545 RealFileName::Remapped {
546 // We do not want any local path to be exported into metadata
548 virtual_name: virtual_name.clone(),
552 adapted.name_hash = {
553 let mut hasher: StableHasher = StableHasher::new();
554 adapted.name.hash(&mut hasher);
555 hasher.finish::<u128>()
560 // expanded code, not from a file
561 _ => source_file.clone(),
564 // We're serializing this `SourceFile` into our crate metadata,
565 // so mark it as coming from this crate.
566 // This also ensures that we don't try to deserialize the
567 // `CrateNum` for a proc-macro dependency - since proc macro
568 // dependencies aren't loaded when we deserialize a proc-macro,
569 // trying to remap the `CrateNum` would fail.
570 if self.is_proc_macro {
571 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
575 .collect::<Vec<_>>();
577 self.lazy(adapted.iter().map(|rc| &**rc))
580 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
581 let mut i = self.position();
583 // Encode the crate deps
584 let crate_deps = self.encode_crate_deps();
585 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
586 let dep_bytes = self.position() - i;
588 // Encode the lib features.
590 let lib_features = self.encode_lib_features();
591 let lib_feature_bytes = self.position() - i;
593 // Encode the language items.
595 let lang_items = self.encode_lang_items();
596 let lang_items_missing = self.encode_lang_items_missing();
597 let lang_item_bytes = self.position() - i;
599 // Encode the diagnostic items.
601 let diagnostic_items = self.encode_diagnostic_items();
602 let diagnostic_item_bytes = self.position() - i;
604 // Encode the native libraries used
606 let native_libraries = self.encode_native_libraries();
607 let native_lib_bytes = self.position() - i;
609 let foreign_modules = self.encode_foreign_modules();
611 // Encode DefPathTable
613 self.encode_def_path_table();
614 let def_path_table_bytes = self.position() - i;
616 // Encode the def IDs of traits, for rustdoc and diagnostics.
618 let traits = self.encode_traits();
619 let traits_bytes = self.position() - i;
621 // Encode the def IDs of impls, for coherence checking.
623 let impls = self.encode_impls();
624 let impls_bytes = self.position() - i;
631 let mir_bytes = self.position() - i;
635 self.encode_def_ids();
636 self.encode_info_for_items();
637 let item_bytes = self.position() - i;
639 // Encode the allocation index
640 let interpret_alloc_index = {
641 let mut interpret_alloc_index = Vec::new();
643 trace!("beginning to encode alloc ids");
645 let new_n = self.interpret_allocs.len();
646 // if we have found new ids, serialize those, too
651 trace!("encoding {} further alloc ids", new_n - n);
652 for idx in n..new_n {
653 let id = self.interpret_allocs[idx];
654 let pos = self.position() as u32;
655 interpret_alloc_index.push(pos);
656 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
660 self.lazy(interpret_alloc_index)
663 // Encode the proc macro data. This affects 'tables',
664 // so we need to do this before we encode the tables
666 let proc_macro_data = self.encode_proc_macros();
667 let proc_macro_data_bytes = self.position() - i;
670 let tables = self.tables.encode(&mut self.opaque);
671 let tables_bytes = self.position() - i;
673 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
674 // this as late as possible to give the prefetching as much time as possible to complete.
676 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
677 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
678 let exported_symbols_bytes = self.position() - i;
680 // Encode the hygiene data,
681 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
682 // of encoding other items (e.g. `optimized_mir`) may cause us to load
683 // data from the incremental cache. If this causes us to deserialize a `Span`,
684 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
685 // Therefore, we need to encode the hygiene data last to ensure that we encode
686 // any `SyntaxContext`s that might be used.
688 let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene();
689 let hygiene_bytes = self.position() - i;
692 let def_path_hash_map = self.encode_def_path_hash_map();
693 let def_path_hash_map_bytes = self.position() - i;
695 // Encode source_map. This needs to be done last,
696 // since encoding `Span`s tells us which `SourceFiles` we actually
699 let source_map = self.encode_source_map();
700 let source_map_bytes = self.position() - i;
702 let attrs = tcx.hir().krate_attrs();
703 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
705 let root = self.lazy(CrateRoot {
706 name: tcx.crate_name(LOCAL_CRATE),
707 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
708 triple: tcx.sess.opts.target_triple.clone(),
709 hash: tcx.crate_hash(LOCAL_CRATE),
710 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
711 panic_strategy: tcx.sess.panic_strategy(),
712 panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop,
713 edition: tcx.sess.edition(),
714 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
715 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
716 has_default_lib_allocator,
718 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
719 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
720 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
721 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
722 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
723 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
724 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
727 dylib_dependency_formats,
738 interpret_alloc_index,
746 let total_bytes = self.position();
748 if tcx.sess.meta_stats() {
749 let mut zero_bytes = 0;
750 for e in self.opaque.data.iter() {
756 eprintln!("metadata stats:");
757 eprintln!(" dep bytes: {}", dep_bytes);
758 eprintln!(" lib feature bytes: {}", lib_feature_bytes);
759 eprintln!(" lang item bytes: {}", lang_item_bytes);
760 eprintln!(" diagnostic item bytes: {}", diagnostic_item_bytes);
761 eprintln!(" native bytes: {}", native_lib_bytes);
762 eprintln!(" source_map bytes: {}", source_map_bytes);
763 eprintln!(" traits bytes: {}", traits_bytes);
764 eprintln!(" impls bytes: {}", impls_bytes);
765 eprintln!(" exp. symbols bytes: {}", exported_symbols_bytes);
766 eprintln!(" def-path table bytes: {}", def_path_table_bytes);
767 eprintln!(" def-path hashes bytes: {}", def_path_hash_map_bytes);
768 eprintln!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
769 eprintln!(" mir bytes: {}", mir_bytes);
770 eprintln!(" item bytes: {}", item_bytes);
771 eprintln!(" table bytes: {}", tables_bytes);
772 eprintln!(" hygiene bytes: {}", hygiene_bytes);
773 eprintln!(" zero bytes: {}", zero_bytes);
774 eprintln!(" total bytes: {}", total_bytes);
781 fn should_encode_visibility(def_kind: DefKind) -> bool {
791 | DefKind::TraitAlias
798 | DefKind::AssocConst
801 | DefKind::ForeignMod
804 | DefKind::Field => true,
806 | DefKind::ConstParam
807 | DefKind::LifetimeParam
809 | DefKind::InlineConst
813 | DefKind::ExternCrate => false,
817 fn should_encode_stability(def_kind: DefKind) -> bool {
826 | DefKind::AssocConst
828 | DefKind::ConstParam
832 | DefKind::ForeignMod
839 | DefKind::TraitAlias
841 | DefKind::ForeignTy => true,
843 | DefKind::LifetimeParam
845 | DefKind::InlineConst
849 | DefKind::ExternCrate => false,
853 /// Whether we should encode MIR.
855 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
856 /// We want to avoid this work when not required. Therefore:
857 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
858 /// - we skip `optimized_mir` for check runs.
860 /// Return a pair, resp. for CTFE and for LLVM.
861 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
862 match tcx.def_kind(def_id) {
864 DefKind::Ctor(_, _) => {
865 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
866 || tcx.sess.opts.debugging_opts.always_encode_mir;
871 | DefKind::InlineConst
872 | DefKind::AssocConst
874 | DefKind::Const => (true, false),
875 // Full-fledged functions
876 DefKind::AssocFn | DefKind::Fn => {
877 let generics = tcx.generics_of(def_id);
878 let needs_inline = (generics.requires_monomorphization(tcx)
879 || tcx.codegen_fn_attrs(def_id).requests_inline())
880 && tcx.sess.opts.output_types.should_codegen();
881 // The function has a `const` modifier or is annotated with `default_method_body_is_const`.
882 let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id())
883 || tcx.has_attr(def_id.to_def_id(), sym::default_method_body_is_const);
884 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
885 (is_const_fn, needs_inline || always_encode_mir)
887 // Closures can't be const fn.
888 DefKind::Closure => {
889 let generics = tcx.generics_of(def_id);
890 let needs_inline = (generics.requires_monomorphization(tcx)
891 || tcx.codegen_fn_attrs(def_id).requests_inline())
892 && tcx.sess.opts.output_types.should_codegen();
893 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
894 (false, needs_inline || always_encode_mir)
896 // Generators require optimized MIR to compute layout.
897 DefKind::Generator => (false, true),
898 // The others don't have MIR.
903 fn should_encode_variances(def_kind: DefKind) -> bool {
911 | DefKind::AssocFn => true,
915 | DefKind::AssocConst
917 | DefKind::ConstParam
920 | DefKind::ForeignMod
925 | DefKind::TraitAlias
929 | DefKind::LifetimeParam
931 | DefKind::InlineConst
935 | DefKind::ExternCrate => false,
939 fn should_encode_generics(def_kind: DefKind) -> bool {
948 | DefKind::TraitAlias
955 | DefKind::AssocConst
957 | DefKind::InlineConst
963 | DefKind::Generator => true,
965 | DefKind::ForeignMod
966 | DefKind::ConstParam
969 | DefKind::LifetimeParam
971 | DefKind::ExternCrate => false,
975 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
976 fn encode_def_ids(&mut self) {
977 if self.is_proc_macro {
982 for local_id in hir.iter_local_def_id() {
983 let def_id = local_id.to_def_id();
984 let def_kind = tcx.opt_def_kind(local_id);
985 let Some(def_kind) = def_kind else { continue };
986 record!(self.tables.opt_def_kind[def_id] <- def_kind);
987 record!(self.tables.def_span[def_id] <- tcx.def_span(def_id));
988 record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id));
989 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
990 if should_encode_visibility(def_kind) {
991 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
993 if should_encode_stability(def_kind) {
994 self.encode_stability(def_id);
995 self.encode_const_stability(def_id);
996 self.encode_deprecation(def_id);
998 if should_encode_variances(def_kind) {
999 let v = self.tcx.variances_of(def_id);
1000 record!(self.tables.variances_of[def_id] <- v);
1002 if should_encode_generics(def_kind) {
1003 let g = tcx.generics_of(def_id);
1004 record!(self.tables.generics_of[def_id] <- g);
1005 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1006 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1007 if !inferred_outlives.is_empty() {
1008 record!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1011 if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1012 record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id));
1015 let inherent_impls = tcx.crate_inherent_impls(());
1016 for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
1017 if implementations.is_empty() {
1020 record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1021 assert!(def_id.is_local());
1027 fn encode_item_type(&mut self, def_id: DefId) {
1028 debug!("EncodeContext::encode_item_type({:?})", def_id);
1029 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1032 fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
1034 let variant = &def.variants[index];
1035 let def_id = variant.def_id;
1036 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1038 let data = VariantData {
1039 ctor_kind: variant.ctor_kind,
1040 discr: variant.discr,
1041 ctor: variant.ctor_def_id.map(|did| did.index),
1042 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1045 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1046 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1047 assert!(f.did.is_local());
1050 self.encode_ident_span(def_id, variant.ident(tcx));
1051 self.encode_item_type(def_id);
1052 if variant.ctor_kind == CtorKind::Fn {
1053 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1054 if let Some(ctor_def_id) = variant.ctor_def_id {
1055 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1060 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
1062 let variant = &def.variants[index];
1063 let def_id = variant.ctor_def_id.unwrap();
1064 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1066 // FIXME(eddyb) encode only the `CtorKind` for constructors.
1067 let data = VariantData {
1068 ctor_kind: variant.ctor_kind,
1069 discr: variant.discr,
1070 ctor: Some(def_id.index),
1071 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1074 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1075 self.encode_item_type(def_id);
1076 if variant.ctor_kind == CtorKind::Fn {
1077 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1081 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1083 let def_id = local_def_id.to_def_id();
1084 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1086 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1087 // only ever get called for the crate root. We still want to encode
1088 // the crate root for consistency with other crates (some of the resolver
1089 // code uses it). However, we skip encoding anything relating to child
1090 // items - we encode information about proc-macros later on.
1091 let reexports = if !self.is_proc_macro {
1092 match tcx.module_reexports(local_def_id) {
1093 Some(exports) => self.lazy(exports),
1100 record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports));
1101 if self.is_proc_macro {
1102 // Encode this here because we don't do it in encode_def_ids.
1103 record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1105 let direct_children = md.item_ids.iter().map(|item_id| item_id.def_id.local_def_index);
1106 // Foreign items are planted into their parent modules from name resolution point of view.
1108 let foreign_item_children = md
1111 .filter_map(|item_id| match tcx.hir().item(*item_id).kind {
1112 hir::ItemKind::ForeignMod { items, .. } => {
1113 Some(items.iter().map(|fi_ref| fi_ref.id.def_id.local_def_index))
1119 record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children));
1125 adt_def: &ty::AdtDef,
1126 variant_index: VariantIdx,
1129 let variant = &adt_def.variants[variant_index];
1130 let field = &variant.fields[field_index];
1132 let def_id = field.did;
1133 debug!("EncodeContext::encode_field({:?})", def_id);
1135 record!(self.tables.kind[def_id] <- EntryKind::Field);
1136 self.encode_ident_span(def_id, field.ident(self.tcx));
1137 self.encode_item_type(def_id);
1140 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
1141 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1143 let variant = adt_def.non_enum_variant();
1145 let data = VariantData {
1146 ctor_kind: variant.ctor_kind,
1147 discr: variant.discr,
1148 ctor: Some(def_id.index),
1149 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1152 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
1153 self.encode_item_type(def_id);
1154 if variant.ctor_kind == CtorKind::Fn {
1155 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1159 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1160 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1161 let bounds = self.tcx.explicit_item_bounds(def_id);
1162 if !bounds.is_empty() {
1163 record!(self.tables.explicit_item_bounds[def_id] <- bounds);
1167 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1168 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1171 let ast_item = tcx.hir().expect_trait_item(def_id.expect_local());
1172 let trait_item = tcx.associated_item(def_id);
1174 let container = match trait_item.defaultness {
1175 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
1176 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
1177 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
1180 match trait_item.kind {
1181 ty::AssocKind::Const => {
1182 let rendered = rustc_hir_pretty::to_string(
1183 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
1184 |s| s.print_trait_item(ast_item),
1187 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(container));
1188 record!(self.tables.mir_const_qualif[def_id] <- mir::ConstQualifs::default());
1189 record!(self.tables.rendered_const[def_id] <- rendered);
1191 ty::AssocKind::Fn => {
1192 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
1194 hir::TraitFn::Required(ref names) => {
1195 record!(self.tables.fn_arg_names[def_id] <- *names)
1197 hir::TraitFn::Provided(body) => {
1198 record!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body))
1201 record!(self.tables.asyncness[def_id] <- m_sig.header.asyncness);
1202 FnData { constness: hir::Constness::NotConst }
1206 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1209 has_self: trait_item.fn_has_self_parameter,
1212 ty::AssocKind::Type => {
1213 self.encode_explicit_item_bounds(def_id);
1214 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1217 self.encode_ident_span(def_id, ast_item.ident);
1218 match trait_item.kind {
1219 ty::AssocKind::Const | ty::AssocKind::Fn => {
1220 self.encode_item_type(def_id);
1222 ty::AssocKind::Type => {
1223 if trait_item.defaultness.has_value() {
1224 self.encode_item_type(def_id);
1228 if trait_item.kind == ty::AssocKind::Fn {
1229 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1233 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1234 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1237 let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local());
1238 let impl_item = self.tcx.associated_item(def_id);
1240 let container = match impl_item.defaultness {
1241 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1242 hir::Defaultness::Final => AssocContainer::ImplFinal,
1243 hir::Defaultness::Default { has_value: false } => {
1244 span_bug!(ast_item.span, "impl items always have values (currently)")
1248 match impl_item.kind {
1249 ty::AssocKind::Const => {
1250 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1251 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1252 let const_data = self.encode_rendered_const_for_body(body_id);
1254 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(container));
1255 record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1256 record!(self.tables.rendered_const[def_id] <- const_data);
1261 ty::AssocKind::Fn => {
1262 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1263 record!(self.tables.asyncness[def_id] <- sig.header.asyncness);
1264 record!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1266 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1267 constness: if self.tcx.is_const_fn_raw(def_id) {
1268 hir::Constness::Const
1270 hir::Constness::NotConst
1276 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1279 has_self: impl_item.fn_has_self_parameter,
1282 ty::AssocKind::Type => {
1283 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1286 self.encode_ident_span(def_id, impl_item.ident(self.tcx));
1287 self.encode_item_type(def_id);
1288 if let Some(trait_item_def_id) = impl_item.trait_item_def_id {
1289 record!(self.tables.trait_item_def_id[def_id] <- trait_item_def_id);
1291 if impl_item.kind == ty::AssocKind::Fn {
1292 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1296 fn encode_mir(&mut self) {
1297 if self.is_proc_macro {
1301 let keys_and_jobs = self
1305 .filter_map(|&def_id| {
1306 let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id);
1307 if encode_const || encode_opt {
1308 Some((def_id, encode_const, encode_opt))
1313 .collect::<Vec<_>>();
1314 for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() {
1315 debug_assert!(encode_const || encode_opt);
1317 debug!("EntryBuilder::encode_mir({:?})", def_id);
1319 record!(self.tables.optimized_mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1322 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id));
1324 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1325 let abstract_const = self.tcx.thir_abstract_const(def_id);
1326 if let Ok(Some(abstract_const)) = abstract_const {
1327 record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1330 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1333 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1334 let unused = self.tcx.unused_generic_params(instance);
1335 if !unused.is_empty() {
1336 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1341 fn encode_stability(&mut self, def_id: DefId) {
1342 debug!("EncodeContext::encode_stability({:?})", def_id);
1344 // The query lookup can take a measurable amount of time in crates with many items. Check if
1345 // the stability attributes are even enabled before using their queries.
1346 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1347 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1348 record!(self.tables.lookup_stability[def_id] <- stab)
1353 fn encode_const_stability(&mut self, def_id: DefId) {
1354 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1356 // The query lookup can take a measurable amount of time in crates with many items. Check if
1357 // the stability attributes are even enabled before using their queries.
1358 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1359 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1360 record!(self.tables.lookup_const_stability[def_id] <- stab)
1365 fn encode_deprecation(&mut self, def_id: DefId) {
1366 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1367 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1368 record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1372 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> String {
1373 let hir = self.tcx.hir();
1374 let body = hir.body(body_id);
1375 rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1376 s.print_expr(&body.value)
1380 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1383 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1385 self.encode_ident_span(def_id, item.ident);
1387 let entry_kind = match item.kind {
1388 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1389 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1390 hir::ItemKind::Const(_, body_id) => {
1391 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1392 let const_data = self.encode_rendered_const_for_body(body_id);
1393 record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1394 record!(self.tables.rendered_const[def_id] <- const_data);
1397 hir::ItemKind::Fn(ref sig, .., body) => {
1398 record!(self.tables.asyncness[def_id] <- sig.header.asyncness);
1399 record!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1400 let data = FnData { constness: sig.header.constness };
1402 EntryKind::Fn(self.lazy(data))
1404 hir::ItemKind::Macro(ref macro_def, _) => {
1405 EntryKind::MacroDef(self.lazy(&*macro_def.body), macro_def.macro_rules)
1407 hir::ItemKind::Mod(ref m) => {
1408 return self.encode_info_for_mod(item.def_id, m);
1410 hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1411 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1412 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1413 hir::ItemKind::OpaqueTy(..) => {
1414 self.encode_explicit_item_bounds(def_id);
1417 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1418 hir::ItemKind::Struct(ref struct_def, _) => {
1419 let adt_def = self.tcx.adt_def(def_id);
1420 let variant = adt_def.non_enum_variant();
1422 // Encode def_ids for each field and method
1423 // for methods, write all the stuff get_trait_method
1425 let ctor = struct_def
1427 .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1430 self.lazy(VariantData {
1431 ctor_kind: variant.ctor_kind,
1432 discr: variant.discr,
1434 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1439 hir::ItemKind::Union(..) => {
1440 let adt_def = self.tcx.adt_def(def_id);
1441 let variant = adt_def.non_enum_variant();
1444 self.lazy(VariantData {
1445 ctor_kind: variant.ctor_kind,
1446 discr: variant.discr,
1448 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1453 hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1454 record!(self.tables.impl_defaultness[def_id] <- defaultness);
1455 record!(self.tables.impl_constness[def_id] <- constness);
1457 let trait_ref = self.tcx.impl_trait_ref(def_id);
1458 if let Some(trait_ref) = trait_ref {
1459 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1460 if let Some(mut an) = trait_def.ancestors(self.tcx, def_id).ok() {
1461 if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
1462 record!(self.tables.impl_parent[def_id] <- parent);
1466 // if this is an impl of `CoerceUnsized`, create its
1467 // "unsized info", else just store None
1468 if Some(trait_ref.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1469 let coerce_unsized_info =
1470 self.tcx.at(item.span).coerce_unsized_info(def_id);
1471 record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
1475 let polarity = self.tcx.impl_polarity(def_id);
1476 record!(self.tables.impl_polarity[def_id] <- polarity);
1480 hir::ItemKind::Trait(..) => {
1481 let trait_def = self.tcx.trait_def(def_id);
1482 let data = TraitData {
1483 unsafety: trait_def.unsafety,
1484 paren_sugar: trait_def.paren_sugar,
1485 has_auto_impl: self.tcx.trait_is_auto(def_id),
1486 is_marker: trait_def.is_marker,
1487 skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch,
1488 specialization_kind: trait_def.specialization_kind,
1489 must_implement_one_of: trait_def.must_implement_one_of.clone(),
1492 EntryKind::Trait(self.lazy(data))
1494 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1495 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1496 bug!("cannot encode info for item {:?}", item)
1499 record!(self.tables.kind[def_id] <- entry_kind);
1500 // FIXME(eddyb) there should be a nicer way to do this.
1502 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1503 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1504 assert!(v.def_id.is_local());
1508 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1509 record!(self.tables.children[def_id] <-
1510 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1511 assert!(f.did.is_local());
1516 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1517 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1518 record!(self.tables.children[def_id] <-
1519 associated_item_def_ids.iter().map(|&def_id| {
1520 assert!(def_id.is_local());
1528 hir::ItemKind::Static(..)
1529 | hir::ItemKind::Const(..)
1530 | hir::ItemKind::Fn(..)
1531 | hir::ItemKind::TyAlias(..)
1532 | hir::ItemKind::OpaqueTy(..)
1533 | hir::ItemKind::Enum(..)
1534 | hir::ItemKind::Struct(..)
1535 | hir::ItemKind::Union(..)
1536 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1539 if let hir::ItemKind::Fn(..) = item.kind {
1540 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1542 if let hir::ItemKind::Impl { .. } = item.kind {
1543 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1544 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1549 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1550 record!(self.tables.kind[def_id] <- kind);
1552 self.encode_item_type(def_id);
1556 fn encode_info_for_closure(&mut self, hir_id: hir::HirId) {
1557 let def_id = self.tcx.hir().local_def_id(hir_id);
1558 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1560 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1561 // including on the signature, which is inferred in `typeck.
1562 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1565 ty::Generator(..) => {
1566 let data = self.tcx.generator_kind(def_id).unwrap();
1567 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator);
1568 record!(self.tables.generator_kind[def_id.to_def_id()] <- data);
1571 ty::Closure(..) => {
1572 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1575 _ => bug!("closure that is neither generator nor closure"),
1577 self.encode_item_type(def_id.to_def_id());
1578 if let ty::Closure(def_id, substs) = *ty.kind() {
1579 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1583 fn encode_info_for_anon_const(&mut self, id: hir::HirId) {
1584 let def_id = self.tcx.hir().local_def_id(id);
1585 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1586 let body_id = self.tcx.hir().body_owned_by(id);
1587 let const_data = self.encode_rendered_const_for_body(body_id);
1588 let qualifs = self.tcx.mir_const_qualif(def_id);
1590 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst);
1591 record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1592 record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1593 self.encode_item_type(def_id.to_def_id());
1596 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1597 empty_proc_macro!(self);
1598 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1599 self.lazy(used_libraries.iter())
1602 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1603 empty_proc_macro!(self);
1604 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1605 self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1608 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1609 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1610 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1611 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1613 let _: Result<(), !> = self.hygiene_ctxt.encode(
1614 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1615 |(this, syntax_contexts, _, _), index, ctxt_data| {
1616 syntax_contexts.set(index, this.lazy(ctxt_data));
1619 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1620 if let Some(index) = index.as_local() {
1621 expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1622 expn_hash_table.set(index.as_raw(), this.lazy(hash));
1629 syntax_contexts.encode(&mut self.opaque),
1630 expn_data_table.encode(&mut self.opaque),
1631 expn_hash_table.encode(&mut self.opaque),
1635 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1636 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1639 let hir = tcx.hir();
1641 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1642 let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX));
1644 self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1645 let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1646 for (i, span) in spans.into_iter().enumerate() {
1647 let span = self.lazy(span);
1648 self.tables.proc_macro_quoted_spans.set(i, span);
1651 record!(self.tables.opt_def_kind[LOCAL_CRATE.as_def_id()] <- DefKind::Mod);
1652 record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1653 record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id()));
1654 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1655 if let Some(stability) = stability {
1656 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1658 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1660 // Normally, this information is encoded when we walk the items
1661 // defined in this crate. However, we skip doing that for proc-macro crates,
1662 // so we manually encode just the information that we need
1663 for &proc_macro in &tcx.resolutions(()).proc_macros {
1664 let id = proc_macro;
1665 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1666 let mut name = hir.name(proc_macro);
1667 let span = hir.span(proc_macro);
1668 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1669 // so downstream crates need access to them.
1670 let attrs = hir.attrs(proc_macro);
1671 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1673 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1675 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1676 // This unwrap chain should have been checked by the proc-macro harness.
1677 name = attr.meta_item_list().unwrap()[0]
1685 bug!("Unknown proc-macro type for item {:?}", id);
1688 let mut def_key = self.tcx.hir().def_key(id);
1689 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1691 let def_id = id.to_def_id();
1692 record!(self.tables.opt_def_kind[def_id] <- DefKind::Macro(macro_kind));
1693 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1694 record!(self.tables.attributes[def_id] <- attrs);
1695 record!(self.tables.def_keys[def_id] <- def_key);
1696 record!(self.tables.def_ident_span[def_id] <- span);
1697 record!(self.tables.def_span[def_id] <- span);
1698 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1699 if let Some(stability) = stability {
1700 record!(self.tables.lookup_stability[def_id] <- stability);
1704 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1710 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1711 empty_proc_macro!(self);
1718 let dep = CrateDep {
1719 name: self.tcx.crate_name(cnum),
1720 hash: self.tcx.crate_hash(cnum),
1721 host_hash: self.tcx.crate_host_hash(cnum),
1722 kind: self.tcx.dep_kind(cnum),
1723 extra_filename: self.tcx.extra_filename(cnum).clone(),
1727 .collect::<Vec<_>>();
1730 // Sanity-check the crate numbers
1731 let mut expected_cnum = 1;
1732 for &(n, _) in &deps {
1733 assert_eq!(n, CrateNum::new(expected_cnum));
1738 // We're just going to write a list of crate 'name-hash-version's, with
1739 // the assumption that they are numbered 1 to n.
1740 // FIXME (#2166): This is not nearly enough to support correct versioning
1741 // but is enough to get transitive crate dependencies working.
1742 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1745 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1746 empty_proc_macro!(self);
1748 let lib_features = tcx.lib_features(());
1749 self.lazy(lib_features.to_vec())
1752 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1753 empty_proc_macro!(self);
1755 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1756 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1759 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1760 empty_proc_macro!(self);
1762 let lang_items = tcx.lang_items();
1763 let lang_items = lang_items.items().iter();
1764 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1765 if let Some(def_id) = opt_def_id {
1766 if def_id.is_local() {
1767 return Some((def_id.index, i));
1774 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1775 empty_proc_macro!(self);
1777 self.lazy(&tcx.lang_items().missing)
1780 fn encode_traits(&mut self) -> Lazy<[DefIndex]> {
1781 empty_proc_macro!(self);
1782 self.lazy(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index))
1785 /// Encodes an index, mapping each trait to its (local) implementations.
1786 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1787 debug!("EncodeContext::encode_traits_and_impls()");
1788 empty_proc_macro!(self);
1790 let mut visitor = ImplsVisitor { tcx, impls: FxHashMap::default() };
1791 tcx.hir().visit_all_item_likes(&mut visitor);
1793 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1795 // Bring everything into deterministic order for hashing
1796 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1798 let all_impls: Vec<_> = all_impls
1800 .map(|(trait_def_id, mut impls)| {
1801 // Bring everything into deterministic order for hashing
1802 impls.sort_by_cached_key(|&(index, _)| {
1803 tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1807 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1808 impls: self.lazy(&impls),
1813 self.lazy(&all_impls)
1816 // Encodes all symbols exported from this crate into the metadata.
1818 // This pass is seeded off the reachability list calculated in the
1819 // middle::reachable module but filters out items that either don't have a
1820 // symbol associated with them (they weren't translated) or if they're an FFI
1821 // definition (as that's not defined in this crate).
1822 fn encode_exported_symbols(
1824 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1825 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1826 empty_proc_macro!(self);
1827 // The metadata symbol name is special. It should not show up in
1828 // downstream crates.
1829 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1834 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1835 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1842 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1843 empty_proc_macro!(self);
1844 let formats = self.tcx.dependency_formats(());
1845 for (ty, arr) in formats.iter() {
1846 if *ty != CrateType::Dylib {
1849 return self.lazy(arr.iter().map(|slot| match *slot {
1850 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1852 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1853 Linkage::Static => Some(LinkagePreference::RequireStatic),
1859 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1862 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1865 hir::ForeignItemKind::Fn(_, ref names, _) => {
1866 record!(self.tables.asyncness[def_id] <- hir::IsAsync::NotAsync);
1867 record!(self.tables.fn_arg_names[def_id] <- *names);
1869 constness: if self.tcx.is_const_fn_raw(def_id) {
1870 hir::Constness::Const
1872 hir::Constness::NotConst
1875 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn(self.lazy(data)));
1877 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => {
1878 record!(self.tables.kind[def_id] <- EntryKind::ForeignMutStatic);
1880 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => {
1881 record!(self.tables.kind[def_id] <- EntryKind::ForeignImmStatic);
1883 hir::ForeignItemKind::Type => {
1884 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
1887 self.encode_ident_span(def_id, nitem.ident);
1888 self.encode_item_type(def_id);
1889 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1890 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1895 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1896 impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1897 type NestedFilter = nested_filter::OnlyBodies;
1899 fn nested_visit_map(&mut self) -> Self::Map {
1902 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1903 intravisit::walk_expr(self, ex);
1904 self.encode_info_for_expr(ex);
1906 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1907 intravisit::walk_anon_const(self, c);
1908 self.encode_info_for_anon_const(c.hir_id);
1910 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1911 intravisit::walk_item(self, item);
1913 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1914 _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
1916 self.encode_addl_info_for_item(item);
1918 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1919 intravisit::walk_foreign_item(self, ni);
1920 self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
1922 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1923 intravisit::walk_generics(self, generics);
1924 self.encode_info_for_generics(generics);
1928 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1929 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1930 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1931 for (field_index, _field) in variant.fields.iter().enumerate() {
1932 self.encode_field(adt_def, variant_index, field_index);
1937 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1938 for param in generics.params {
1939 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1941 GenericParamKind::Lifetime { .. } => continue,
1942 GenericParamKind::Type { default, .. } => {
1943 self.encode_info_for_generic_param(
1945 EntryKind::TypeParam,
1949 GenericParamKind::Const { ref default, .. } => {
1950 let def_id = def_id.to_def_id();
1951 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1952 if default.is_some() {
1953 record!(self.tables.const_param_default[def_id] <- self.tcx.const_param_default(def_id))
1960 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1961 if let hir::ExprKind::Closure(..) = expr.kind {
1962 self.encode_info_for_closure(expr.hir_id);
1966 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1967 record!(self.tables.def_ident_span[def_id] <- ident.span);
1970 /// In some cases, along with the item itself, we also
1971 /// encode some sub-items. Usually we want some info from the item
1972 /// so it's easier to do that here then to wait until we would encounter
1973 /// normally in the visitor walk.
1974 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1976 hir::ItemKind::Static(..)
1977 | hir::ItemKind::Const(..)
1978 | hir::ItemKind::Fn(..)
1979 | hir::ItemKind::Macro(..)
1980 | hir::ItemKind::Mod(..)
1981 | hir::ItemKind::ForeignMod { .. }
1982 | hir::ItemKind::GlobalAsm(..)
1983 | hir::ItemKind::ExternCrate(..)
1984 | hir::ItemKind::Use(..)
1985 | hir::ItemKind::TyAlias(..)
1986 | hir::ItemKind::OpaqueTy(..)
1987 | hir::ItemKind::TraitAlias(..) => {
1988 // no sub-item recording needed in these cases
1990 hir::ItemKind::Enum(..) => {
1991 let def = self.tcx.adt_def(item.def_id.to_def_id());
1992 self.encode_fields(def);
1994 for (i, variant) in def.variants.iter_enumerated() {
1995 self.encode_enum_variant_info(def, i);
1997 if let Some(_ctor_def_id) = variant.ctor_def_id {
1998 self.encode_enum_variant_ctor(def, i);
2002 hir::ItemKind::Struct(ref struct_def, _) => {
2003 let def = self.tcx.adt_def(item.def_id.to_def_id());
2004 self.encode_fields(def);
2006 // If the struct has a constructor, encode it.
2007 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
2008 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
2009 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
2012 hir::ItemKind::Union(..) => {
2013 let def = self.tcx.adt_def(item.def_id.to_def_id());
2014 self.encode_fields(def);
2016 hir::ItemKind::Impl { .. } => {
2017 for &trait_item_def_id in
2018 self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2020 self.encode_info_for_impl_item(trait_item_def_id);
2023 hir::ItemKind::Trait(..) => {
2024 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2026 self.encode_info_for_trait_item(item_def_id);
2033 struct ImplsVisitor<'tcx> {
2035 impls: FxHashMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>>,
2038 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> {
2039 fn visit_item(&mut self, item: &hir::Item<'_>) {
2041 hir::ItemKind::Impl(..) => {
2042 if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) {
2043 let simplified_self_ty = fast_reject::simplify_type(
2045 trait_ref.self_ty(),
2050 .entry(trait_ref.def_id)
2052 .push((item.def_id.local_def_index, simplified_self_ty));
2059 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
2061 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
2062 // handled in `visit_item` above
2065 fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
2068 /// Used to prefetch queries which will be needed later by metadata encoding.
2069 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2070 fn prefetch_mir(tcx: TyCtxt<'_>) {
2071 if !tcx.sess.opts.output_types.should_codegen() {
2072 // We won't emit MIR, so don't prefetch it.
2076 par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2077 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2080 tcx.ensure().mir_for_ctfe(def_id);
2083 tcx.ensure().optimized_mir(def_id);
2085 if encode_opt || encode_const {
2086 tcx.ensure().promoted_mir(def_id);
2091 // NOTE(eddyb) The following comment was preserved for posterity, even
2092 // though it's no longer relevant as EBML (which uses nested & tagged
2093 // "documents") was replaced with a scheme that can't go out of bounds.
2095 // And here we run into yet another obscure archive bug: in which metadata
2096 // loaded from archives may have trailing garbage bytes. Awhile back one of
2097 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2098 // and opt) by having ebml generate an out-of-bounds panic when looking at
2101 // Upon investigation it turned out that the metadata file inside of an rlib
2102 // (and ar archive) was being corrupted. Some compilations would generate a
2103 // metadata file which would end in a few extra bytes, while other
2104 // compilations would not have these extra bytes appended to the end. These
2105 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2106 // being interpreted causing the out-of-bounds.
2108 // The root cause of why these extra bytes were appearing was never
2109 // discovered, and in the meantime the solution we're employing is to insert
2110 // the length of the metadata to the start of the metadata. Later on this
2111 // will allow us to slice the metadata to the precise length that we just
2112 // generated regardless of trailing bytes that end up in it.
2114 #[derive(Encodable, Decodable)]
2115 pub struct EncodedMetadata {
2119 impl EncodedMetadata {
2121 pub fn new() -> EncodedMetadata {
2122 EncodedMetadata { raw_data: Vec::new() }
2126 pub fn raw_data(&self) -> &[u8] {
2131 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2132 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2134 // Since encoding metadata is not in a query, and nothing is cached,
2135 // there's no need to do dep-graph tracking for any of it.
2136 tcx.dep_graph.assert_ignored();
2139 || encode_metadata_impl(tcx),
2141 if tcx.sess.threads() == 1 {
2144 // Prefetch some queries used by metadata encoding.
2145 // This is not necessary for correctness, but is only done for performance reasons.
2146 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2147 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2153 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2154 let mut encoder = opaque::Encoder::new(vec![]);
2155 encoder.emit_raw_bytes(METADATA_HEADER).unwrap();
2157 // Will be filled with the root position after encoding everything.
2158 encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap();
2160 let source_map_files = tcx.sess.source_map().files();
2161 let source_file_cache = (source_map_files[0].clone(), 0);
2162 let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2163 drop(source_map_files);
2165 let hygiene_ctxt = HygieneEncodeContext::default();
2167 let mut ecx = EncodeContext {
2170 feat: tcx.features(),
2171 tables: Default::default(),
2172 lazy_state: LazyState::NoNode,
2173 type_shorthands: Default::default(),
2174 predicate_shorthands: Default::default(),
2176 interpret_allocs: Default::default(),
2177 required_source_files,
2178 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2179 hygiene_ctxt: &hygiene_ctxt,
2182 // Encode the rustc version string in a predictable location.
2183 rustc_version().encode(&mut ecx).unwrap();
2185 // Encode all the entries and extra information in the crate,
2186 // culminating in the `CrateRoot` which points to all of it.
2187 let root = ecx.encode_crate_root();
2189 let mut result = ecx.opaque.into_inner();
2191 // Encode the root position.
2192 let header = METADATA_HEADER.len();
2193 let pos = root.position.get();
2194 result[header + 0] = (pos >> 24) as u8;
2195 result[header + 1] = (pos >> 16) as u8;
2196 result[header + 2] = (pos >> 8) as u8;
2197 result[header + 3] = (pos >> 0) as u8;
2199 // Record metadata size for self-profiling
2200 tcx.prof.artifact_size("crate_metadata", "crate_metadata", result.len() as u64);
2202 EncodedMetadata { raw_data: result }
2205 pub fn provide(providers: &mut Providers) {
2206 *providers = Providers {
2207 traits_in_crate: |tcx, cnum| {
2208 assert_eq!(cnum, LOCAL_CRATE);
2211 struct TraitsVisitor {
2214 impl ItemLikeVisitor<'_> for TraitsVisitor {
2215 fn visit_item(&mut self, item: &hir::Item<'_>) {
2216 if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind {
2217 self.traits.push(item.def_id.to_def_id());
2220 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
2221 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {}
2222 fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {}
2225 let mut visitor = TraitsVisitor::default();
2226 tcx.hir().visit_all_item_likes(&mut visitor);
2227 // Bring everything into deterministic order.
2228 visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
2229 tcx.arena.alloc_slice(&visitor.traits)