1 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
2 use crate::rmeta::table::TableBuilder;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
7 use rustc_data_structures::memmap::{Mmap, MmapMut};
8 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
9 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
10 use rustc_data_structures::temp_dir::MaybeTempDir;
12 use rustc_hir::def::DefKind;
13 use rustc_hir::def_id::{
14 CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
16 use rustc_hir::definitions::DefPathData;
17 use rustc_hir::intravisit::{self, Visitor};
18 use rustc_hir::lang_items;
19 use rustc_hir::{AnonConst, GenericParamKind};
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, SymbolExportInfo,
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::fast_reject::{self, SimplifiedType, TreatParams};
29 use rustc_middle::ty::query::Providers;
30 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
31 use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder};
32 use rustc_session::config::CrateType;
33 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
34 use rustc_span::hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind};
35 use rustc_span::symbol::{sym, Symbol};
37 self, DebuggerVisualizerFile, ExternalSource, FileName, SourceFile, Span, SyntaxContext,
39 use rustc_target::abi::VariantIdx;
40 use std::borrow::Borrow;
41 use std::collections::hash_map::Entry;
43 use std::io::{Read, Seek, Write};
45 use std::num::NonZeroUsize;
46 use std::path::{Path, PathBuf};
47 use tracing::{debug, trace};
49 pub(super) struct EncodeContext<'a, 'tcx> {
50 opaque: opaque::FileEncoder,
52 feat: &'tcx rustc_feature::Features,
54 tables: TableBuilders,
56 lazy_state: LazyState,
57 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
58 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
60 interpret_allocs: FxIndexSet<interpret::AllocId>,
62 // This is used to speed up Span encoding.
63 // The `usize` is an index into the `MonotonicVec`
64 // that stores the `SourceFile`
65 source_file_cache: (Lrc<SourceFile>, usize),
66 // The indices (into the `SourceMap`'s `MonotonicVec`)
67 // of all of the `SourceFiles` that we need to serialize.
68 // When we serialize a `Span`, we insert the index of its
69 // `SourceFile` into the `FxIndexSet`.
70 // The order inside the `FxIndexSet` is used as on-disk
71 // order of `SourceFiles`, and encoded inside `Span`s.
72 required_source_files: Option<FxIndexSet<usize>>,
74 hygiene_ctxt: &'a HygieneEncodeContext,
75 symbol_table: FxHashMap<Symbol, usize>,
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 {
84 return LazyArray::empty();
89 macro_rules! encoder_methods {
90 ($($name:ident($ty:ty);)*) => {
91 $(fn $name(&mut self, value: $ty) {
92 self.opaque.$name(value)
97 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
118 emit_raw_bytes(&[u8]);
122 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
123 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
124 e.emit_lazy_distance(self.position);
128 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
129 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
130 e.emit_usize(self.num_elems);
131 if self.num_elems > 0 {
132 e.emit_lazy_distance(self.position)
137 impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
138 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
139 e.emit_usize(self.encoded_size);
140 e.emit_lazy_distance(self.position);
144 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
145 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
146 if *self != LOCAL_CRATE && s.is_proc_macro {
147 panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
149 s.emit_u32(self.as_u32());
153 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
154 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
155 s.emit_u32(self.as_u32());
159 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
160 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
161 s.emit_u32(self.as_u32());
165 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
166 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
167 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s);
171 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
172 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
173 if self.krate == LOCAL_CRATE {
174 // We will only write details for local expansions. Non-local expansions will fetch
175 // data from the corresponding crate's metadata.
176 // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
177 // metadata from proc-macro crates.
178 s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
180 self.krate.encode(s);
181 self.local_id.encode(s);
185 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
186 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
187 let span = self.data();
189 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
190 // since we don't load proc-macro dependencies during serialization.
191 // This means that any hygiene information from macros used *within*
192 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
193 // definition) will be lost.
195 // This can show up in two ways:
197 // 1. Any hygiene information associated with identifier of
198 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
199 // Since proc-macros can only be invoked from a different crate,
200 // real code should never need to care about this.
202 // 2. Using `Span::def_site` or `Span::mixed_site` will not
203 // include any hygiene information associated with the definition
204 // site. This means that a proc-macro cannot emit a `$crate`
205 // identifier which resolves to one of its dependencies,
206 // which also should never come up in practice.
208 // Additionally, this affects `Span::parent`, and any other
209 // span inspection APIs that would otherwise allow traversing
210 // the `SyntaxContexts` associated with a span.
212 // None of these user-visible effects should result in any
213 // cross-crate inconsistencies (getting one behavior in the same
214 // crate, and a different behavior in another crate) due to the
215 // limited surface that proc-macros can expose.
217 // IMPORTANT: If this is ever changed, be sure to update
218 // `rustc_span::hygiene::raw_encode_expn_id` to handle
219 // encoding `ExpnData` for proc-macro crates.
221 SyntaxContext::root().encode(s);
227 return TAG_PARTIAL_SPAN.encode(s);
230 // The Span infrastructure should make sure that this invariant holds:
231 debug_assert!(span.lo <= span.hi);
233 if !s.source_file_cache.0.contains(span.lo) {
234 let source_map = s.tcx.sess.source_map();
235 let source_file_index = source_map.lookup_source_file_idx(span.lo);
236 s.source_file_cache =
237 (source_map.files()[source_file_index].clone(), source_file_index);
239 let (ref source_file, source_file_index) = s.source_file_cache;
240 debug_assert!(source_file.contains(span.lo));
242 if !source_file.contains(span.hi) {
243 // Unfortunately, macro expansion still sometimes generates Spans
244 // that malformed in this way.
245 return TAG_PARTIAL_SPAN.encode(s);
248 // There are two possible cases here:
249 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
250 // crate we are writing metadata for. When the metadata for *this* crate gets
251 // deserialized, the deserializer will need to know which crate it originally came
252 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
253 // be deserialized after the rest of the span data, which tells the deserializer
254 // which crate contains the source map information.
255 // 2. This span comes from our own crate. No special handling is needed - we just
256 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
257 // our own source map information.
259 // If we're a proc-macro crate, we always treat this as a local `Span`.
260 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
261 // if we're a proc-macro crate.
262 // This allows us to avoid loading the dependencies of proc-macro crates: all of
263 // the information we need to decode `Span`s is stored in the proc-macro crate.
264 let (tag, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
265 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
266 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
267 // are relative to the source map information for the 'foreign' crate whose CrateNum
268 // we write into the metadata. This allows `imported_source_files` to binary
269 // search through the 'foreign' crate's source map information, using the
270 // deserialized 'lo' and 'hi' values directly.
272 // All of this logic ensures that the final result of deserialization is a 'normal'
273 // Span that can be used without any additional trouble.
274 let metadata_index = {
275 // Introduce a new scope so that we drop the 'lock()' temporary
276 match &*source_file.external_src.lock() {
277 ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
278 src => panic!("Unexpected external source {:?}", src),
282 (TAG_VALID_SPAN_FOREIGN, metadata_index)
284 // Record the fact that we need to encode the data for this `SourceFile`
286 s.required_source_files.as_mut().expect("Already encoded SourceMap!");
287 let (metadata_index, _) = source_files.insert_full(source_file_index);
288 let metadata_index: u32 =
289 metadata_index.try_into().expect("cannot export more than U32_MAX files");
291 (TAG_VALID_SPAN_LOCAL, metadata_index)
294 // Encode the start position relative to the file start, so we profit more from the
295 // variable-length integer encoding.
296 let lo = span.lo - source_file.start_pos;
298 // Encode length which is usually less than span.hi and profits more
299 // from the variable-length integer encoding that we use.
300 let len = span.hi - span.lo;
306 // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
307 metadata_index.encode(s);
309 if tag == TAG_VALID_SPAN_FOREIGN {
310 // This needs to be two lines to avoid holding the `s.source_file_cache`
311 // while calling `cnum.encode(s)`
312 let cnum = s.source_file_cache.0.cnum;
318 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Symbol {
319 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
320 // if symbol preinterned, emit tag and symbol index
321 if self.is_preinterned() {
322 s.opaque.emit_u8(SYMBOL_PREINTERNED);
323 s.opaque.emit_u32(self.as_u32());
325 // otherwise write it as string or as offset to it
326 match s.symbol_table.entry(*self) {
327 Entry::Vacant(o) => {
328 s.opaque.emit_u8(SYMBOL_STR);
329 let pos = s.opaque.position();
331 s.emit_str(self.as_str());
333 Entry::Occupied(o) => {
334 let x = o.get().clone();
335 s.emit_u8(SYMBOL_OFFSET);
343 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
344 const CLEAR_CROSS_CRATE: bool = true;
346 type I = TyCtxt<'tcx>;
348 fn position(&self) -> usize {
349 self.opaque.position()
352 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
353 &mut self.type_shorthands
356 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
357 &mut self.predicate_shorthands
360 fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
361 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
367 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
368 // normally need extra variables to avoid errors about multiple mutable borrows.
369 macro_rules! record {
370 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
373 let lazy = $self.lazy(value);
374 $self.$tables.$table.set($def_id.index, lazy);
379 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
380 // normally need extra variables to avoid errors about multiple mutable borrows.
381 macro_rules! record_array {
382 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
385 let lazy = $self.lazy_array(value);
386 $self.$tables.$table.set($def_id.index, lazy);
391 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
392 fn emit_lazy_distance(&mut self, position: NonZeroUsize) {
393 let pos = position.get();
394 let distance = match self.lazy_state {
395 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
396 LazyState::NodeStart(start) => {
397 let start = start.get();
398 assert!(pos <= start);
401 LazyState::Previous(last_pos) => {
403 last_pos <= position,
404 "make sure that the calls to `lazy*` \
405 are in the same order as the metadata fields",
407 position.get() - last_pos.get()
410 self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap());
411 self.emit_usize(distance);
414 fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
416 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
418 let pos = NonZeroUsize::new(self.position()).unwrap();
420 assert_eq!(self.lazy_state, LazyState::NoNode);
421 self.lazy_state = LazyState::NodeStart(pos);
422 value.borrow().encode(self);
423 self.lazy_state = LazyState::NoNode;
425 assert!(pos.get() <= self.position());
427 LazyValue::from_position(pos)
430 fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
435 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
437 let pos = NonZeroUsize::new(self.position()).unwrap();
439 assert_eq!(self.lazy_state, LazyState::NoNode);
440 self.lazy_state = LazyState::NodeStart(pos);
441 let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
442 self.lazy_state = LazyState::NoNode;
444 assert!(pos.get() <= self.position());
446 LazyArray::from_position_and_num_elems(pos, len)
449 fn encode_info_for_items(&mut self) {
450 self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
452 // Proc-macro crates only export proc-macro items, which are looked
453 // up using `proc_macro_data`
454 if self.is_proc_macro {
458 self.tcx.hir().visit_all_item_likes_in_crate(self);
461 fn encode_def_path_table(&mut self) {
462 let table = self.tcx.def_path_table();
463 if self.is_proc_macro {
464 for def_index in std::iter::once(CRATE_DEF_INDEX)
465 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
467 let def_key = self.lazy(table.def_key(def_index));
468 let def_path_hash = table.def_path_hash(def_index);
469 self.tables.def_keys.set(def_index, def_key);
470 self.tables.def_path_hashes.set(def_index, def_path_hash);
473 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
474 let def_key = self.lazy(def_key);
475 self.tables.def_keys.set(def_index, def_key);
476 self.tables.def_path_hashes.set(def_index, *def_path_hash);
481 fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
482 self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
485 fn encode_source_map(&mut self) -> LazyTable<u32, LazyValue<rustc_span::SourceFile>> {
486 let source_map = self.tcx.sess.source_map();
487 let all_source_files = source_map.files();
489 // By replacing the `Option` with `None`, we ensure that we can't
490 // accidentally serialize any more `Span`s after the source map encoding
492 let required_source_files = self.required_source_files.take().unwrap();
494 let working_directory = &self.tcx.sess.opts.working_dir;
496 let mut adapted = TableBuilder::default();
498 // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
500 // The order in which we encode source files is important here: the on-disk format for
501 // `Span` contains the index of the corresponding `SourceFile`.
502 for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
503 let source_file = &all_source_files[source_file_index];
504 // Don't serialize imported `SourceFile`s, unless we're in a proc-macro crate.
505 assert!(!source_file.is_imported() || self.is_proc_macro);
507 // At export time we expand all source file paths to absolute paths because
508 // downstream compilation sessions can have a different compiler working
509 // directory, so relative paths from this or any other upstream crate
510 // won't be valid anymore.
512 // At this point we also erase the actual on-disk path and only keep
513 // the remapped version -- as is necessary for reproducible builds.
514 let mut source_file = match source_file.name {
515 FileName::Real(ref original_file_name) => {
516 let adapted_file_name = source_map
518 .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
520 if adapted_file_name != *original_file_name {
521 let mut adapted: SourceFile = (**source_file).clone();
522 adapted.name = FileName::Real(adapted_file_name);
523 adapted.name_hash = {
524 let mut hasher: StableHasher = StableHasher::new();
525 adapted.name.hash(&mut hasher);
526 hasher.finish::<u128>()
534 // expanded code, not from a file
535 _ => source_file.clone(),
538 // We're serializing this `SourceFile` into our crate metadata,
539 // so mark it as coming from this crate.
540 // This also ensures that we don't try to deserialize the
541 // `CrateNum` for a proc-macro dependency - since proc macro
542 // dependencies aren't loaded when we deserialize a proc-macro,
543 // trying to remap the `CrateNum` would fail.
544 if self.is_proc_macro {
545 Lrc::make_mut(&mut source_file).cnum = LOCAL_CRATE;
548 let on_disk_index: u32 =
549 on_disk_index.try_into().expect("cannot export more than U32_MAX files");
550 adapted.set(on_disk_index, self.lazy(source_file));
553 adapted.encode(&mut self.opaque)
556 fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
559 let preamble_bytes = self.position() - i;
561 // Encode the crate deps
563 let crate_deps = self.encode_crate_deps();
564 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
565 let dep_bytes = self.position() - i;
567 // Encode the lib features.
569 let lib_features = self.encode_lib_features();
570 let lib_feature_bytes = self.position() - i;
572 // Encode the stability implications.
574 let stability_implications = self.encode_stability_implications();
575 let stability_implications_bytes = self.position() - i;
577 // Encode the language items.
579 let lang_items = self.encode_lang_items();
580 let lang_items_missing = self.encode_lang_items_missing();
581 let lang_item_bytes = self.position() - i;
583 // Encode the diagnostic items.
585 let diagnostic_items = self.encode_diagnostic_items();
586 let diagnostic_item_bytes = self.position() - i;
588 // Encode the native libraries used
590 let native_libraries = self.encode_native_libraries();
591 let native_lib_bytes = self.position() - i;
594 let foreign_modules = self.encode_foreign_modules();
595 let foreign_modules_bytes = self.position() - i;
597 // Encode DefPathTable
599 self.encode_def_path_table();
600 let def_path_table_bytes = self.position() - i;
602 // Encode the def IDs of traits, for rustdoc and diagnostics.
604 let traits = self.encode_traits();
605 let traits_bytes = self.position() - i;
607 // Encode the def IDs of impls, for coherence checking.
609 let impls = self.encode_impls();
610 let impls_bytes = self.position() - i;
613 let incoherent_impls = self.encode_incoherent_impls();
614 let incoherent_impls_bytes = self.position() - i;
619 let mir_bytes = self.position() - i;
623 self.encode_def_ids();
624 self.encode_info_for_items();
625 let item_bytes = self.position() - i;
627 // Encode the allocation index
629 let interpret_alloc_index = {
630 let mut interpret_alloc_index = Vec::new();
632 trace!("beginning to encode alloc ids");
634 let new_n = self.interpret_allocs.len();
635 // if we have found new ids, serialize those, too
640 trace!("encoding {} further alloc ids", new_n - n);
641 for idx in n..new_n {
642 let id = self.interpret_allocs[idx];
643 let pos = self.position() as u32;
644 interpret_alloc_index.push(pos);
645 interpret::specialized_encode_alloc_id(self, tcx, id);
649 self.lazy_array(interpret_alloc_index)
651 let interpret_alloc_index_bytes = self.position() - i;
653 // Encode the proc macro data. This affects 'tables',
654 // so we need to do this before we encode the tables.
655 // This overwrites def_keys, so it must happen after encode_def_path_table.
657 let proc_macro_data = self.encode_proc_macros();
658 let proc_macro_data_bytes = self.position() - i;
661 let tables = self.tables.encode(&mut self.opaque);
662 let tables_bytes = self.position() - i;
665 let debugger_visualizers = self.encode_debugger_visualizers();
666 let debugger_visualizers_bytes = self.position() - i;
668 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
669 // this as late as possible to give the prefetching as much time as possible to complete.
671 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
672 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
673 let exported_symbols_bytes = self.position() - i;
675 // Encode the hygiene data,
676 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
677 // of encoding other items (e.g. `optimized_mir`) may cause us to load
678 // data from the incremental cache. If this causes us to deserialize a `Span`,
679 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
680 // Therefore, we need to encode the hygiene data last to ensure that we encode
681 // any `SyntaxContext`s that might be used.
683 let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene();
684 let hygiene_bytes = self.position() - i;
687 let def_path_hash_map = self.encode_def_path_hash_map();
688 let def_path_hash_map_bytes = self.position() - i;
690 // Encode source_map. This needs to be done last,
691 // since encoding `Span`s tells us which `SourceFiles` we actually
694 let source_map = self.encode_source_map();
695 let source_map_bytes = self.position() - i;
698 let attrs = tcx.hir().krate_attrs();
699 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
700 let root = self.lazy(CrateRoot {
701 name: tcx.crate_name(LOCAL_CRATE),
702 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
703 triple: tcx.sess.opts.target_triple.clone(),
704 hash: tcx.crate_hash(LOCAL_CRATE),
705 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
706 required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
707 panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
708 edition: tcx.sess.edition(),
709 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
710 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
711 has_default_lib_allocator,
713 debugger_visualizers,
714 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
715 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
716 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
717 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
718 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
719 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
720 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
723 dylib_dependency_formats,
725 stability_implications,
736 interpret_alloc_index,
743 let final_bytes = self.position() - i;
745 let total_bytes = self.position();
747 let computed_total_bytes = preamble_bytes
750 + stability_implications_bytes
752 + diagnostic_item_bytes
754 + foreign_modules_bytes
755 + def_path_table_bytes
758 + incoherent_impls_bytes
761 + interpret_alloc_index_bytes
762 + proc_macro_data_bytes
764 + debugger_visualizers_bytes
765 + exported_symbols_bytes
767 + def_path_hash_map_bytes
770 assert_eq!(total_bytes, computed_total_bytes);
772 if tcx.sess.meta_stats() {
775 // Rewind and re-read all the metadata to count the zero bytes we wrote.
776 let pos_before_rewind = self.opaque.file().stream_position().unwrap();
777 let mut zero_bytes = 0;
778 self.opaque.file().rewind().unwrap();
779 let file = std::io::BufReader::new(self.opaque.file());
780 for e in file.bytes() {
785 assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
787 let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
788 let p = |label, bytes| {
789 eprintln!("{:>21}: {:>8} bytes ({:4.1}%)", label, bytes, perc(bytes));
794 "{} metadata bytes, of which {} bytes ({:.1}%) are zero",
799 p("preamble", preamble_bytes);
801 p("lib feature", lib_feature_bytes);
802 p("stability_implications", stability_implications_bytes);
803 p("lang item", lang_item_bytes);
804 p("diagnostic item", diagnostic_item_bytes);
805 p("native lib", native_lib_bytes);
806 p("foreign modules", foreign_modules_bytes);
807 p("def-path table", def_path_table_bytes);
808 p("traits", traits_bytes);
809 p("impls", impls_bytes);
810 p("incoherent_impls", incoherent_impls_bytes);
812 p("item", item_bytes);
813 p("interpret_alloc_index", interpret_alloc_index_bytes);
814 p("proc-macro-data", proc_macro_data_bytes);
815 p("tables", tables_bytes);
816 p("debugger visualizers", debugger_visualizers_bytes);
817 p("exported symbols", exported_symbols_bytes);
818 p("hygiene", hygiene_bytes);
819 p("def-path hashes", def_path_hash_map_bytes);
820 p("source_map", source_map_bytes);
821 p("final", final_bytes);
829 fn should_encode_visibility(def_kind: DefKind) -> bool {
839 | DefKind::TraitAlias
843 | DefKind::Static(..)
846 | DefKind::AssocConst
849 | DefKind::ForeignMod
852 | DefKind::Field => true,
854 | DefKind::ConstParam
855 | DefKind::LifetimeParam
857 | DefKind::InlineConst
861 | DefKind::ExternCrate => false,
865 fn should_encode_stability(def_kind: DefKind) -> bool {
874 | DefKind::AssocConst
876 | DefKind::ConstParam
877 | DefKind::Static(..)
880 | DefKind::ForeignMod
887 | DefKind::TraitAlias
889 | DefKind::ForeignTy => true,
891 | DefKind::LifetimeParam
893 | DefKind::InlineConst
897 | DefKind::ExternCrate => false,
901 /// Whether we should encode MIR.
903 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
904 /// We want to avoid this work when not required. Therefore:
905 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
906 /// - we skip `optimized_mir` for check runs.
908 /// Return a pair, resp. for CTFE and for LLVM.
909 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
910 match tcx.def_kind(def_id) {
912 DefKind::Ctor(_, _) => {
913 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
914 || tcx.sess.opts.unstable_opts.always_encode_mir;
919 | DefKind::InlineConst
920 | DefKind::AssocConst
921 | DefKind::Static(..)
922 | DefKind::Const => (true, false),
923 // Full-fledged functions
924 DefKind::AssocFn | DefKind::Fn => {
925 let generics = tcx.generics_of(def_id);
926 let needs_inline = (generics.requires_monomorphization(tcx)
927 || tcx.codegen_fn_attrs(def_id).requests_inline())
928 && tcx.sess.opts.output_types.should_codegen();
929 // The function has a `const` modifier or is in a `#[const_trait]`.
930 let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id())
931 || tcx.is_const_default_method(def_id.to_def_id());
932 let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
933 (is_const_fn, needs_inline || always_encode_mir)
935 // Closures can't be const fn.
936 DefKind::Closure => {
937 let generics = tcx.generics_of(def_id);
938 let needs_inline = (generics.requires_monomorphization(tcx)
939 || tcx.codegen_fn_attrs(def_id).requests_inline())
940 && tcx.sess.opts.output_types.should_codegen();
941 let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
942 (false, needs_inline || always_encode_mir)
944 // Generators require optimized MIR to compute layout.
945 DefKind::Generator => (false, true),
946 // The others don't have MIR.
951 fn should_encode_variances(def_kind: DefKind) -> bool {
959 | DefKind::AssocFn => true,
963 | DefKind::AssocConst
965 | DefKind::ConstParam
966 | DefKind::Static(..)
968 | DefKind::ForeignMod
973 | DefKind::TraitAlias
977 | DefKind::LifetimeParam
979 | DefKind::InlineConst
983 | DefKind::ExternCrate => false,
987 fn should_encode_generics(def_kind: DefKind) -> bool {
996 | DefKind::TraitAlias
1000 | DefKind::Static(..)
1003 | DefKind::AssocConst
1004 | DefKind::AnonConst
1005 | DefKind::InlineConst
1011 | DefKind::Generator => true,
1013 | DefKind::ForeignMod
1014 | DefKind::ConstParam
1015 | DefKind::Macro(..)
1017 | DefKind::LifetimeParam
1018 | DefKind::GlobalAsm
1019 | DefKind::ExternCrate => false,
1023 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1024 fn encode_attrs(&mut self, def_id: LocalDefId) {
1025 let mut attrs = self
1028 .attrs(self.tcx.hir().local_def_id_to_hir_id(def_id))
1030 .filter(|attr| !rustc_feature::is_builtin_only_local(attr.name_or_empty()));
1032 record_array!(self.tables.attributes[def_id.to_def_id()] <- attrs.clone());
1033 if attrs.any(|attr| attr.may_have_doc_links()) {
1034 self.tables.may_have_doc_links.set(def_id.local_def_index, ());
1038 fn encode_def_ids(&mut self) {
1039 if self.is_proc_macro {
1043 for local_id in tcx.iter_local_def_id() {
1044 let def_id = local_id.to_def_id();
1045 let def_kind = tcx.opt_def_kind(local_id);
1046 let Some(def_kind) = def_kind else { continue };
1047 self.tables.opt_def_kind.set(def_id.index, def_kind);
1048 record!(self.tables.def_span[def_id] <- tcx.def_span(def_id));
1049 self.encode_attrs(local_id);
1050 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1051 if let Some(ident_span) = tcx.def_ident_span(def_id) {
1052 record!(self.tables.def_ident_span[def_id] <- ident_span);
1054 if def_kind.has_codegen_attrs() {
1055 record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1057 if should_encode_visibility(def_kind) {
1058 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1060 if should_encode_stability(def_kind) {
1061 self.encode_stability(def_id);
1062 self.encode_const_stability(def_id);
1063 self.encode_default_body_stability(def_id);
1064 self.encode_deprecation(def_id);
1066 if should_encode_variances(def_kind) {
1067 let v = self.tcx.variances_of(def_id);
1068 record_array!(self.tables.variances_of[def_id] <- v);
1070 if should_encode_generics(def_kind) {
1071 let g = tcx.generics_of(def_id);
1072 record!(self.tables.generics_of[def_id] <- g);
1073 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1074 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1075 if !inferred_outlives.is_empty() {
1076 record_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1079 if let DefKind::TyParam | DefKind::ConstParam = def_kind {
1080 if let Some(default) = self.tcx.object_lifetime_default(def_id) {
1081 record!(self.tables.object_lifetime_default[def_id] <- default);
1084 if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1085 record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id));
1088 let inherent_impls = tcx.crate_inherent_impls(());
1089 for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
1090 if implementations.is_empty() {
1093 record_array!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1094 assert!(def_id.is_local());
1100 fn encode_item_type(&mut self, def_id: DefId) {
1101 debug!("EncodeContext::encode_item_type({:?})", def_id);
1102 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1105 fn encode_enum_variant_info(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1107 let variant = &def.variant(index);
1108 let def_id = variant.def_id;
1109 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1111 let data = VariantData {
1112 ctor_kind: variant.ctor_kind,
1113 discr: variant.discr,
1114 ctor: variant.ctor_def_id.map(|did| did.index),
1115 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1118 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1119 self.tables.constness.set(def_id.index, hir::Constness::Const);
1120 record_array!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1121 assert!(f.did.is_local());
1124 self.encode_item_type(def_id);
1125 if variant.ctor_kind == CtorKind::Fn {
1126 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1127 if let Some(ctor_def_id) = variant.ctor_def_id {
1128 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1133 fn encode_enum_variant_ctor(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1135 let variant = &def.variant(index);
1136 let def_id = variant.ctor_def_id.unwrap();
1137 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1139 // FIXME(eddyb) encode only the `CtorKind` for constructors.
1140 let data = VariantData {
1141 ctor_kind: variant.ctor_kind,
1142 discr: variant.discr,
1143 ctor: Some(def_id.index),
1144 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1147 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1148 self.tables.constness.set(def_id.index, hir::Constness::Const);
1149 self.encode_item_type(def_id);
1150 if variant.ctor_kind == CtorKind::Fn {
1151 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1155 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1157 let def_id = local_def_id.to_def_id();
1158 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1160 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1161 // only ever get called for the crate root. We still want to encode
1162 // the crate root for consistency with other crates (some of the resolver
1163 // code uses it). However, we skip encoding anything relating to child
1164 // items - we encode information about proc-macros later on.
1165 let reexports = if !self.is_proc_macro {
1166 match tcx.module_reexports(local_def_id) {
1167 Some(exports) => self.lazy_array(exports),
1168 _ => LazyArray::empty(),
1174 record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports));
1175 if self.is_proc_macro {
1176 // Encode this here because we don't do it in encode_def_ids.
1177 record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1179 record_array!(self.tables.children[def_id] <- iter::from_generator(|| {
1180 for item_id in md.item_ids {
1181 match tcx.hir().item(*item_id).kind {
1182 // Foreign items are planted into their parent modules
1183 // from name resolution point of view.
1184 hir::ItemKind::ForeignMod { items, .. } => {
1185 for foreign_item in items {
1186 yield foreign_item.id.def_id.local_def_index;
1189 // Only encode named non-reexport children, reexports are encoded
1190 // separately and unnamed items are not used by name resolution.
1191 hir::ItemKind::ExternCrate(..) => continue,
1192 _ if tcx.def_key(item_id.def_id.to_def_id()).get_opt_name().is_some() => {
1193 yield item_id.def_id.local_def_index;
1204 adt_def: ty::AdtDef<'tcx>,
1205 variant_index: VariantIdx,
1208 let variant = &adt_def.variant(variant_index);
1209 let field = &variant.fields[field_index];
1211 let def_id = field.did;
1212 debug!("EncodeContext::encode_field({:?})", def_id);
1214 record!(self.tables.kind[def_id] <- EntryKind::Field);
1215 self.encode_item_type(def_id);
1218 fn encode_struct_ctor(&mut self, adt_def: ty::AdtDef<'tcx>, def_id: DefId) {
1219 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1221 let variant = adt_def.non_enum_variant();
1223 let data = VariantData {
1224 ctor_kind: variant.ctor_kind,
1225 discr: variant.discr,
1226 ctor: Some(def_id.index),
1227 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1230 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1231 self.tables.constness.set(def_id.index, hir::Constness::Const);
1232 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data)));
1233 self.encode_item_type(def_id);
1234 if variant.ctor_kind == CtorKind::Fn {
1235 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1239 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1240 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1241 let bounds = self.tcx.explicit_item_bounds(def_id);
1242 if !bounds.is_empty() {
1243 record_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1247 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1248 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1251 let ast_item = tcx.hir().expect_trait_item(def_id.expect_local());
1252 self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
1253 let trait_item = tcx.associated_item(def_id);
1255 match trait_item.kind {
1256 ty::AssocKind::Const => {
1257 let rendered = rustc_hir_pretty::to_string(
1258 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
1259 |s| s.print_trait_item(ast_item),
1262 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(ty::AssocItemContainer::TraitContainer));
1263 record!(self.tables.mir_const_qualif[def_id] <- mir::ConstQualifs::default());
1264 record!(self.tables.rendered_const[def_id] <- rendered);
1266 ty::AssocKind::Fn => {
1267 let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind else { bug!() };
1269 hir::TraitFn::Required(ref names) => {
1270 record_array!(self.tables.fn_arg_names[def_id] <- *names)
1272 hir::TraitFn::Provided(body) => {
1273 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body))
1276 self.tables.asyncness.set(def_id.index, m_sig.header.asyncness);
1277 self.tables.constness.set(def_id.index, hir::Constness::NotConst);
1278 record!(self.tables.kind[def_id] <- EntryKind::AssocFn {
1279 container: ty::AssocItemContainer::TraitContainer,
1280 has_self: trait_item.fn_has_self_parameter,
1283 ty::AssocKind::Type => {
1284 self.encode_explicit_item_bounds(def_id);
1285 record!(self.tables.kind[def_id] <- EntryKind::AssocType(ty::AssocItemContainer::TraitContainer));
1288 match trait_item.kind {
1289 ty::AssocKind::Const | ty::AssocKind::Fn => {
1290 self.encode_item_type(def_id);
1292 ty::AssocKind::Type => {
1293 if ast_item.defaultness.has_value() {
1294 self.encode_item_type(def_id);
1298 if trait_item.kind == ty::AssocKind::Fn {
1299 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1303 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1304 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1307 let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local());
1308 self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
1309 let impl_item = self.tcx.associated_item(def_id);
1311 match impl_item.kind {
1312 ty::AssocKind::Const => {
1313 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1314 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1315 let const_data = self.encode_rendered_const_for_body(body_id);
1317 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(ty::AssocItemContainer::ImplContainer));
1318 record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1319 record!(self.tables.rendered_const[def_id] <- const_data);
1324 ty::AssocKind::Fn => {
1325 let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() };
1326 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1327 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1328 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1329 let constness = if self.tcx.is_const_fn_raw(def_id) {
1330 hir::Constness::Const
1332 hir::Constness::NotConst
1334 self.tables.constness.set(def_id.index, constness);
1335 record!(self.tables.kind[def_id] <- EntryKind::AssocFn {
1336 container: ty::AssocItemContainer::ImplContainer,
1337 has_self: impl_item.fn_has_self_parameter,
1340 ty::AssocKind::Type => {
1341 record!(self.tables.kind[def_id] <- EntryKind::AssocType(ty::AssocItemContainer::ImplContainer));
1344 self.encode_item_type(def_id);
1345 if let Some(trait_item_def_id) = impl_item.trait_item_def_id {
1346 self.tables.trait_item_def_id.set(def_id.index, trait_item_def_id.into());
1348 if impl_item.kind == ty::AssocKind::Fn {
1349 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1350 if tcx.is_intrinsic(def_id) {
1351 self.tables.is_intrinsic.set(def_id.index, ());
1356 fn encode_mir(&mut self) {
1357 if self.is_proc_macro {
1361 let keys_and_jobs = self
1365 .filter_map(|&def_id| {
1366 let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id);
1367 if encode_const || encode_opt {
1368 Some((def_id, encode_const, encode_opt))
1373 .collect::<Vec<_>>();
1374 for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() {
1375 debug_assert!(encode_const || encode_opt);
1377 debug!("EntryBuilder::encode_mir({:?})", def_id);
1379 record!(self.tables.optimized_mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1382 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id));
1384 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1385 let abstract_const = self.tcx.thir_abstract_const(def_id);
1386 if let Ok(Some(abstract_const)) = abstract_const {
1387 record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1390 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1393 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1394 let unused = self.tcx.unused_generic_params(instance);
1395 if !unused.is_empty() {
1396 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1401 fn encode_stability(&mut self, def_id: DefId) {
1402 debug!("EncodeContext::encode_stability({:?})", def_id);
1404 // The query lookup can take a measurable amount of time in crates with many items. Check if
1405 // the stability attributes are even enabled before using their queries.
1406 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1407 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1408 record!(self.tables.lookup_stability[def_id] <- stab)
1413 fn encode_const_stability(&mut self, def_id: DefId) {
1414 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1416 // The query lookup can take a measurable amount of time in crates with many items. Check if
1417 // the stability attributes are even enabled before using their queries.
1418 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1419 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1420 record!(self.tables.lookup_const_stability[def_id] <- stab)
1425 fn encode_default_body_stability(&mut self, def_id: DefId) {
1426 debug!("EncodeContext::encode_default_body_stability({:?})", def_id);
1428 // The query lookup can take a measurable amount of time in crates with many items. Check if
1429 // the stability attributes are even enabled before using their queries.
1430 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1431 if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1432 record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1437 fn encode_deprecation(&mut self, def_id: DefId) {
1438 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1439 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1440 record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1444 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> String {
1445 let hir = self.tcx.hir();
1446 let body = hir.body(body_id);
1447 rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1448 s.print_expr(&body.value)
1452 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1455 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1457 let entry_kind = match item.kind {
1458 hir::ItemKind::Static(..) => EntryKind::Static,
1459 hir::ItemKind::Const(_, body_id) => {
1460 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1461 let const_data = self.encode_rendered_const_for_body(body_id);
1462 record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1463 record!(self.tables.rendered_const[def_id] <- const_data);
1466 hir::ItemKind::Fn(ref sig, .., body) => {
1467 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1468 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1469 self.tables.constness.set(def_id.index, sig.header.constness);
1472 hir::ItemKind::Macro(ref macro_def, _) => {
1473 EntryKind::MacroDef(self.lazy(&*macro_def.body), macro_def.macro_rules)
1475 hir::ItemKind::Mod(ref m) => {
1476 return self.encode_info_for_mod(item.def_id, m);
1478 hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1479 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1480 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1481 hir::ItemKind::OpaqueTy(..) => {
1482 self.encode_explicit_item_bounds(def_id);
1485 hir::ItemKind::Enum(..) => {
1486 let adt_def = self.tcx.adt_def(def_id);
1487 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1490 hir::ItemKind::Struct(ref struct_def, _) => {
1491 let adt_def = self.tcx.adt_def(def_id);
1492 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1493 self.tables.constness.set(def_id.index, hir::Constness::Const);
1495 // Encode def_ids for each field and method
1496 // for methods, write all the stuff get_trait_method
1498 let ctor = struct_def
1500 .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1502 let variant = adt_def.non_enum_variant();
1503 EntryKind::Struct(self.lazy(VariantData {
1504 ctor_kind: variant.ctor_kind,
1505 discr: variant.discr,
1507 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1510 hir::ItemKind::Union(..) => {
1511 let adt_def = self.tcx.adt_def(def_id);
1512 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1514 let variant = adt_def.non_enum_variant();
1515 EntryKind::Union(self.lazy(VariantData {
1516 ctor_kind: variant.ctor_kind,
1517 discr: variant.discr,
1519 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1522 hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1523 self.tables.impl_defaultness.set(def_id.index, *defaultness);
1524 self.tables.constness.set(def_id.index, *constness);
1526 let trait_ref = self.tcx.impl_trait_ref(def_id);
1527 if let Some(trait_ref) = trait_ref {
1528 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1529 if let Some(mut an) = trait_def.ancestors(self.tcx, def_id).ok() {
1530 if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
1531 self.tables.impl_parent.set(def_id.index, parent.into());
1535 // if this is an impl of `CoerceUnsized`, create its
1536 // "unsized info", else just store None
1537 if Some(trait_ref.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1538 let coerce_unsized_info =
1539 self.tcx.at(item.span).coerce_unsized_info(def_id);
1540 record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
1544 let polarity = self.tcx.impl_polarity(def_id);
1545 self.tables.impl_polarity.set(def_id.index, polarity);
1549 hir::ItemKind::Trait(..) => {
1550 let trait_def = self.tcx.trait_def(def_id);
1551 record!(self.tables.trait_def[def_id] <- trait_def);
1555 hir::ItemKind::TraitAlias(..) => {
1556 let trait_def = self.tcx.trait_def(def_id);
1557 record!(self.tables.trait_def[def_id] <- trait_def);
1559 EntryKind::TraitAlias
1561 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1562 bug!("cannot encode info for item {:?}", item)
1565 record!(self.tables.kind[def_id] <- entry_kind);
1566 // FIXME(eddyb) there should be a nicer way to do this.
1568 hir::ItemKind::Enum(..) => record_array!(self.tables.children[def_id] <-
1569 self.tcx.adt_def(def_id).variants().iter().map(|v| {
1570 assert!(v.def_id.is_local());
1574 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1575 record_array!(self.tables.children[def_id] <-
1576 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1577 assert!(f.did.is_local());
1582 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1583 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1584 record_array!(self.tables.children[def_id] <-
1585 associated_item_def_ids.iter().map(|&def_id| {
1586 assert!(def_id.is_local());
1594 hir::ItemKind::Static(..)
1595 | hir::ItemKind::Const(..)
1596 | hir::ItemKind::Fn(..)
1597 | hir::ItemKind::TyAlias(..)
1598 | hir::ItemKind::OpaqueTy(..)
1599 | hir::ItemKind::Enum(..)
1600 | hir::ItemKind::Struct(..)
1601 | hir::ItemKind::Union(..)
1602 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1605 if let hir::ItemKind::Fn(..) = item.kind {
1606 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1607 if tcx.is_intrinsic(def_id) {
1608 self.tables.is_intrinsic.set(def_id.index, ());
1611 if let hir::ItemKind::Impl { .. } = item.kind {
1612 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1613 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1618 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1619 record!(self.tables.kind[def_id] <- kind);
1621 self.encode_item_type(def_id);
1625 fn encode_info_for_closure(&mut self, hir_id: hir::HirId) {
1626 let def_id = self.tcx.hir().local_def_id(hir_id);
1627 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1628 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1629 // including on the signature, which is inferred in `typeck.
1630 let typeck_result: &'tcx ty::TypeckResults<'tcx> = self.tcx.typeck(def_id);
1631 let ty = typeck_result.node_type(hir_id);
1633 ty::Generator(..) => {
1634 let data = self.tcx.generator_kind(def_id).unwrap();
1635 let generator_diagnostic_data = typeck_result.get_generator_diagnostic_data();
1636 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator);
1637 record!(self.tables.generator_kind[def_id.to_def_id()] <- data);
1638 record!(self.tables.generator_diagnostic_data[def_id.to_def_id()] <- generator_diagnostic_data);
1641 ty::Closure(..) => {
1642 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1645 _ => bug!("closure that is neither generator nor closure"),
1647 self.encode_item_type(def_id.to_def_id());
1648 if let ty::Closure(def_id, substs) = *ty.kind() {
1649 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1653 fn encode_info_for_anon_const(&mut self, id: hir::HirId) {
1654 let def_id = self.tcx.hir().local_def_id(id);
1655 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1656 let body_id = self.tcx.hir().body_owned_by(def_id);
1657 let const_data = self.encode_rendered_const_for_body(body_id);
1658 let qualifs = self.tcx.mir_const_qualif(def_id);
1660 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst);
1661 record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1662 record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1663 self.encode_item_type(def_id.to_def_id());
1666 fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1667 empty_proc_macro!(self);
1668 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1669 self.lazy_array(used_libraries.iter())
1672 fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1673 empty_proc_macro!(self);
1674 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1675 self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1678 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1679 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1680 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1681 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1683 self.hygiene_ctxt.encode(
1684 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1685 |(this, syntax_contexts, _, _), index, ctxt_data| {
1686 syntax_contexts.set(index, this.lazy(ctxt_data));
1688 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1689 if let Some(index) = index.as_local() {
1690 expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1691 expn_hash_table.set(index.as_raw(), this.lazy(hash));
1697 syntax_contexts.encode(&mut self.opaque),
1698 expn_data_table.encode(&mut self.opaque),
1699 expn_hash_table.encode(&mut self.opaque),
1703 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1704 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1707 let hir = tcx.hir();
1709 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1710 let stability = tcx.lookup_stability(CRATE_DEF_ID);
1712 self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1713 let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1714 for (i, span) in spans.into_iter().enumerate() {
1715 let span = self.lazy(span);
1716 self.tables.proc_macro_quoted_spans.set(i, span);
1719 self.tables.opt_def_kind.set(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1720 record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1721 self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1722 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1723 if let Some(stability) = stability {
1724 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1726 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1728 // Normally, this information is encoded when we walk the items
1729 // defined in this crate. However, we skip doing that for proc-macro crates,
1730 // so we manually encode just the information that we need
1731 for &proc_macro in &tcx.resolutions(()).proc_macros {
1732 let id = proc_macro;
1733 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1734 let mut name = hir.name(proc_macro);
1735 let span = hir.span(proc_macro);
1736 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1737 // so downstream crates need access to them.
1738 let attrs = hir.attrs(proc_macro);
1739 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1741 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1743 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1744 // This unwrap chain should have been checked by the proc-macro harness.
1745 name = attr.meta_item_list().unwrap()[0]
1753 bug!("Unknown proc-macro type for item {:?}", id);
1756 let mut def_key = self.tcx.hir().def_key(id);
1757 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1759 let def_id = id.to_def_id();
1760 self.tables.opt_def_kind.set(def_id.index, DefKind::Macro(macro_kind));
1761 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1762 self.encode_attrs(id);
1763 record!(self.tables.def_keys[def_id] <- def_key);
1764 record!(self.tables.def_ident_span[def_id] <- span);
1765 record!(self.tables.def_span[def_id] <- span);
1766 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1767 if let Some(stability) = stability {
1768 record!(self.tables.lookup_stability[def_id] <- stability);
1772 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1778 fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1779 empty_proc_macro!(self);
1780 self.lazy_array(self.tcx.debugger_visualizers(LOCAL_CRATE).iter())
1783 fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1784 empty_proc_macro!(self);
1791 let dep = CrateDep {
1792 name: self.tcx.crate_name(cnum),
1793 hash: self.tcx.crate_hash(cnum),
1794 host_hash: self.tcx.crate_host_hash(cnum),
1795 kind: self.tcx.dep_kind(cnum),
1796 extra_filename: self.tcx.extra_filename(cnum).clone(),
1800 .collect::<Vec<_>>();
1803 // Sanity-check the crate numbers
1804 let mut expected_cnum = 1;
1805 for &(n, _) in &deps {
1806 assert_eq!(n, CrateNum::new(expected_cnum));
1811 // We're just going to write a list of crate 'name-hash-version's, with
1812 // the assumption that they are numbered 1 to n.
1813 // FIXME (#2166): This is not nearly enough to support correct versioning
1814 // but is enough to get transitive crate dependencies working.
1815 self.lazy_array(deps.iter().map(|&(_, ref dep)| dep))
1818 fn encode_lib_features(&mut self) -> LazyArray<(Symbol, Option<Symbol>)> {
1819 empty_proc_macro!(self);
1821 let lib_features = tcx.lib_features(());
1822 self.lazy_array(lib_features.to_vec())
1825 fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
1826 empty_proc_macro!(self);
1828 let implications = tcx.stability_implications(LOCAL_CRATE);
1829 self.lazy_array(implications.iter().map(|(k, v)| (*k, *v)))
1832 fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
1833 empty_proc_macro!(self);
1835 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1836 self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1839 fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, usize)> {
1840 empty_proc_macro!(self);
1842 let lang_items = tcx.lang_items();
1843 let lang_items = lang_items.items().iter();
1844 self.lazy_array(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1845 if let Some(def_id) = opt_def_id {
1846 if def_id.is_local() {
1847 return Some((def_id.index, i));
1854 fn encode_lang_items_missing(&mut self) -> LazyArray<lang_items::LangItem> {
1855 empty_proc_macro!(self);
1857 self.lazy_array(&tcx.lang_items().missing)
1860 fn encode_traits(&mut self) -> LazyArray<DefIndex> {
1861 empty_proc_macro!(self);
1862 self.lazy_array(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index))
1865 /// Encodes an index, mapping each trait to its (local) implementations.
1866 fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
1867 debug!("EncodeContext::encode_traits_and_impls()");
1868 empty_proc_macro!(self);
1870 let mut fx_hash_map: FxHashMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
1871 FxHashMap::default();
1873 for id in tcx.hir().items() {
1874 if matches!(tcx.def_kind(id.def_id), DefKind::Impl) {
1875 if let Some(trait_ref) = tcx.impl_trait_ref(id.def_id.to_def_id()) {
1876 let simplified_self_ty = fast_reject::simplify_type(
1878 trait_ref.self_ty(),
1879 TreatParams::AsInfer,
1883 .entry(trait_ref.def_id)
1885 .push((id.def_id.local_def_index, simplified_self_ty));
1890 let mut all_impls: Vec<_> = fx_hash_map.into_iter().collect();
1892 // Bring everything into deterministic order for hashing
1893 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1895 let all_impls: Vec<_> = all_impls
1897 .map(|(trait_def_id, mut impls)| {
1898 // Bring everything into deterministic order for hashing
1899 impls.sort_by_cached_key(|&(index, _)| {
1900 tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1904 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1905 impls: self.lazy_array(&impls),
1910 self.lazy_array(&all_impls)
1913 fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
1914 debug!("EncodeContext::encode_traits_and_impls()");
1915 empty_proc_macro!(self);
1917 let mut all_impls: Vec<_> = tcx.crate_inherent_impls(()).incoherent_impls.iter().collect();
1918 tcx.with_stable_hashing_context(|mut ctx| {
1919 all_impls.sort_by_cached_key(|&(&simp, _)| {
1920 let mut hasher = StableHasher::new();
1921 simp.hash_stable(&mut ctx, &mut hasher);
1922 hasher.finish::<Fingerprint>()
1925 let all_impls: Vec<_> = all_impls
1927 .map(|(&simp, impls)| {
1928 let mut impls: Vec<_> =
1929 impls.into_iter().map(|def_id| def_id.local_def_index).collect();
1930 impls.sort_by_cached_key(|&local_def_index| {
1931 tcx.hir().def_path_hash(LocalDefId { local_def_index })
1934 IncoherentImpls { self_ty: simp, impls: self.lazy_array(impls) }
1938 self.lazy_array(&all_impls)
1941 // Encodes all symbols exported from this crate into the metadata.
1943 // This pass is seeded off the reachability list calculated in the
1944 // middle::reachable module but filters out items that either don't have a
1945 // symbol associated with them (they weren't translated) or if they're an FFI
1946 // definition (as that's not defined in this crate).
1947 fn encode_exported_symbols(
1949 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
1950 ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
1951 empty_proc_macro!(self);
1952 // The metadata symbol name is special. It should not show up in
1953 // downstream crates.
1954 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1959 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1960 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1967 fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
1968 empty_proc_macro!(self);
1969 let formats = self.tcx.dependency_formats(());
1970 for (ty, arr) in formats.iter() {
1971 if *ty != CrateType::Dylib {
1974 return self.lazy_array(arr.iter().map(|slot| match *slot {
1975 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1977 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1978 Linkage::Static => Some(LinkagePreference::RequireStatic),
1984 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1987 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1990 hir::ForeignItemKind::Fn(_, ref names, _) => {
1991 self.tables.asyncness.set(def_id.index, hir::IsAsync::NotAsync);
1992 record_array!(self.tables.fn_arg_names[def_id] <- *names);
1993 let constness = if self.tcx.is_const_fn_raw(def_id) {
1994 hir::Constness::Const
1996 hir::Constness::NotConst
1998 self.tables.constness.set(def_id.index, constness);
1999 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn);
2001 hir::ForeignItemKind::Static(..) => {
2002 record!(self.tables.kind[def_id] <- EntryKind::ForeignStatic);
2004 hir::ForeignItemKind::Type => {
2005 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
2008 self.encode_item_type(def_id);
2009 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
2010 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
2011 if tcx.is_intrinsic(def_id) {
2012 self.tables.is_intrinsic.set(def_id.index, ());
2018 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
2019 impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> {
2020 type NestedFilter = nested_filter::OnlyBodies;
2022 fn nested_visit_map(&mut self) -> Self::Map {
2025 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2026 intravisit::walk_expr(self, ex);
2027 self.encode_info_for_expr(ex);
2029 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
2030 intravisit::walk_anon_const(self, c);
2031 self.encode_info_for_anon_const(c.hir_id);
2033 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
2034 intravisit::walk_item(self, item);
2036 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
2037 _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
2039 self.encode_addl_info_for_item(item);
2041 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
2042 intravisit::walk_foreign_item(self, ni);
2043 self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
2045 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
2046 intravisit::walk_generics(self, generics);
2047 self.encode_info_for_generics(generics);
2051 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
2052 fn encode_fields(&mut self, adt_def: ty::AdtDef<'tcx>) {
2053 for (variant_index, variant) in adt_def.variants().iter_enumerated() {
2054 for (field_index, _field) in variant.fields.iter().enumerate() {
2055 self.encode_field(adt_def, variant_index, field_index);
2060 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
2061 for param in generics.params {
2062 let def_id = self.tcx.hir().local_def_id(param.hir_id);
2064 GenericParamKind::Lifetime { .. } => continue,
2065 GenericParamKind::Type { default, .. } => {
2066 self.encode_info_for_generic_param(
2068 EntryKind::TypeParam,
2072 GenericParamKind::Const { ref default, .. } => {
2073 let def_id = def_id.to_def_id();
2074 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
2075 if default.is_some() {
2076 record!(self.tables.const_param_default[def_id] <- self.tcx.const_param_default(def_id))
2083 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
2084 if let hir::ExprKind::Closure { .. } = expr.kind {
2085 self.encode_info_for_closure(expr.hir_id);
2089 /// In some cases, along with the item itself, we also
2090 /// encode some sub-items. Usually we want some info from the item
2091 /// so it's easier to do that here then to wait until we would encounter
2092 /// normally in the visitor walk.
2093 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
2095 hir::ItemKind::Static(..)
2096 | hir::ItemKind::Const(..)
2097 | hir::ItemKind::Fn(..)
2098 | hir::ItemKind::Macro(..)
2099 | hir::ItemKind::Mod(..)
2100 | hir::ItemKind::ForeignMod { .. }
2101 | hir::ItemKind::GlobalAsm(..)
2102 | hir::ItemKind::ExternCrate(..)
2103 | hir::ItemKind::Use(..)
2104 | hir::ItemKind::TyAlias(..)
2105 | hir::ItemKind::OpaqueTy(..)
2106 | hir::ItemKind::TraitAlias(..) => {
2107 // no sub-item recording needed in these cases
2109 hir::ItemKind::Enum(..) => {
2110 let def = self.tcx.adt_def(item.def_id.to_def_id());
2111 self.encode_fields(def);
2113 for (i, variant) in def.variants().iter_enumerated() {
2114 self.encode_enum_variant_info(def, i);
2116 if let Some(_ctor_def_id) = variant.ctor_def_id {
2117 self.encode_enum_variant_ctor(def, i);
2121 hir::ItemKind::Struct(ref struct_def, _) => {
2122 let def = self.tcx.adt_def(item.def_id.to_def_id());
2123 self.encode_fields(def);
2125 // If the struct has a constructor, encode it.
2126 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
2127 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
2128 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
2131 hir::ItemKind::Union(..) => {
2132 let def = self.tcx.adt_def(item.def_id.to_def_id());
2133 self.encode_fields(def);
2135 hir::ItemKind::Impl { .. } => {
2136 for &trait_item_def_id in
2137 self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2139 self.encode_info_for_impl_item(trait_item_def_id);
2142 hir::ItemKind::Trait(..) => {
2143 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2145 self.encode_info_for_trait_item(item_def_id);
2152 /// Used to prefetch queries which will be needed later by metadata encoding.
2153 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2154 fn prefetch_mir(tcx: TyCtxt<'_>) {
2155 if !tcx.sess.opts.output_types.should_codegen() {
2156 // We won't emit MIR, so don't prefetch it.
2160 par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2161 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2164 tcx.ensure().mir_for_ctfe(def_id);
2167 tcx.ensure().optimized_mir(def_id);
2169 if encode_opt || encode_const {
2170 tcx.ensure().promoted_mir(def_id);
2175 // NOTE(eddyb) The following comment was preserved for posterity, even
2176 // though it's no longer relevant as EBML (which uses nested & tagged
2177 // "documents") was replaced with a scheme that can't go out of bounds.
2179 // And here we run into yet another obscure archive bug: in which metadata
2180 // loaded from archives may have trailing garbage bytes. Awhile back one of
2181 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2182 // and opt) by having ebml generate an out-of-bounds panic when looking at
2185 // Upon investigation it turned out that the metadata file inside of an rlib
2186 // (and ar archive) was being corrupted. Some compilations would generate a
2187 // metadata file which would end in a few extra bytes, while other
2188 // compilations would not have these extra bytes appended to the end. These
2189 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2190 // being interpreted causing the out-of-bounds.
2192 // The root cause of why these extra bytes were appearing was never
2193 // discovered, and in the meantime the solution we're employing is to insert
2194 // the length of the metadata to the start of the metadata. Later on this
2195 // will allow us to slice the metadata to the precise length that we just
2196 // generated regardless of trailing bytes that end up in it.
2198 pub struct EncodedMetadata {
2199 // The declaration order matters because `mmap` should be dropped before `_temp_dir`.
2201 // We need to carry MaybeTempDir to avoid deleting the temporary
2202 // directory while accessing the Mmap.
2203 _temp_dir: Option<MaybeTempDir>,
2206 impl EncodedMetadata {
2208 pub fn from_path(path: PathBuf, temp_dir: Option<MaybeTempDir>) -> std::io::Result<Self> {
2209 let file = std::fs::File::open(&path)?;
2210 let file_metadata = file.metadata()?;
2211 if file_metadata.len() == 0 {
2212 return Ok(Self { mmap: None, _temp_dir: None });
2214 let mmap = unsafe { Some(Mmap::map(file)?) };
2215 Ok(Self { mmap, _temp_dir: temp_dir })
2219 pub fn raw_data(&self) -> &[u8] {
2220 self.mmap.as_ref().map(|mmap| mmap.as_ref()).unwrap_or_default()
2224 impl<S: Encoder> Encodable<S> for EncodedMetadata {
2225 fn encode(&self, s: &mut S) {
2226 let slice = self.raw_data();
2231 impl<D: Decoder> Decodable<D> for EncodedMetadata {
2232 fn decode(d: &mut D) -> Self {
2233 let len = d.read_usize();
2234 let mmap = if len > 0 {
2235 let mut mmap = MmapMut::map_anon(len).unwrap();
2237 (&mut mmap[..]).write(&[d.read_u8()]).unwrap();
2239 mmap.flush().unwrap();
2240 Some(mmap.make_read_only().unwrap())
2245 Self { mmap, _temp_dir: None }
2249 pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path) {
2250 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2252 // Since encoding metadata is not in a query, and nothing is cached,
2253 // there's no need to do dep-graph tracking for any of it.
2254 tcx.dep_graph.assert_ignored();
2257 || encode_metadata_impl(tcx, path),
2259 if tcx.sess.threads() == 1 {
2262 // Prefetch some queries used by metadata encoding.
2263 // This is not necessary for correctness, but is only done for performance reasons.
2264 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2265 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2270 fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) {
2271 let mut encoder = opaque::FileEncoder::new(path)
2272 .unwrap_or_else(|err| tcx.sess.fatal(&format!("failed to create file encoder: {}", err)));
2273 encoder.emit_raw_bytes(METADATA_HEADER);
2275 // Will be filled with the root position after encoding everything.
2276 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2278 let source_map_files = tcx.sess.source_map().files();
2279 let source_file_cache = (source_map_files[0].clone(), 0);
2280 let required_source_files = Some(FxIndexSet::default());
2281 drop(source_map_files);
2283 let hygiene_ctxt = HygieneEncodeContext::default();
2285 let mut ecx = EncodeContext {
2288 feat: tcx.features(),
2289 tables: Default::default(),
2290 lazy_state: LazyState::NoNode,
2291 type_shorthands: Default::default(),
2292 predicate_shorthands: Default::default(),
2294 interpret_allocs: Default::default(),
2295 required_source_files,
2296 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2297 hygiene_ctxt: &hygiene_ctxt,
2298 symbol_table: Default::default(),
2301 // Encode the rustc version string in a predictable location.
2302 rustc_version().encode(&mut ecx);
2304 // Encode all the entries and extra information in the crate,
2305 // culminating in the `CrateRoot` which points to all of it.
2306 let root = ecx.encode_crate_root();
2310 let mut file = ecx.opaque.file();
2311 // We will return to this position after writing the root position.
2312 let pos_before_seek = file.stream_position().unwrap();
2314 // Encode the root position.
2315 let header = METADATA_HEADER.len();
2316 file.seek(std::io::SeekFrom::Start(header as u64))
2317 .unwrap_or_else(|err| tcx.sess.fatal(&format!("failed to seek the file: {}", err)));
2318 let pos = root.position.get();
2319 file.write_all(&[(pos >> 24) as u8, (pos >> 16) as u8, (pos >> 8) as u8, (pos >> 0) as u8])
2320 .unwrap_or_else(|err| tcx.sess.fatal(&format!("failed to write to the file: {}", err)));
2322 // Return to the position where we are before writing the root position.
2323 file.seek(std::io::SeekFrom::Start(pos_before_seek)).unwrap();
2325 // Record metadata size for self-profiling
2326 tcx.prof.artifact_size(
2329 file.metadata().unwrap().len() as u64,
2333 pub fn provide(providers: &mut Providers) {
2334 *providers = Providers {
2335 traits_in_crate: |tcx, cnum| {
2336 assert_eq!(cnum, LOCAL_CRATE);
2338 let mut traits = Vec::new();
2339 for id in tcx.hir().items() {
2340 if matches!(tcx.def_kind(id.def_id), DefKind::Trait | DefKind::TraitAlias) {
2341 traits.push(id.def_id.to_def_id())
2345 // Bring everything into deterministic order.
2346 traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
2347 tcx.arena.alloc_slice(&traits)