1 use crate::errors::{FailCreateFileEncoder, FailSeekFile, FailWriteFile};
2 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
3 use crate::rmeta::table::TableBuilder;
6 use rustc_ast::Attribute;
7 use rustc_data_structures::fingerprint::Fingerprint;
8 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
9 use rustc_data_structures::memmap::{Mmap, MmapMut};
10 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
11 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
12 use rustc_data_structures::temp_dir::MaybeTempDir;
14 use rustc_hir::def::DefKind;
15 use rustc_hir::def_id::{
16 CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
18 use rustc_hir::definitions::DefPathData;
19 use rustc_hir::intravisit::{self, Visitor};
20 use rustc_hir::lang_items::LangItem;
21 use rustc_middle::hir::nested_filter;
22 use rustc_middle::middle::dependency_format::Linkage;
23 use rustc_middle::middle::exported_symbols::{
24 metadata_symbol_name, ExportedSymbol, SymbolExportInfo,
26 use rustc_middle::mir::interpret;
27 use rustc_middle::traits::specialization_graph;
28 use rustc_middle::ty::codec::TyEncoder;
29 use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams};
30 use rustc_middle::ty::query::Providers;
31 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
32 use rustc_middle::util::common::to_readable_str;
33 use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder};
34 use rustc_session::config::{CrateType, OptLevel};
35 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
36 use rustc_span::hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind};
37 use rustc_span::symbol::{sym, Symbol};
39 self, DebuggerVisualizerFile, ExternalSource, FileName, SourceFile, Span, SyntaxContext,
41 use rustc_target::abi::VariantIdx;
42 use std::borrow::Borrow;
43 use std::collections::hash_map::Entry;
45 use std::io::{Read, Seek, Write};
47 use std::num::NonZeroUsize;
48 use std::path::{Path, PathBuf};
50 pub(super) struct EncodeContext<'a, 'tcx> {
51 opaque: opaque::FileEncoder,
53 feat: &'tcx rustc_feature::Features,
55 tables: TableBuilders,
57 lazy_state: LazyState,
58 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
59 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
61 interpret_allocs: FxIndexSet<interpret::AllocId>,
63 // This is used to speed up Span encoding.
64 // The `usize` is an index into the `MonotonicVec`
65 // that stores the `SourceFile`
66 source_file_cache: (Lrc<SourceFile>, usize),
67 // The indices (into the `SourceMap`'s `MonotonicVec`)
68 // of all of the `SourceFiles` that we need to serialize.
69 // When we serialize a `Span`, we insert the index of its
70 // `SourceFile` into the `FxIndexSet`.
71 // The order inside the `FxIndexSet` is used as on-disk
72 // order of `SourceFiles`, and encoded inside `Span`s.
73 required_source_files: Option<FxIndexSet<usize>>,
75 hygiene_ctxt: &'a HygieneEncodeContext,
76 symbol_table: FxHashMap<Symbol, usize>,
79 /// If the current crate is a proc-macro, returns early with `LazyArray::empty()`.
80 /// This is useful for skipping the encoding of things that aren't needed
81 /// for proc-macro crates.
82 macro_rules! empty_proc_macro {
84 if $self.is_proc_macro {
85 return LazyArray::empty();
90 macro_rules! encoder_methods {
91 ($($name:ident($ty:ty);)*) => {
92 $(fn $name(&mut self, value: $ty) {
93 self.opaque.$name(value)
98 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
119 emit_raw_bytes(&[u8]);
123 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
124 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
125 e.emit_lazy_distance(self.position);
129 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
130 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
131 e.emit_usize(self.num_elems);
132 if self.num_elems > 0 {
133 e.emit_lazy_distance(self.position)
138 impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
139 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
140 e.emit_usize(self.encoded_size);
141 e.emit_lazy_distance(self.position);
145 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
146 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
147 if *self != LOCAL_CRATE && s.is_proc_macro {
148 panic!("Attempted to encode non-local CrateNum {self:?} for proc-macro crate");
150 s.emit_u32(self.as_u32());
154 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
155 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
156 s.emit_u32(self.as_u32());
160 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
161 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
162 s.emit_u32(self.as_u32());
166 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
167 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
168 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s);
172 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
173 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
174 if self.krate == LOCAL_CRATE {
175 // We will only write details for local expansions. Non-local expansions will fetch
176 // data from the corresponding crate's metadata.
177 // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
178 // metadata from proc-macro crates.
179 s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
181 self.krate.encode(s);
182 self.local_id.encode(s);
186 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
187 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
188 let span = self.data();
190 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
191 // since we don't load proc-macro dependencies during serialization.
192 // This means that any hygiene information from macros used *within*
193 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
194 // definition) will be lost.
196 // This can show up in two ways:
198 // 1. Any hygiene information associated with identifier of
199 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
200 // Since proc-macros can only be invoked from a different crate,
201 // real code should never need to care about this.
203 // 2. Using `Span::def_site` or `Span::mixed_site` will not
204 // include any hygiene information associated with the definition
205 // site. This means that a proc-macro cannot emit a `$crate`
206 // identifier which resolves to one of its dependencies,
207 // which also should never come up in practice.
209 // Additionally, this affects `Span::parent`, and any other
210 // span inspection APIs that would otherwise allow traversing
211 // the `SyntaxContexts` associated with a span.
213 // None of these user-visible effects should result in any
214 // cross-crate inconsistencies (getting one behavior in the same
215 // crate, and a different behavior in another crate) due to the
216 // limited surface that proc-macros can expose.
218 // IMPORTANT: If this is ever changed, be sure to update
219 // `rustc_span::hygiene::raw_encode_expn_id` to handle
220 // encoding `ExpnData` for proc-macro crates.
222 SyntaxContext::root().encode(s);
228 return TAG_PARTIAL_SPAN.encode(s);
231 // The Span infrastructure should make sure that this invariant holds:
232 debug_assert!(span.lo <= span.hi);
234 if !s.source_file_cache.0.contains(span.lo) {
235 let source_map = s.tcx.sess.source_map();
236 let source_file_index = source_map.lookup_source_file_idx(span.lo);
237 s.source_file_cache =
238 (source_map.files()[source_file_index].clone(), source_file_index);
240 let (ref source_file, source_file_index) = s.source_file_cache;
241 debug_assert!(source_file.contains(span.lo));
243 if !source_file.contains(span.hi) {
244 // Unfortunately, macro expansion still sometimes generates Spans
245 // that malformed in this way.
246 return TAG_PARTIAL_SPAN.encode(s);
249 // There are two possible cases here:
250 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
251 // crate we are writing metadata for. When the metadata for *this* crate gets
252 // deserialized, the deserializer will need to know which crate it originally came
253 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
254 // be deserialized after the rest of the span data, which tells the deserializer
255 // which crate contains the source map information.
256 // 2. This span comes from our own crate. No special handling is needed - we just
257 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
258 // our own source map information.
260 // If we're a proc-macro crate, we always treat this as a local `Span`.
261 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
262 // if we're a proc-macro crate.
263 // This allows us to avoid loading the dependencies of proc-macro crates: all of
264 // the information we need to decode `Span`s is stored in the proc-macro crate.
265 let (tag, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
266 // To simplify deserialization, we 'rebase' this span onto the crate it originally came
267 // from (the crate that 'owns' the file it references. These rebased 'lo' and 'hi'
268 // values are relative to the source map information for the 'foreign' crate whose
269 // CrateNum we write into the metadata. This allows `imported_source_files` to binary
270 // search through the 'foreign' crate's source map information, using the
271 // deserialized 'lo' and 'hi' values directly.
273 // All of this logic ensures that the final result of deserialization is a 'normal'
274 // Span that can be used without any additional trouble.
275 let metadata_index = {
276 // Introduce a new scope so that we drop the 'lock()' temporary
277 match &*source_file.external_src.lock() {
278 ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
279 src => panic!("Unexpected external source {src:?}"),
283 (TAG_VALID_SPAN_FOREIGN, metadata_index)
285 // Record the fact that we need to encode the data for this `SourceFile`
287 s.required_source_files.as_mut().expect("Already encoded SourceMap!");
288 let (metadata_index, _) = source_files.insert_full(source_file_index);
289 let metadata_index: u32 =
290 metadata_index.try_into().expect("cannot export more than U32_MAX files");
292 (TAG_VALID_SPAN_LOCAL, metadata_index)
295 // Encode the start position relative to the file start, so we profit more from the
296 // variable-length integer encoding.
297 let lo = span.lo - source_file.start_pos;
299 // Encode length which is usually less than span.hi and profits more
300 // from the variable-length integer encoding that we use.
301 let len = span.hi - span.lo;
307 // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
308 metadata_index.encode(s);
310 if tag == TAG_VALID_SPAN_FOREIGN {
311 // This needs to be two lines to avoid holding the `s.source_file_cache`
312 // while calling `cnum.encode(s)`
313 let cnum = s.source_file_cache.0.cnum;
319 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Symbol {
320 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
321 // if symbol preinterned, emit tag and symbol index
322 if self.is_preinterned() {
323 s.opaque.emit_u8(SYMBOL_PREINTERNED);
324 s.opaque.emit_u32(self.as_u32());
326 // otherwise write it as string or as offset to it
327 match s.symbol_table.entry(*self) {
328 Entry::Vacant(o) => {
329 s.opaque.emit_u8(SYMBOL_STR);
330 let pos = s.opaque.position();
332 s.emit_str(self.as_str());
334 Entry::Occupied(o) => {
336 s.emit_u8(SYMBOL_OFFSET);
344 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
345 const CLEAR_CROSS_CRATE: bool = true;
347 type I = TyCtxt<'tcx>;
349 fn position(&self) -> usize {
350 self.opaque.position()
353 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
354 &mut self.type_shorthands
357 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
358 &mut self.predicate_shorthands
361 fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
362 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
368 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
369 // normally need extra variables to avoid errors about multiple mutable borrows.
370 macro_rules! record {
371 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
374 let lazy = $self.lazy(value);
375 $self.$tables.$table.set($def_id.index, lazy);
380 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
381 // normally need extra variables to avoid errors about multiple mutable borrows.
382 macro_rules! record_array {
383 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
386 let lazy = $self.lazy_array(value);
387 $self.$tables.$table.set($def_id.index, lazy);
392 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
393 fn emit_lazy_distance(&mut self, position: NonZeroUsize) {
394 let pos = position.get();
395 let distance = match self.lazy_state {
396 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
397 LazyState::NodeStart(start) => {
398 let start = start.get();
399 assert!(pos <= start);
402 LazyState::Previous(last_pos) => {
404 last_pos <= position,
405 "make sure that the calls to `lazy*` \
406 are in the same order as the metadata fields",
408 position.get() - last_pos.get()
411 self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap());
412 self.emit_usize(distance);
415 fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
417 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
419 let pos = NonZeroUsize::new(self.position()).unwrap();
421 assert_eq!(self.lazy_state, LazyState::NoNode);
422 self.lazy_state = LazyState::NodeStart(pos);
423 value.borrow().encode(self);
424 self.lazy_state = LazyState::NoNode;
426 assert!(pos.get() <= self.position());
428 LazyValue::from_position(pos)
431 fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
436 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
438 let pos = NonZeroUsize::new(self.position()).unwrap();
440 assert_eq!(self.lazy_state, LazyState::NoNode);
441 self.lazy_state = LazyState::NodeStart(pos);
442 let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
443 self.lazy_state = LazyState::NoNode;
445 assert!(pos.get() <= self.position());
447 LazyArray::from_position_and_num_elems(pos, len)
450 fn encode_info_for_items(&mut self) {
451 self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
453 // Proc-macro crates only export proc-macro items, which are looked
454 // up using `proc_macro_data`
455 if self.is_proc_macro {
459 self.tcx.hir().visit_all_item_likes_in_crate(self);
462 fn encode_def_path_table(&mut self) {
463 let table = self.tcx.def_path_table();
464 if self.is_proc_macro {
465 for def_index in std::iter::once(CRATE_DEF_INDEX)
466 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
468 let def_key = self.lazy(table.def_key(def_index));
469 let def_path_hash = table.def_path_hash(def_index);
470 self.tables.def_keys.set(def_index, def_key);
471 self.tables.def_path_hashes.set(def_index, def_path_hash);
474 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
475 let def_key = self.lazy(def_key);
476 self.tables.def_keys.set(def_index, def_key);
477 self.tables.def_path_hashes.set(def_index, *def_path_hash);
482 fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
483 self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
486 fn encode_source_map(&mut self) -> LazyTable<u32, LazyValue<rustc_span::SourceFile>> {
487 let source_map = self.tcx.sess.source_map();
488 let all_source_files = source_map.files();
490 // By replacing the `Option` with `None`, we ensure that we can't
491 // accidentally serialize any more `Span`s after the source map encoding
493 let required_source_files = self.required_source_files.take().unwrap();
495 let working_directory = &self.tcx.sess.opts.working_dir;
497 let mut adapted = TableBuilder::default();
499 // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
501 // The order in which we encode source files is important here: the on-disk format for
502 // `Span` contains the index of the corresponding `SourceFile`.
503 for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
504 let source_file = &all_source_files[source_file_index];
505 // Don't serialize imported `SourceFile`s, unless we're in a proc-macro crate.
506 assert!(!source_file.is_imported() || self.is_proc_macro);
508 // At export time we expand all source file paths to absolute paths because
509 // downstream compilation sessions can have a different compiler working
510 // directory, so relative paths from this or any other upstream crate
511 // won't be valid anymore.
513 // At this point we also erase the actual on-disk path and only keep
514 // the remapped version -- as is necessary for reproducible builds.
515 let mut source_file = match source_file.name {
516 FileName::Real(ref original_file_name) => {
517 let adapted_file_name = source_map
519 .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
521 if adapted_file_name != *original_file_name {
522 let mut adapted: SourceFile = (**source_file).clone();
523 adapted.name = FileName::Real(adapted_file_name);
524 adapted.name_hash = {
525 let mut hasher: StableHasher = StableHasher::new();
526 adapted.name.hash(&mut hasher);
527 hasher.finish::<u128>()
535 // expanded code, not from a file
536 _ => source_file.clone(),
539 // We're serializing this `SourceFile` into our crate metadata,
540 // so mark it as coming from this crate.
541 // This also ensures that we don't try to deserialize the
542 // `CrateNum` for a proc-macro dependency - since proc macro
543 // dependencies aren't loaded when we deserialize a proc-macro,
544 // trying to remap the `CrateNum` would fail.
545 if self.is_proc_macro {
546 Lrc::make_mut(&mut source_file).cnum = LOCAL_CRATE;
549 let on_disk_index: u32 =
550 on_disk_index.try_into().expect("cannot export more than U32_MAX files");
551 adapted.set(on_disk_index, self.lazy(source_file));
554 adapted.encode(&mut self.opaque)
557 fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
559 let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
562 ($label:literal, $f:expr) => {{
563 let orig_pos = self.position();
565 stats.push(($label, self.position() - orig_pos));
570 // We have already encoded some things. Get their combined size from the current position.
571 stats.push(("preamble", self.position()));
573 let (crate_deps, dylib_dependency_formats) =
574 stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
576 let lib_features = stat!("lib-features", || self.encode_lib_features());
578 let stability_implications =
579 stat!("stability-implications", || self.encode_stability_implications());
581 let (lang_items, lang_items_missing) = stat!("lang-items", || {
582 (self.encode_lang_items(), self.encode_lang_items_missing())
585 let diagnostic_items = stat!("diagnostic-items", || self.encode_diagnostic_items());
587 let native_libraries = stat!("native-libs", || self.encode_native_libraries());
589 let foreign_modules = stat!("foreign-modules", || self.encode_foreign_modules());
591 _ = stat!("def-path-table", || self.encode_def_path_table());
593 // Encode the def IDs of traits, for rustdoc and diagnostics.
594 let traits = stat!("traits", || self.encode_traits());
596 // Encode the def IDs of impls, for coherence checking.
597 let impls = stat!("impls", || self.encode_impls());
599 let incoherent_impls = stat!("incoherent-impls", || self.encode_incoherent_impls());
601 _ = stat!("mir", || self.encode_mir());
603 _ = stat!("items", || {
604 self.encode_def_ids();
605 self.encode_info_for_items();
608 let interpret_alloc_index = stat!("interpret-alloc-index", || {
609 let mut interpret_alloc_index = Vec::new();
611 trace!("beginning to encode alloc ids");
613 let new_n = self.interpret_allocs.len();
614 // if we have found new ids, serialize those, too
619 trace!("encoding {} further alloc ids", new_n - n);
620 for idx in n..new_n {
621 let id = self.interpret_allocs[idx];
622 let pos = self.position() as u32;
623 interpret_alloc_index.push(pos);
624 interpret::specialized_encode_alloc_id(self, tcx, id);
628 self.lazy_array(interpret_alloc_index)
631 // Encode the proc macro data. This affects `tables`, so we need to do this before we
632 // encode the tables. This overwrites def_keys, so it must happen after
633 // encode_def_path_table.
634 let proc_macro_data = stat!("proc-macro-data", || self.encode_proc_macros());
636 let tables = stat!("tables", || self.tables.encode(&mut self.opaque));
638 let debugger_visualizers =
639 stat!("debugger-visualizers", || self.encode_debugger_visualizers());
641 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
642 // this as late as possible to give the prefetching as much time as possible to complete.
643 let exported_symbols = stat!("exported-symbols", || {
644 self.encode_exported_symbols(&tcx.exported_symbols(LOCAL_CRATE))
647 // Encode the hygiene data.
648 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The
649 // process of encoding other items (e.g. `optimized_mir`) may cause us to load data from
650 // the incremental cache. If this causes us to deserialize a `Span`, then we may load
651 // additional `SyntaxContext`s into the global `HygieneData`. Therefore, we need to encode
652 // the hygiene data last to ensure that we encode any `SyntaxContext`s that might be used.
653 let (syntax_contexts, expn_data, expn_hashes) = stat!("hygiene", || self.encode_hygiene());
655 let def_path_hash_map = stat!("def-path-hash-map", || self.encode_def_path_hash_map());
657 // Encode source_map. This needs to be done last, because encoding `Span`s tells us which
658 // `SourceFiles` we actually need to encode.
659 let source_map = stat!("source-map", || self.encode_source_map());
661 let root = stat!("final", || {
662 let attrs = tcx.hir().krate_attrs();
663 self.lazy(CrateRoot {
664 name: tcx.crate_name(LOCAL_CRATE),
665 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
666 triple: tcx.sess.opts.target_triple.clone(),
667 hash: tcx.crate_hash(LOCAL_CRATE),
668 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
669 required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
670 panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
671 edition: tcx.sess.edition(),
672 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
673 has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
674 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
675 has_default_lib_allocator: tcx
677 .contains_name(&attrs, sym::default_lib_allocator),
679 debugger_visualizers,
680 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
681 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
682 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
683 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
684 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
685 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
686 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
689 dylib_dependency_formats,
691 stability_implications,
702 interpret_alloc_index,
711 let total_bytes = self.position();
713 let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
714 assert_eq!(total_bytes, computed_total_bytes);
716 if tcx.sess.opts.unstable_opts.meta_stats {
719 // Rewind and re-read all the metadata to count the zero bytes we wrote.
720 let pos_before_rewind = self.opaque.file().stream_position().unwrap();
721 let mut zero_bytes = 0;
722 self.opaque.file().rewind().unwrap();
723 let file = std::io::BufReader::new(self.opaque.file());
724 for e in file.bytes() {
729 assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
731 stats.sort_by_key(|&(_, usize)| usize);
733 let prefix = "meta-stats";
734 let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
736 eprintln!("{prefix} METADATA STATS");
737 eprintln!("{} {:<23}{:>10}", prefix, "Section", "Size");
738 eprintln!("{prefix} ----------------------------------------------------------------");
739 for (label, size) in stats {
741 "{} {:<23}{:>10} ({:4.1}%)",
744 to_readable_str(size),
748 eprintln!("{prefix} ----------------------------------------------------------------");
750 "{} {:<23}{:>10} (of which {:.1}% are zero bytes)",
753 to_readable_str(total_bytes),
756 eprintln!("{prefix}");
763 /// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and
764 /// useful in downstream crates. Local-only attributes are an obvious example, but some
765 /// rustdoc-specific attributes can equally be of use while documenting the current crate only.
767 /// Removing these superfluous attributes speeds up compilation by making the metadata smaller.
769 /// Note: the `is_def_id_public` parameter is used to cache whether the given `DefId` has a public
770 /// visibility: this is a piece of data that can be computed once per defid, and not once per
771 /// attribute. Some attributes would only be usable downstream if they are public.
773 fn should_encode_attr(
777 is_def_id_public: &mut Option<bool>,
779 if rustc_feature::is_builtin_only_local(attr.name_or_empty()) {
780 // Attributes marked local-only don't need to be encoded for downstream crates.
782 } else if attr.doc_str().is_some() {
783 // We keep all public doc comments because they might be "imported" into downstream crates
784 // if they use `#[doc(inline)]` to copy an item's documentation into their own.
785 *is_def_id_public.get_or_insert_with(|| tcx.effective_visibilities(()).is_exported(def_id))
786 } else if attr.has_name(sym::doc) {
787 // If this is a `doc` attribute, and it's marked `inline` (as in `#[doc(inline)]`), we can
788 // remove it. It won't be inlinable in downstream crates.
789 attr.meta_item_list().map(|l| l.iter().any(|l| !l.has_name(sym::inline))).unwrap_or(false)
795 fn should_encode_visibility(def_kind: DefKind) -> bool {
805 | DefKind::TraitAlias
809 | DefKind::Static(..)
812 | DefKind::AssocConst
815 | DefKind::ForeignMod
817 | DefKind::ImplTraitPlaceholder
819 | DefKind::Field => true,
821 | DefKind::ConstParam
822 | DefKind::LifetimeParam
824 | DefKind::InlineConst
828 | DefKind::ExternCrate => false,
832 fn should_encode_stability(def_kind: DefKind) -> bool {
841 | DefKind::AssocConst
843 | DefKind::ConstParam
844 | DefKind::Static(..)
847 | DefKind::ForeignMod
850 | DefKind::ImplTraitPlaceholder
855 | DefKind::TraitAlias
857 | DefKind::ForeignTy => true,
859 | DefKind::LifetimeParam
861 | DefKind::InlineConst
865 | DefKind::ExternCrate => false,
869 /// Whether we should encode MIR.
871 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
872 /// We want to avoid this work when not required. Therefore:
873 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
874 /// - we skip `optimized_mir` for check runs.
876 /// Return a pair, resp. for CTFE and for LLVM.
877 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
878 match tcx.def_kind(def_id) {
880 DefKind::Ctor(_, _) => {
881 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
882 || tcx.sess.opts.unstable_opts.always_encode_mir;
887 | DefKind::InlineConst
888 | DefKind::AssocConst
889 | DefKind::Static(..)
890 | DefKind::Const => (true, false),
891 // Full-fledged functions + closures
892 DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
893 let generics = tcx.generics_of(def_id);
894 let needs_inline = (generics.requires_monomorphization(tcx)
895 || tcx.codegen_fn_attrs(def_id).requests_inline())
896 && tcx.sess.opts.output_types.should_codegen();
897 // The function has a `const` modifier or is in a `#[const_trait]`.
898 let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id())
899 || tcx.is_const_default_method(def_id.to_def_id());
900 let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
901 (is_const_fn, needs_inline || always_encode_mir)
903 // Generators require optimized MIR to compute layout.
904 DefKind::Generator => (false, true),
905 // The others don't have MIR.
910 fn should_encode_variances(def_kind: DefKind) -> bool {
917 | DefKind::ImplTraitPlaceholder
920 | DefKind::AssocFn => true,
924 | DefKind::AssocConst
926 | DefKind::ConstParam
927 | DefKind::Static(..)
929 | DefKind::ForeignMod
933 | DefKind::TraitAlias
937 | DefKind::LifetimeParam
939 | DefKind::InlineConst
943 | DefKind::ExternCrate => false,
947 fn should_encode_generics(def_kind: DefKind) -> bool {
956 | DefKind::TraitAlias
960 | DefKind::Static(..)
963 | DefKind::AssocConst
965 | DefKind::InlineConst
967 | DefKind::ImplTraitPlaceholder
972 | DefKind::Generator => true,
974 | DefKind::ForeignMod
975 | DefKind::ConstParam
978 | DefKind::LifetimeParam
980 | DefKind::ExternCrate => false,
984 fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
994 | DefKind::Static(..)
1000 | DefKind::AssocConst
1002 | DefKind::Generator
1003 | DefKind::ConstParam
1004 | DefKind::AnonConst
1005 | DefKind::InlineConst => true,
1007 DefKind::ImplTraitPlaceholder => {
1008 let parent_def_id = tcx.impl_trait_in_trait_parent(def_id.to_def_id());
1009 let assoc_item = tcx.associated_item(parent_def_id);
1010 match assoc_item.container {
1011 // Always encode an RPIT in an impl fn, since it always has a body
1012 ty::AssocItemContainer::ImplContainer => true,
1013 ty::AssocItemContainer::TraitContainer => {
1014 // Encode an RPIT for a trait only if the trait has a default body
1015 assoc_item.defaultness(tcx).has_value()
1020 DefKind::AssocTy => {
1021 let assoc_item = tcx.associated_item(def_id);
1022 match assoc_item.container {
1023 ty::AssocItemContainer::ImplContainer => true,
1024 ty::AssocItemContainer::TraitContainer => assoc_item.defaultness(tcx).has_value(),
1027 DefKind::TyParam => {
1028 let hir::Node::GenericParam(param) = tcx.hir().get_by_def_id(def_id) else { bug!() };
1029 let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() };
1034 | DefKind::TraitAlias
1036 | DefKind::ForeignMod
1037 | DefKind::Macro(..)
1039 | DefKind::LifetimeParam
1040 | DefKind::GlobalAsm
1041 | DefKind::ExternCrate => false,
1045 fn should_encode_const(def_kind: DefKind) -> bool {
1047 DefKind::Const | DefKind::AssocConst | DefKind::AnonConst => true,
1056 | DefKind::Static(..)
1059 | DefKind::ImplTraitPlaceholder
1060 | DefKind::ForeignTy
1064 | DefKind::Generator
1065 | DefKind::ConstParam
1066 | DefKind::InlineConst
1070 | DefKind::TraitAlias
1072 | DefKind::ForeignMod
1073 | DefKind::Macro(..)
1075 | DefKind::LifetimeParam
1076 | DefKind::GlobalAsm
1077 | DefKind::ExternCrate => false,
1081 fn should_encode_trait_impl_trait_tys(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1082 if tcx.def_kind(def_id) != DefKind::AssocFn {
1086 let Some(item) = tcx.opt_associated_item(def_id) else { return false; };
1087 if item.container != ty::AssocItemContainer::ImplContainer {
1091 let Some(trait_item_def_id) = item.trait_item_def_id else { return false; };
1093 // FIXME(RPITIT): This does a somewhat manual walk through the signature
1094 // of the trait fn to look for any RPITITs, but that's kinda doing a lot
1095 // of work. We can probably remove this when we refactor RPITITs to be
1096 // associated types.
1097 tcx.fn_sig(trait_item_def_id).skip_binder().output().walk().any(|arg| {
1098 if let ty::GenericArgKind::Type(ty) = arg.unpack()
1099 && let ty::Alias(ty::Projection, data) = ty.kind()
1100 && tcx.def_kind(data.def_id) == DefKind::ImplTraitPlaceholder
1109 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1110 fn encode_attrs(&mut self, def_id: LocalDefId) {
1112 let mut is_public: Option<bool> = None;
1116 .attrs(tcx.hir().local_def_id_to_hir_id(def_id))
1118 .filter(move |attr| should_encode_attr(tcx, attr, def_id, &mut is_public));
1120 record_array!(self.tables.attributes[def_id.to_def_id()] <- attrs.clone());
1121 if attrs.any(|attr| attr.may_have_doc_links()) {
1122 self.tables.may_have_doc_links.set(def_id.local_def_index, ());
1126 fn encode_def_ids(&mut self) {
1127 if self.is_proc_macro {
1131 for local_id in tcx.iter_local_def_id() {
1132 let def_id = local_id.to_def_id();
1133 let def_kind = tcx.opt_def_kind(local_id);
1134 let Some(def_kind) = def_kind else { continue };
1135 self.tables.opt_def_kind.set(def_id.index, def_kind);
1136 let def_span = tcx.def_span(local_id);
1137 record!(self.tables.def_span[def_id] <- def_span);
1138 self.encode_attrs(local_id);
1139 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1140 if let Some(ident_span) = tcx.def_ident_span(def_id) {
1141 record!(self.tables.def_ident_span[def_id] <- ident_span);
1143 if def_kind.has_codegen_attrs() {
1144 record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1146 if should_encode_visibility(def_kind) {
1148 self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);
1149 record!(self.tables.visibility[def_id] <- vis);
1151 if should_encode_stability(def_kind) {
1152 self.encode_stability(def_id);
1153 self.encode_const_stability(def_id);
1154 self.encode_default_body_stability(def_id);
1155 self.encode_deprecation(def_id);
1157 if should_encode_variances(def_kind) {
1158 let v = self.tcx.variances_of(def_id);
1159 record_array!(self.tables.variances_of[def_id] <- v);
1161 if should_encode_generics(def_kind) {
1162 let g = tcx.generics_of(def_id);
1163 record!(self.tables.generics_of[def_id] <- g);
1164 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1165 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1166 if !inferred_outlives.is_empty() {
1167 record_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1170 if should_encode_type(tcx, local_id, def_kind) {
1171 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1173 if let DefKind::TyParam = def_kind {
1174 let default = self.tcx.object_lifetime_default(def_id);
1175 record!(self.tables.object_lifetime_default[def_id] <- default);
1177 if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1178 record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id));
1180 if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1181 let params_in_repr = self.tcx.params_in_repr(def_id);
1182 record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1184 if should_encode_trait_impl_trait_tys(tcx, def_id)
1185 && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1187 record!(self.tables.trait_impl_trait_tys[def_id] <- table);
1190 let inherent_impls = tcx.with_stable_hashing_context(|hcx| {
1191 tcx.crate_inherent_impls(()).inherent_impls.to_sorted(&hcx, true)
1194 for (def_id, implementations) in inherent_impls {
1195 if implementations.is_empty() {
1198 record_array!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1199 assert!(def_id.is_local());
1205 fn encode_enum_variant_info(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1207 let variant = &def.variant(index);
1208 let def_id = variant.def_id;
1209 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1211 let data = VariantData {
1212 discr: variant.discr,
1213 ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1214 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1217 record!(self.tables.variant_data[def_id] <- data);
1218 self.tables.constness.set(def_id.index, hir::Constness::Const);
1219 record_array!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1220 assert!(f.did.is_local());
1223 if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1224 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1225 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1229 fn encode_enum_variant_ctor(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1230 let variant = &def.variant(index);
1231 let Some((ctor_kind, def_id)) = variant.ctor else { return };
1232 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1234 // FIXME(eddyb) encode only the `CtorKind` for constructors.
1235 let data = VariantData {
1236 discr: variant.discr,
1237 ctor: Some((ctor_kind, def_id.index)),
1238 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1241 record!(self.tables.variant_data[def_id] <- data);
1242 self.tables.constness.set(def_id.index, hir::Constness::Const);
1243 if ctor_kind == CtorKind::Fn {
1244 record!(self.tables.fn_sig[def_id] <- self.tcx.fn_sig(def_id));
1248 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1250 let def_id = local_def_id.to_def_id();
1251 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1253 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1254 // only ever get called for the crate root. We still want to encode
1255 // the crate root for consistency with other crates (some of the resolver
1256 // code uses it). However, we skip encoding anything relating to child
1257 // items - we encode information about proc-macros later on.
1258 if self.is_proc_macro {
1259 // Encode this here because we don't do it in encode_def_ids.
1260 record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1262 record_array!(self.tables.children[def_id] <- iter::from_generator(|| {
1263 for item_id in md.item_ids {
1264 match tcx.hir().item(*item_id).kind {
1265 // Foreign items are planted into their parent modules
1266 // from name resolution point of view.
1267 hir::ItemKind::ForeignMod { items, .. } => {
1268 for foreign_item in items {
1269 yield foreign_item.id.owner_id.def_id.local_def_index;
1272 // Only encode named non-reexport children, reexports are encoded
1273 // separately and unnamed items are not used by name resolution.
1274 hir::ItemKind::ExternCrate(..) => continue,
1275 hir::ItemKind::Struct(ref vdata, _) => {
1276 yield item_id.owner_id.def_id.local_def_index;
1277 // Encode constructors which take a separate slot in value namespace.
1278 if let Some(ctor_hir_id) = vdata.ctor_hir_id() {
1279 yield tcx.hir().local_def_id(ctor_hir_id).local_def_index;
1282 _ if tcx.def_key(item_id.owner_id.to_def_id()).get_opt_name().is_some() => {
1283 yield item_id.owner_id.def_id.local_def_index;
1290 if let Some(reexports) = tcx.module_reexports(local_def_id) {
1291 assert!(!reexports.is_empty());
1292 record_array!(self.tables.module_reexports[def_id] <- reexports);
1297 fn encode_struct_ctor(&mut self, adt_def: ty::AdtDef<'tcx>) {
1298 let variant = adt_def.non_enum_variant();
1299 let Some((ctor_kind, def_id)) = variant.ctor else { return };
1300 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1302 let data = VariantData {
1303 discr: variant.discr,
1304 ctor: Some((ctor_kind, def_id.index)),
1305 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1308 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1309 record!(self.tables.variant_data[def_id] <- data);
1310 self.tables.constness.set(def_id.index, hir::Constness::Const);
1311 if ctor_kind == CtorKind::Fn {
1312 record!(self.tables.fn_sig[def_id] <- self.tcx.fn_sig(def_id));
1316 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1317 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1318 let bounds = self.tcx.explicit_item_bounds(def_id);
1319 if !bounds.is_empty() {
1320 record_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1324 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1325 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1328 let impl_defaultness = tcx.impl_defaultness(def_id.expect_local());
1329 self.tables.impl_defaultness.set(def_id.index, impl_defaultness);
1330 let trait_item = tcx.associated_item(def_id);
1331 self.tables.assoc_container.set(def_id.index, trait_item.container);
1333 match trait_item.kind {
1334 ty::AssocKind::Const => {}
1335 ty::AssocKind::Fn => {
1336 record_array!(self.tables.fn_arg_names[def_id] <- tcx.fn_arg_names(def_id));
1337 self.tables.asyncness.set(def_id.index, tcx.asyncness(def_id));
1338 self.tables.constness.set(def_id.index, hir::Constness::NotConst);
1340 ty::AssocKind::Type => {
1341 self.encode_explicit_item_bounds(def_id);
1344 if trait_item.kind == ty::AssocKind::Fn {
1345 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1349 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1350 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1353 let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local());
1354 self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
1355 let impl_item = self.tcx.associated_item(def_id);
1356 self.tables.assoc_container.set(def_id.index, impl_item.container);
1358 match impl_item.kind {
1359 ty::AssocKind::Fn => {
1360 let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() };
1361 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1362 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1363 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1364 let constness = if self.tcx.is_const_fn_raw(def_id) {
1365 hir::Constness::Const
1367 hir::Constness::NotConst
1369 self.tables.constness.set(def_id.index, constness);
1371 ty::AssocKind::Const | ty::AssocKind::Type => {}
1373 if let Some(trait_item_def_id) = impl_item.trait_item_def_id {
1374 self.tables.trait_item_def_id.set(def_id.index, trait_item_def_id.into());
1376 if impl_item.kind == ty::AssocKind::Fn {
1377 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1378 if tcx.is_intrinsic(def_id) {
1379 self.tables.is_intrinsic.set(def_id.index, ());
1384 fn encode_mir(&mut self) {
1385 if self.is_proc_macro {
1391 let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1392 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
1393 if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1395 for (def_id, encode_const, encode_opt) in keys_and_jobs {
1396 debug_assert!(encode_const || encode_opt);
1398 debug!("EntryBuilder::encode_mir({:?})", def_id);
1400 record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1403 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1405 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1406 let abstract_const = tcx.thir_abstract_const(def_id);
1407 if let Ok(Some(abstract_const)) = abstract_const {
1408 record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1411 if should_encode_const(tcx.def_kind(def_id)) {
1412 let qualifs = tcx.mir_const_qualif(def_id);
1413 record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1414 let body_id = tcx.hir().maybe_body_owned_by(def_id);
1415 if let Some(body_id) = body_id {
1416 let const_data = self.encode_rendered_const_for_body(body_id);
1417 record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1421 record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1424 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1425 let unused = tcx.unused_generic_params(instance);
1426 if !unused.all_used() {
1427 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1431 // Encode all the deduced parameter attributes for everything that has MIR, even for items
1432 // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1433 // save the query traffic.
1434 if tcx.sess.opts.output_types.should_codegen()
1435 && tcx.sess.opts.optimize != OptLevel::No
1436 && tcx.sess.opts.incremental.is_none()
1438 for &local_def_id in tcx.mir_keys(()) {
1439 if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1440 record_array!(self.tables.deduced_param_attrs[local_def_id.to_def_id()] <-
1441 self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1447 fn encode_stability(&mut self, def_id: DefId) {
1448 debug!("EncodeContext::encode_stability({:?})", def_id);
1450 // The query lookup can take a measurable amount of time in crates with many items. Check if
1451 // the stability attributes are even enabled before using their queries.
1452 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1453 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1454 record!(self.tables.lookup_stability[def_id] <- stab)
1459 fn encode_const_stability(&mut self, def_id: DefId) {
1460 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1462 // The query lookup can take a measurable amount of time in crates with many items. Check if
1463 // the stability attributes are even enabled before using their queries.
1464 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1465 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1466 record!(self.tables.lookup_const_stability[def_id] <- stab)
1471 fn encode_default_body_stability(&mut self, def_id: DefId) {
1472 debug!("EncodeContext::encode_default_body_stability({:?})", def_id);
1474 // The query lookup can take a measurable amount of time in crates with many items. Check if
1475 // the stability attributes are even enabled before using their queries.
1476 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1477 if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1478 record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1483 fn encode_deprecation(&mut self, def_id: DefId) {
1484 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1485 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1486 record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1490 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> String {
1491 let hir = self.tcx.hir();
1492 let body = hir.body(body_id);
1493 rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1494 s.print_expr(&body.value)
1498 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1501 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1504 hir::ItemKind::Fn(ref sig, .., body) => {
1505 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1506 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1507 self.tables.constness.set(def_id.index, sig.header.constness);
1509 hir::ItemKind::Macro(ref macro_def, _) => {
1510 if macro_def.macro_rules {
1511 self.tables.macro_rules.set(def_id.index, ());
1513 record!(self.tables.macro_definition[def_id] <- &*macro_def.body);
1515 hir::ItemKind::Mod(ref m) => {
1516 return self.encode_info_for_mod(item.owner_id.def_id, m);
1518 hir::ItemKind::OpaqueTy(ref opaque) => {
1519 self.encode_explicit_item_bounds(def_id);
1520 if matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias) {
1521 self.tables.is_type_alias_impl_trait.set(def_id.index, ());
1524 hir::ItemKind::Enum(..) => {
1525 let adt_def = self.tcx.adt_def(def_id);
1526 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1528 hir::ItemKind::Struct(..) => {
1529 let adt_def = self.tcx.adt_def(def_id);
1530 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1531 self.tables.constness.set(def_id.index, hir::Constness::Const);
1533 let variant = adt_def.non_enum_variant();
1534 record!(self.tables.variant_data[def_id] <- VariantData {
1535 discr: variant.discr,
1536 ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1537 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1540 hir::ItemKind::Union(..) => {
1541 let adt_def = self.tcx.adt_def(def_id);
1542 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1544 let variant = adt_def.non_enum_variant();
1545 record!(self.tables.variant_data[def_id] <- VariantData {
1546 discr: variant.discr,
1547 ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1548 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1551 hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1552 self.tables.impl_defaultness.set(def_id.index, *defaultness);
1553 self.tables.constness.set(def_id.index, *constness);
1555 let trait_ref = self.tcx.impl_trait_ref(def_id).map(ty::EarlyBinder::skip_binder);
1556 if let Some(trait_ref) = trait_ref {
1557 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1558 if let Ok(mut an) = trait_def.ancestors(self.tcx, def_id) {
1559 if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
1560 self.tables.impl_parent.set(def_id.index, parent.into());
1564 // if this is an impl of `CoerceUnsized`, create its
1565 // "unsized info", else just store None
1566 if Some(trait_ref.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1567 let coerce_unsized_info =
1568 self.tcx.at(item.span).coerce_unsized_info(def_id);
1569 record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
1573 let polarity = self.tcx.impl_polarity(def_id);
1574 self.tables.impl_polarity.set(def_id.index, polarity);
1576 hir::ItemKind::Trait(..) => {
1577 let trait_def = self.tcx.trait_def(def_id);
1578 record!(self.tables.trait_def[def_id] <- trait_def);
1580 hir::ItemKind::TraitAlias(..) => {
1581 let trait_def = self.tcx.trait_def(def_id);
1582 record!(self.tables.trait_def[def_id] <- trait_def);
1584 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1585 bug!("cannot encode info for item {:?}", item)
1587 hir::ItemKind::Static(..)
1588 | hir::ItemKind::Const(..)
1589 | hir::ItemKind::ForeignMod { .. }
1590 | hir::ItemKind::GlobalAsm(..)
1591 | hir::ItemKind::TyAlias(..) => {}
1593 // FIXME(eddyb) there should be a nicer way to do this.
1595 hir::ItemKind::Enum(..) => {
1596 record_array!(self.tables.children[def_id] <- iter::from_generator(||
1597 for variant in tcx.adt_def(def_id).variants() {
1598 yield variant.def_id.index;
1599 // Encode constructors which take a separate slot in value namespace.
1600 if let Some(ctor_def_id) = variant.ctor_def_id() {
1601 yield ctor_def_id.index;
1606 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1607 record_array!(self.tables.children[def_id] <-
1608 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1609 assert!(f.did.is_local());
1614 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1615 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1616 record_array!(self.tables.children[def_id] <-
1617 associated_item_def_ids.iter().map(|&def_id| {
1618 assert!(def_id.is_local());
1625 if let hir::ItemKind::Fn(..) = item.kind {
1626 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1627 if tcx.is_intrinsic(def_id) {
1628 self.tables.is_intrinsic.set(def_id.index, ());
1631 if let hir::ItemKind::Impl { .. } = item.kind {
1632 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1633 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1636 // In some cases, along with the item itself, we also
1637 // encode some sub-items. Usually we want some info from the item
1638 // so it's easier to do that here then to wait until we would encounter
1639 // normally in the visitor walk.
1641 hir::ItemKind::Enum(..) => {
1642 let def = self.tcx.adt_def(item.owner_id.to_def_id());
1643 for (i, _) in def.variants().iter_enumerated() {
1644 self.encode_enum_variant_info(def, i);
1645 self.encode_enum_variant_ctor(def, i);
1648 hir::ItemKind::Struct(..) => {
1649 let def = self.tcx.adt_def(item.owner_id.to_def_id());
1650 self.encode_struct_ctor(def);
1652 hir::ItemKind::Impl { .. } => {
1653 for &trait_item_def_id in
1654 self.tcx.associated_item_def_ids(item.owner_id.to_def_id()).iter()
1656 self.encode_info_for_impl_item(trait_item_def_id);
1659 hir::ItemKind::Trait(..) => {
1661 self.tcx.associated_item_def_ids(item.owner_id.to_def_id()).iter()
1663 self.encode_info_for_trait_item(item_def_id);
1670 #[instrument(level = "debug", skip(self))]
1671 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1672 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1673 // including on the signature, which is inferred in `typeck.
1674 let typeck_result: &'tcx ty::TypeckResults<'tcx> = self.tcx.typeck(def_id);
1675 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1676 let ty = typeck_result.node_type(hir_id);
1678 ty::Generator(..) => {
1679 let data = self.tcx.generator_kind(def_id).unwrap();
1680 let generator_diagnostic_data = typeck_result.get_generator_diagnostic_data();
1681 record!(self.tables.generator_kind[def_id.to_def_id()] <- data);
1682 record!(self.tables.generator_diagnostic_data[def_id.to_def_id()] <- generator_diagnostic_data);
1685 ty::Closure(_, substs) => {
1686 let constness = self.tcx.constness(def_id.to_def_id());
1687 self.tables.constness.set(def_id.to_def_id().index, constness);
1688 record!(self.tables.fn_sig[def_id.to_def_id()] <- substs.as_closure().sig());
1691 _ => bug!("closure that is neither generator nor closure"),
1695 fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1696 empty_proc_macro!(self);
1697 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1698 self.lazy_array(used_libraries.iter())
1701 fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1702 empty_proc_macro!(self);
1703 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1704 self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1707 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1708 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1709 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1710 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1712 self.hygiene_ctxt.encode(
1713 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1714 |(this, syntax_contexts, _, _), index, ctxt_data| {
1715 syntax_contexts.set(index, this.lazy(ctxt_data));
1717 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1718 if let Some(index) = index.as_local() {
1719 expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1720 expn_hash_table.set(index.as_raw(), this.lazy(hash));
1726 syntax_contexts.encode(&mut self.opaque),
1727 expn_data_table.encode(&mut self.opaque),
1728 expn_hash_table.encode(&mut self.opaque),
1732 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1733 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1736 let hir = tcx.hir();
1738 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1739 let stability = tcx.lookup_stability(CRATE_DEF_ID);
1741 self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1742 let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1743 for (i, span) in spans.into_iter().enumerate() {
1744 let span = self.lazy(span);
1745 self.tables.proc_macro_quoted_spans.set(i, span);
1748 self.tables.opt_def_kind.set(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1749 record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1750 self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1751 let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|def_id| def_id.local_def_index);
1752 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
1753 if let Some(stability) = stability {
1754 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1756 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1758 // Normally, this information is encoded when we walk the items
1759 // defined in this crate. However, we skip doing that for proc-macro crates,
1760 // so we manually encode just the information that we need
1761 for &proc_macro in &tcx.resolutions(()).proc_macros {
1762 let id = proc_macro;
1763 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1764 let mut name = hir.name(proc_macro);
1765 let span = hir.span(proc_macro);
1766 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1767 // so downstream crates need access to them.
1768 let attrs = hir.attrs(proc_macro);
1769 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1771 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1773 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1774 // This unwrap chain should have been checked by the proc-macro harness.
1775 name = attr.meta_item_list().unwrap()[0]
1783 bug!("Unknown proc-macro type for item {:?}", id);
1786 let mut def_key = self.tcx.hir().def_key(id);
1787 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1789 let def_id = id.to_def_id();
1790 self.tables.opt_def_kind.set(def_id.index, DefKind::Macro(macro_kind));
1791 self.tables.proc_macro.set(def_id.index, macro_kind);
1792 self.encode_attrs(id);
1793 record!(self.tables.def_keys[def_id] <- def_key);
1794 record!(self.tables.def_ident_span[def_id] <- span);
1795 record!(self.tables.def_span[def_id] <- span);
1796 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1797 if let Some(stability) = stability {
1798 record!(self.tables.lookup_stability[def_id] <- stability);
1802 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1808 fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1809 empty_proc_macro!(self);
1810 self.lazy_array(self.tcx.debugger_visualizers(LOCAL_CRATE).iter())
1813 fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1814 empty_proc_macro!(self);
1821 let dep = CrateDep {
1822 name: self.tcx.crate_name(cnum),
1823 hash: self.tcx.crate_hash(cnum),
1824 host_hash: self.tcx.crate_host_hash(cnum),
1825 kind: self.tcx.dep_kind(cnum),
1826 extra_filename: self.tcx.extra_filename(cnum).clone(),
1830 .collect::<Vec<_>>();
1833 // Sanity-check the crate numbers
1834 let mut expected_cnum = 1;
1835 for &(n, _) in &deps {
1836 assert_eq!(n, CrateNum::new(expected_cnum));
1841 // We're just going to write a list of crate 'name-hash-version's, with
1842 // the assumption that they are numbered 1 to n.
1843 // FIXME (#2166): This is not nearly enough to support correct versioning
1844 // but is enough to get transitive crate dependencies working.
1845 self.lazy_array(deps.iter().map(|(_, dep)| dep))
1848 fn encode_lib_features(&mut self) -> LazyArray<(Symbol, Option<Symbol>)> {
1849 empty_proc_macro!(self);
1851 let lib_features = tcx.lib_features(());
1852 self.lazy_array(lib_features.to_vec())
1855 fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
1856 empty_proc_macro!(self);
1858 let implications = tcx.stability_implications(LOCAL_CRATE);
1859 self.lazy_array(implications.iter().map(|(k, v)| (*k, *v)))
1862 fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
1863 empty_proc_macro!(self);
1865 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1866 self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1869 fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
1870 empty_proc_macro!(self);
1871 let lang_items = self.tcx.lang_items().iter();
1872 self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
1873 def_id.as_local().map(|id| (id.local_def_index, lang_item))
1877 fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
1878 empty_proc_macro!(self);
1880 self.lazy_array(&tcx.lang_items().missing)
1883 fn encode_traits(&mut self) -> LazyArray<DefIndex> {
1884 empty_proc_macro!(self);
1885 self.lazy_array(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index))
1888 /// Encodes an index, mapping each trait to its (local) implementations.
1889 fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
1890 debug!("EncodeContext::encode_traits_and_impls()");
1891 empty_proc_macro!(self);
1893 let mut fx_hash_map: FxHashMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
1894 FxHashMap::default();
1896 for id in tcx.hir().items() {
1897 if matches!(tcx.def_kind(id.owner_id), DefKind::Impl) {
1898 if let Some(trait_ref) = tcx.impl_trait_ref(id.owner_id) {
1899 let trait_ref = trait_ref.subst_identity();
1901 let simplified_self_ty = fast_reject::simplify_type(
1903 trait_ref.self_ty(),
1904 TreatParams::AsInfer,
1908 .entry(trait_ref.def_id)
1910 .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
1915 let mut all_impls: Vec<_> = fx_hash_map.into_iter().collect();
1917 // Bring everything into deterministic order for hashing
1918 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1920 let all_impls: Vec<_> = all_impls
1922 .map(|(trait_def_id, mut impls)| {
1923 // Bring everything into deterministic order for hashing
1924 impls.sort_by_cached_key(|&(index, _)| {
1925 tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1929 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1930 impls: self.lazy_array(&impls),
1935 self.lazy_array(&all_impls)
1938 fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
1939 debug!("EncodeContext::encode_traits_and_impls()");
1940 empty_proc_macro!(self);
1942 let mut all_impls: Vec<_> = tcx.crate_inherent_impls(()).incoherent_impls.iter().collect();
1943 tcx.with_stable_hashing_context(|mut ctx| {
1944 all_impls.sort_by_cached_key(|&(&simp, _)| {
1945 let mut hasher = StableHasher::new();
1946 simp.hash_stable(&mut ctx, &mut hasher);
1947 hasher.finish::<Fingerprint>()
1950 let all_impls: Vec<_> = all_impls
1952 .map(|(&simp, impls)| {
1953 let mut impls: Vec<_> =
1954 impls.into_iter().map(|def_id| def_id.local_def_index).collect();
1955 impls.sort_by_cached_key(|&local_def_index| {
1956 tcx.hir().def_path_hash(LocalDefId { local_def_index })
1959 IncoherentImpls { self_ty: simp, impls: self.lazy_array(impls) }
1963 self.lazy_array(&all_impls)
1966 // Encodes all symbols exported from this crate into the metadata.
1968 // This pass is seeded off the reachability list calculated in the
1969 // middle::reachable module but filters out items that either don't have a
1970 // symbol associated with them (they weren't translated) or if they're an FFI
1971 // definition (as that's not defined in this crate).
1972 fn encode_exported_symbols(
1974 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
1975 ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
1976 empty_proc_macro!(self);
1977 // The metadata symbol name is special. It should not show up in
1978 // downstream crates.
1979 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1984 .filter(|&(exported_symbol, _)| match *exported_symbol {
1985 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1992 fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
1993 empty_proc_macro!(self);
1994 let formats = self.tcx.dependency_formats(());
1995 for (ty, arr) in formats.iter() {
1996 if *ty != CrateType::Dylib {
1999 return self.lazy_array(arr.iter().map(|slot| match *slot {
2000 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2002 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2003 Linkage::Static => Some(LinkagePreference::RequireStatic),
2009 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
2012 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
2015 hir::ForeignItemKind::Fn(_, ref names, _) => {
2016 self.tables.asyncness.set(def_id.index, hir::IsAsync::NotAsync);
2017 record_array!(self.tables.fn_arg_names[def_id] <- *names);
2018 let constness = if self.tcx.is_const_fn_raw(def_id) {
2019 hir::Constness::Const
2021 hir::Constness::NotConst
2023 self.tables.constness.set(def_id.index, constness);
2024 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
2026 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => {}
2028 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
2029 if tcx.is_intrinsic(def_id) {
2030 self.tables.is_intrinsic.set(def_id.index, ());
2036 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
2037 impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> {
2038 type NestedFilter = nested_filter::OnlyBodies;
2040 fn nested_visit_map(&mut self) -> Self::Map {
2043 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2044 intravisit::walk_expr(self, ex);
2045 self.encode_info_for_expr(ex);
2047 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
2048 intravisit::walk_item(self, item);
2050 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
2051 _ => self.encode_info_for_item(item.owner_id.to_def_id(), item),
2054 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
2055 intravisit::walk_foreign_item(self, ni);
2056 self.encode_info_for_foreign_item(ni.owner_id.to_def_id(), ni);
2058 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
2059 intravisit::walk_generics(self, generics);
2060 self.encode_info_for_generics(generics);
2064 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
2065 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
2066 for param in generics.params {
2068 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => {}
2069 hir::GenericParamKind::Const { ref default, .. } => {
2070 let def_id = param.def_id.to_def_id();
2071 if default.is_some() {
2072 record!(self.tables.const_param_default[def_id] <- self.tcx.const_param_default(def_id))
2079 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
2080 if let hir::ExprKind::Closure(closure) = expr.kind {
2081 self.encode_info_for_closure(closure.def_id);
2086 /// Used to prefetch queries which will be needed later by metadata encoding.
2087 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2088 fn prefetch_mir(tcx: TyCtxt<'_>) {
2089 if !tcx.sess.opts.output_types.should_codegen() {
2090 // We won't emit MIR, so don't prefetch it.
2094 par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2095 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2098 tcx.ensure().mir_for_ctfe(def_id);
2101 tcx.ensure().optimized_mir(def_id);
2103 if encode_opt || encode_const {
2104 tcx.ensure().promoted_mir(def_id);
2109 // NOTE(eddyb) The following comment was preserved for posterity, even
2110 // though it's no longer relevant as EBML (which uses nested & tagged
2111 // "documents") was replaced with a scheme that can't go out of bounds.
2113 // And here we run into yet another obscure archive bug: in which metadata
2114 // loaded from archives may have trailing garbage bytes. Awhile back one of
2115 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2116 // and opt) by having ebml generate an out-of-bounds panic when looking at
2119 // Upon investigation it turned out that the metadata file inside of an rlib
2120 // (and ar archive) was being corrupted. Some compilations would generate a
2121 // metadata file which would end in a few extra bytes, while other
2122 // compilations would not have these extra bytes appended to the end. These
2123 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2124 // being interpreted causing the out-of-bounds.
2126 // The root cause of why these extra bytes were appearing was never
2127 // discovered, and in the meantime the solution we're employing is to insert
2128 // the length of the metadata to the start of the metadata. Later on this
2129 // will allow us to slice the metadata to the precise length that we just
2130 // generated regardless of trailing bytes that end up in it.
2132 pub struct EncodedMetadata {
2133 // The declaration order matters because `mmap` should be dropped before `_temp_dir`.
2135 // We need to carry MaybeTempDir to avoid deleting the temporary
2136 // directory while accessing the Mmap.
2137 _temp_dir: Option<MaybeTempDir>,
2140 impl EncodedMetadata {
2142 pub fn from_path(path: PathBuf, temp_dir: Option<MaybeTempDir>) -> std::io::Result<Self> {
2143 let file = std::fs::File::open(&path)?;
2144 let file_metadata = file.metadata()?;
2145 if file_metadata.len() == 0 {
2146 return Ok(Self { mmap: None, _temp_dir: None });
2148 let mmap = unsafe { Some(Mmap::map(file)?) };
2149 Ok(Self { mmap, _temp_dir: temp_dir })
2153 pub fn raw_data(&self) -> &[u8] {
2154 self.mmap.as_deref().unwrap_or_default()
2158 impl<S: Encoder> Encodable<S> for EncodedMetadata {
2159 fn encode(&self, s: &mut S) {
2160 let slice = self.raw_data();
2165 impl<D: Decoder> Decodable<D> for EncodedMetadata {
2166 fn decode(d: &mut D) -> Self {
2167 let len = d.read_usize();
2168 let mmap = if len > 0 {
2169 let mut mmap = MmapMut::map_anon(len).unwrap();
2171 (&mut mmap[..]).write(&[d.read_u8()]).unwrap();
2173 mmap.flush().unwrap();
2174 Some(mmap.make_read_only().unwrap())
2179 Self { mmap, _temp_dir: None }
2183 pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path) {
2184 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2186 // Since encoding metadata is not in a query, and nothing is cached,
2187 // there's no need to do dep-graph tracking for any of it.
2188 tcx.dep_graph.assert_ignored();
2191 || encode_metadata_impl(tcx, path),
2193 if tcx.sess.threads() == 1 {
2196 // Prefetch some queries used by metadata encoding.
2197 // This is not necessary for correctness, but is only done for performance reasons.
2198 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2199 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2204 fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) {
2205 let mut encoder = opaque::FileEncoder::new(path)
2206 .unwrap_or_else(|err| tcx.sess.emit_fatal(FailCreateFileEncoder { err }));
2207 encoder.emit_raw_bytes(METADATA_HEADER);
2209 // Will be filled with the root position after encoding everything.
2210 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2212 let source_map_files = tcx.sess.source_map().files();
2213 let source_file_cache = (source_map_files[0].clone(), 0);
2214 let required_source_files = Some(FxIndexSet::default());
2215 drop(source_map_files);
2217 let hygiene_ctxt = HygieneEncodeContext::default();
2219 let mut ecx = EncodeContext {
2222 feat: tcx.features(),
2223 tables: Default::default(),
2224 lazy_state: LazyState::NoNode,
2225 type_shorthands: Default::default(),
2226 predicate_shorthands: Default::default(),
2228 interpret_allocs: Default::default(),
2229 required_source_files,
2230 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2231 hygiene_ctxt: &hygiene_ctxt,
2232 symbol_table: Default::default(),
2235 // Encode the rustc version string in a predictable location.
2236 rustc_version().encode(&mut ecx);
2238 // Encode all the entries and extra information in the crate,
2239 // culminating in the `CrateRoot` which points to all of it.
2240 let root = ecx.encode_crate_root();
2244 let mut file = ecx.opaque.file();
2245 // We will return to this position after writing the root position.
2246 let pos_before_seek = file.stream_position().unwrap();
2248 // Encode the root position.
2249 let header = METADATA_HEADER.len();
2250 file.seek(std::io::SeekFrom::Start(header as u64))
2251 .unwrap_or_else(|err| tcx.sess.emit_fatal(FailSeekFile { err }));
2252 let pos = root.position.get();
2253 file.write_all(&[(pos >> 24) as u8, (pos >> 16) as u8, (pos >> 8) as u8, (pos >> 0) as u8])
2254 .unwrap_or_else(|err| tcx.sess.emit_fatal(FailWriteFile { err }));
2256 // Return to the position where we are before writing the root position.
2257 file.seek(std::io::SeekFrom::Start(pos_before_seek)).unwrap();
2259 // Record metadata size for self-profiling
2260 tcx.prof.artifact_size(
2263 file.metadata().unwrap().len() as u64,
2267 pub fn provide(providers: &mut Providers) {
2268 *providers = Providers {
2269 traits_in_crate: |tcx, cnum| {
2270 assert_eq!(cnum, LOCAL_CRATE);
2272 let mut traits = Vec::new();
2273 for id in tcx.hir().items() {
2274 if matches!(tcx.def_kind(id.owner_id), DefKind::Trait | DefKind::TraitAlias) {
2275 traits.push(id.owner_id.to_def_id())
2279 // Bring everything into deterministic order.
2280 traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
2281 tcx.arena.alloc_slice(&traits)