rustc_metadata/rmeta/
encoder.rs

1use std::borrow::Borrow;
2use std::collections::hash_map::Entry;
3use std::fs::File;
4use std::io::{Read, Seek, Write};
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
9use rustc_data_structures::memmap::{Mmap, MmapMut};
10use rustc_data_structures::sync::{join, par_for_each_in};
11use rustc_data_structures::temp_dir::MaybeTempDir;
12use rustc_data_structures::thousands::usize_with_underscores;
13use rustc_feature::Features;
14use rustc_hir as hir;
15use rustc_hir::attrs::{AttributeKind, EncodeCrossCrate};
16use rustc_hir::def_id::{CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE, LocalDefId, LocalDefIdSet};
17use rustc_hir::definitions::DefPathData;
18use rustc_hir::find_attr;
19use rustc_hir_pretty::id_to_string;
20use rustc_middle::dep_graph::WorkProductId;
21use rustc_middle::middle::dependency_format::Linkage;
22use rustc_middle::mir::interpret;
23use rustc_middle::query::Providers;
24use rustc_middle::traits::specialization_graph;
25use rustc_middle::ty::AssocContainer;
26use rustc_middle::ty::codec::TyEncoder;
27use rustc_middle::ty::fast_reject::{self, TreatParams};
28use rustc_middle::{bug, span_bug};
29use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque};
30use rustc_session::config::{CrateType, OptLevel, TargetModifier};
31use rustc_span::hygiene::HygieneEncodeContext;
32use rustc_span::{
33    ByteSymbol, ExternalSource, FileName, SourceFile, SpanData, SpanEncoder, StableSourceFileId,
34    Symbol, SyntaxContext, sym,
35};
36use tracing::{debug, instrument, trace};
37
38use crate::eii::EiiMapEncodedKeyValue;
39use crate::errors::{FailCreateFileEncoder, FailWriteFile};
40use crate::rmeta::*;
41
42pub(super) struct EncodeContext<'a, 'tcx> {
43    opaque: opaque::FileEncoder,
44    tcx: TyCtxt<'tcx>,
45    feat: &'tcx rustc_feature::Features,
46    tables: TableBuilders,
47
48    lazy_state: LazyState,
49    span_shorthands: FxHashMap<Span, usize>,
50    type_shorthands: FxHashMap<Ty<'tcx>, usize>,
51    predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
52
53    interpret_allocs: FxIndexSet<interpret::AllocId>,
54
55    // This is used to speed up Span encoding.
56    // The `usize` is an index into the `MonotonicVec`
57    // that stores the `SourceFile`
58    source_file_cache: (Arc<SourceFile>, usize),
59    // The indices (into the `SourceMap`'s `MonotonicVec`)
60    // of all of the `SourceFiles` that we need to serialize.
61    // When we serialize a `Span`, we insert the index of its
62    // `SourceFile` into the `FxIndexSet`.
63    // The order inside the `FxIndexSet` is used as on-disk
64    // order of `SourceFiles`, and encoded inside `Span`s.
65    required_source_files: Option<FxIndexSet<usize>>,
66    is_proc_macro: bool,
67    hygiene_ctxt: &'a HygieneEncodeContext,
68    // Used for both `Symbol`s and `ByteSymbol`s.
69    symbol_index_table: FxHashMap<u32, usize>,
70}
71
72/// If the current crate is a proc-macro, returns early with `LazyArray::default()`.
73/// This is useful for skipping the encoding of things that aren't needed
74/// for proc-macro crates.
75macro_rules! empty_proc_macro {
76    ($self:ident) => {
77        if $self.is_proc_macro {
78            return LazyArray::default();
79        }
80    };
81}
82
83macro_rules! encoder_methods {
84    ($($name:ident($ty:ty);)*) => {
85        $(fn $name(&mut self, value: $ty) {
86            self.opaque.$name(value)
87        })*
88    }
89}
90
91impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
92    encoder_methods! {
93        emit_usize(usize);
94        emit_u128(u128);
95        emit_u64(u64);
96        emit_u32(u32);
97        emit_u16(u16);
98        emit_u8(u8);
99
100        emit_isize(isize);
101        emit_i128(i128);
102        emit_i64(i64);
103        emit_i32(i32);
104        emit_i16(i16);
105
106        emit_raw_bytes(&[u8]);
107    }
108}
109
110impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
111    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
112        e.emit_lazy_distance(self.position);
113    }
114}
115
116impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
117    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
118        e.emit_usize(self.num_elems);
119        if self.num_elems > 0 {
120            e.emit_lazy_distance(self.position)
121        }
122    }
123}
124
125impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
126    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
127        e.emit_usize(self.width);
128        e.emit_usize(self.len);
129        e.emit_lazy_distance(self.position);
130    }
131}
132
133impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
134    fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
135        s.emit_u32(self.as_u32());
136    }
137}
138
139impl<'a, 'tcx> SpanEncoder for EncodeContext<'a, 'tcx> {
140    fn encode_crate_num(&mut self, crate_num: CrateNum) {
141        if crate_num != LOCAL_CRATE && self.is_proc_macro {
142            panic!("Attempted to encode non-local CrateNum {crate_num:?} for proc-macro crate");
143        }
144        self.emit_u32(crate_num.as_u32());
145    }
146
147    fn encode_def_index(&mut self, def_index: DefIndex) {
148        self.emit_u32(def_index.as_u32());
149    }
150
151    fn encode_def_id(&mut self, def_id: DefId) {
152        def_id.krate.encode(self);
153        def_id.index.encode(self);
154    }
155
156    fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
157        rustc_span::hygiene::raw_encode_syntax_context(syntax_context, self.hygiene_ctxt, self);
158    }
159
160    fn encode_expn_id(&mut self, expn_id: ExpnId) {
161        if expn_id.krate == LOCAL_CRATE {
162            // We will only write details for local expansions. Non-local expansions will fetch
163            // data from the corresponding crate's metadata.
164            // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
165            // metadata from proc-macro crates.
166            self.hygiene_ctxt.schedule_expn_data_for_encoding(expn_id);
167        }
168        expn_id.krate.encode(self);
169        expn_id.local_id.encode(self);
170    }
171
172    fn encode_span(&mut self, span: Span) {
173        match self.span_shorthands.entry(span) {
174            Entry::Occupied(o) => {
175                // If an offset is smaller than the absolute position, we encode with the offset.
176                // This saves space since smaller numbers encode in less bits.
177                let last_location = *o.get();
178                // This cannot underflow. Metadata is written with increasing position(), so any
179                // previously saved offset must be smaller than the current position.
180                let offset = self.opaque.position() - last_location;
181                if offset < last_location {
182                    let needed = bytes_needed(offset);
183                    SpanTag::indirect(true, needed as u8).encode(self);
184                    self.opaque.write_with(|dest| {
185                        *dest = offset.to_le_bytes();
186                        needed
187                    });
188                } else {
189                    let needed = bytes_needed(last_location);
190                    SpanTag::indirect(false, needed as u8).encode(self);
191                    self.opaque.write_with(|dest| {
192                        *dest = last_location.to_le_bytes();
193                        needed
194                    });
195                }
196            }
197            Entry::Vacant(v) => {
198                let position = self.opaque.position();
199                v.insert(position);
200                // Data is encoded with a SpanTag prefix (see below).
201                span.data().encode(self);
202            }
203        }
204    }
205
206    fn encode_symbol(&mut self, sym: Symbol) {
207        self.encode_symbol_or_byte_symbol(sym.as_u32(), |this| this.emit_str(sym.as_str()));
208    }
209
210    fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
211        self.encode_symbol_or_byte_symbol(byte_sym.as_u32(), |this| {
212            this.emit_byte_str(byte_sym.as_byte_str())
213        });
214    }
215}
216
217fn bytes_needed(n: usize) -> usize {
218    (usize::BITS - n.leading_zeros()).div_ceil(u8::BITS) as usize
219}
220
221impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SpanData {
222    fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
223        // Don't serialize any `SyntaxContext`s from a proc-macro crate,
224        // since we don't load proc-macro dependencies during serialization.
225        // This means that any hygiene information from macros used *within*
226        // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
227        // definition) will be lost.
228        //
229        // This can show up in two ways:
230        //
231        // 1. Any hygiene information associated with identifier of
232        // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
233        // Since proc-macros can only be invoked from a different crate,
234        // real code should never need to care about this.
235        //
236        // 2. Using `Span::def_site` or `Span::mixed_site` will not
237        // include any hygiene information associated with the definition
238        // site. This means that a proc-macro cannot emit a `$crate`
239        // identifier which resolves to one of its dependencies,
240        // which also should never come up in practice.
241        //
242        // Additionally, this affects `Span::parent`, and any other
243        // span inspection APIs that would otherwise allow traversing
244        // the `SyntaxContexts` associated with a span.
245        //
246        // None of these user-visible effects should result in any
247        // cross-crate inconsistencies (getting one behavior in the same
248        // crate, and a different behavior in another crate) due to the
249        // limited surface that proc-macros can expose.
250        //
251        // IMPORTANT: If this is ever changed, be sure to update
252        // `rustc_span::hygiene::raw_encode_expn_id` to handle
253        // encoding `ExpnData` for proc-macro crates.
254        let ctxt = if s.is_proc_macro { SyntaxContext::root() } else { self.ctxt };
255
256        if self.is_dummy() {
257            let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
258            tag.encode(s);
259            if tag.context().is_none() {
260                ctxt.encode(s);
261            }
262            return;
263        }
264
265        // The Span infrastructure should make sure that this invariant holds:
266        debug_assert!(self.lo <= self.hi);
267
268        if !s.source_file_cache.0.contains(self.lo) {
269            let source_map = s.tcx.sess.source_map();
270            let source_file_index = source_map.lookup_source_file_idx(self.lo);
271            s.source_file_cache =
272                (Arc::clone(&source_map.files()[source_file_index]), source_file_index);
273        }
274        let (ref source_file, source_file_index) = s.source_file_cache;
275        debug_assert!(source_file.contains(self.lo));
276
277        if !source_file.contains(self.hi) {
278            // Unfortunately, macro expansion still sometimes generates Spans
279            // that malformed in this way.
280            let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
281            tag.encode(s);
282            if tag.context().is_none() {
283                ctxt.encode(s);
284            }
285            return;
286        }
287
288        // There are two possible cases here:
289        // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
290        // crate we are writing metadata for. When the metadata for *this* crate gets
291        // deserialized, the deserializer will need to know which crate it originally came
292        // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
293        // be deserialized after the rest of the span data, which tells the deserializer
294        // which crate contains the source map information.
295        // 2. This span comes from our own crate. No special handling is needed - we just
296        // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
297        // our own source map information.
298        //
299        // If we're a proc-macro crate, we always treat this as a local `Span`.
300        // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
301        // if we're a proc-macro crate.
302        // This allows us to avoid loading the dependencies of proc-macro crates: all of
303        // the information we need to decode `Span`s is stored in the proc-macro crate.
304        let (kind, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
305            // To simplify deserialization, we 'rebase' this span onto the crate it originally came
306            // from (the crate that 'owns' the file it references. These rebased 'lo' and 'hi'
307            // values are relative to the source map information for the 'foreign' crate whose
308            // CrateNum we write into the metadata. This allows `imported_source_files` to binary
309            // search through the 'foreign' crate's source map information, using the
310            // deserialized 'lo' and 'hi' values directly.
311            //
312            // All of this logic ensures that the final result of deserialization is a 'normal'
313            // Span that can be used without any additional trouble.
314            let metadata_index = {
315                // Introduce a new scope so that we drop the 'read()' temporary
316                match &*source_file.external_src.read() {
317                    ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
318                    src => panic!("Unexpected external source {src:?}"),
319                }
320            };
321
322            (SpanKind::Foreign, metadata_index)
323        } else {
324            // Record the fact that we need to encode the data for this `SourceFile`
325            let source_files =
326                s.required_source_files.as_mut().expect("Already encoded SourceMap!");
327            let (metadata_index, _) = source_files.insert_full(source_file_index);
328            let metadata_index: u32 =
329                metadata_index.try_into().expect("cannot export more than U32_MAX files");
330
331            (SpanKind::Local, metadata_index)
332        };
333
334        // Encode the start position relative to the file start, so we profit more from the
335        // variable-length integer encoding.
336        let lo = self.lo - source_file.start_pos;
337
338        // Encode length which is usually less than span.hi and profits more
339        // from the variable-length integer encoding that we use.
340        let len = self.hi - self.lo;
341
342        let tag = SpanTag::new(kind, ctxt, len.0 as usize);
343        tag.encode(s);
344        if tag.context().is_none() {
345            ctxt.encode(s);
346        }
347        lo.encode(s);
348        if tag.length().is_none() {
349            len.encode(s);
350        }
351
352        // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
353        metadata_index.encode(s);
354
355        if kind == SpanKind::Foreign {
356            // This needs to be two lines to avoid holding the `s.source_file_cache`
357            // while calling `cnum.encode(s)`
358            let cnum = s.source_file_cache.0.cnum;
359            cnum.encode(s);
360        }
361    }
362}
363
364impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for [u8] {
365    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
366        Encoder::emit_usize(e, self.len());
367        e.emit_raw_bytes(self);
368    }
369}
370
371impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
372    const CLEAR_CROSS_CRATE: bool = true;
373
374    fn position(&self) -> usize {
375        self.opaque.position()
376    }
377
378    fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
379        &mut self.type_shorthands
380    }
381
382    fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
383        &mut self.predicate_shorthands
384    }
385
386    fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
387        let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
388
389        index.encode(self);
390    }
391}
392
393// Shorthand for `$self.$tables.$table.set_some($def_id.index, $self.lazy($value))`, which would
394// normally need extra variables to avoid errors about multiple mutable borrows.
395macro_rules! record {
396    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
397        {
398            let value = $value;
399            let lazy = $self.lazy(value);
400            $self.$tables.$table.set_some($def_id.index, lazy);
401        }
402    }};
403}
404
405// Shorthand for `$self.$tables.$table.set_some($def_id.index, $self.lazy_array($value))`, which would
406// normally need extra variables to avoid errors about multiple mutable borrows.
407macro_rules! record_array {
408    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
409        {
410            let value = $value;
411            let lazy = $self.lazy_array(value);
412            $self.$tables.$table.set_some($def_id.index, lazy);
413        }
414    }};
415}
416
417macro_rules! record_defaulted_array {
418    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
419        {
420            let value = $value;
421            let lazy = $self.lazy_array(value);
422            $self.$tables.$table.set($def_id.index, lazy);
423        }
424    }};
425}
426
427impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
428    fn emit_lazy_distance(&mut self, position: NonZero<usize>) {
429        let pos = position.get();
430        let distance = match self.lazy_state {
431            LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
432            LazyState::NodeStart(start) => {
433                let start = start.get();
434                assert!(pos <= start);
435                start - pos
436            }
437            LazyState::Previous(last_pos) => {
438                assert!(
439                    last_pos <= position,
440                    "make sure that the calls to `lazy*` \
441                     are in the same order as the metadata fields",
442                );
443                position.get() - last_pos.get()
444            }
445        };
446        self.lazy_state = LazyState::Previous(NonZero::new(pos).unwrap());
447        self.emit_usize(distance);
448    }
449
450    fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
451    where
452        T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
453    {
454        let pos = NonZero::new(self.position()).unwrap();
455
456        assert_eq!(self.lazy_state, LazyState::NoNode);
457        self.lazy_state = LazyState::NodeStart(pos);
458        value.borrow().encode(self);
459        self.lazy_state = LazyState::NoNode;
460
461        assert!(pos.get() <= self.position());
462
463        LazyValue::from_position(pos)
464    }
465
466    fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
467        &mut self,
468        values: I,
469    ) -> LazyArray<T>
470    where
471        T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
472    {
473        let pos = NonZero::new(self.position()).unwrap();
474
475        assert_eq!(self.lazy_state, LazyState::NoNode);
476        self.lazy_state = LazyState::NodeStart(pos);
477        let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
478        self.lazy_state = LazyState::NoNode;
479
480        assert!(pos.get() <= self.position());
481
482        LazyArray::from_position_and_num_elems(pos, len)
483    }
484
485    fn encode_symbol_or_byte_symbol(
486        &mut self,
487        index: u32,
488        emit_str_or_byte_str: impl Fn(&mut Self),
489    ) {
490        // if symbol/byte symbol is predefined, emit tag and symbol index
491        if Symbol::is_predefined(index) {
492            self.opaque.emit_u8(SYMBOL_PREDEFINED);
493            self.opaque.emit_u32(index);
494        } else {
495            // otherwise write it as string or as offset to it
496            match self.symbol_index_table.entry(index) {
497                Entry::Vacant(o) => {
498                    self.opaque.emit_u8(SYMBOL_STR);
499                    let pos = self.opaque.position();
500                    o.insert(pos);
501                    emit_str_or_byte_str(self);
502                }
503                Entry::Occupied(o) => {
504                    let x = *o.get();
505                    self.emit_u8(SYMBOL_OFFSET);
506                    self.emit_usize(x);
507                }
508            }
509        }
510    }
511
512    fn encode_def_path_table(&mut self) {
513        let table = self.tcx.def_path_table();
514        if self.is_proc_macro {
515            for def_index in std::iter::once(CRATE_DEF_INDEX)
516                .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
517            {
518                let def_key = self.lazy(table.def_key(def_index));
519                let def_path_hash = table.def_path_hash(def_index);
520                self.tables.def_keys.set_some(def_index, def_key);
521                self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
522            }
523        } else {
524            for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
525                let def_key = self.lazy(def_key);
526                self.tables.def_keys.set_some(def_index, def_key);
527                self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
528            }
529        }
530    }
531
532    fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
533        self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
534    }
535
536    fn encode_source_map(&mut self) -> LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>> {
537        let source_map = self.tcx.sess.source_map();
538        let all_source_files = source_map.files();
539
540        // By replacing the `Option` with `None`, we ensure that we can't
541        // accidentally serialize any more `Span`s after the source map encoding
542        // is done.
543        let required_source_files = self.required_source_files.take().unwrap();
544
545        let mut adapted = TableBuilder::default();
546
547        let local_crate_stable_id = self.tcx.stable_crate_id(LOCAL_CRATE);
548
549        // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
550        //
551        // The order in which we encode source files is important here: the on-disk format for
552        // `Span` contains the index of the corresponding `SourceFile`.
553        for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
554            let source_file = &all_source_files[source_file_index];
555            // Don't serialize imported `SourceFile`s, unless we're in a proc-macro crate.
556            assert!(!source_file.is_imported() || self.is_proc_macro);
557
558            // At export time we expand all source file paths to absolute paths because
559            // downstream compilation sessions can have a different compiler working
560            // directory, so relative paths from this or any other upstream crate
561            // won't be valid anymore.
562            //
563            // At this point we also erase the actual on-disk path and only keep
564            // the remapped version -- as is necessary for reproducible builds.
565            let mut adapted_source_file = (**source_file).clone();
566
567            match source_file.name {
568                FileName::Real(ref original_file_name) => {
569                    let mut adapted_file_name = original_file_name.clone();
570                    adapted_file_name.update_for_crate_metadata();
571                    adapted_source_file.name = FileName::Real(adapted_file_name);
572                }
573                _ => {
574                    // expanded code, not from a file
575                }
576            };
577
578            // We're serializing this `SourceFile` into our crate metadata,
579            // so mark it as coming from this crate.
580            // This also ensures that we don't try to deserialize the
581            // `CrateNum` for a proc-macro dependency - since proc macro
582            // dependencies aren't loaded when we deserialize a proc-macro,
583            // trying to remap the `CrateNum` would fail.
584            if self.is_proc_macro {
585                adapted_source_file.cnum = LOCAL_CRATE;
586            }
587
588            // Update the `StableSourceFileId` to make sure it incorporates the
589            // id of the current crate. This way it will be unique within the
590            // crate graph during downstream compilation sessions.
591            adapted_source_file.stable_id = StableSourceFileId::from_filename_for_export(
592                &adapted_source_file.name,
593                local_crate_stable_id,
594            );
595
596            let on_disk_index: u32 =
597                on_disk_index.try_into().expect("cannot export more than U32_MAX files");
598            adapted.set_some(on_disk_index, self.lazy(adapted_source_file));
599        }
600
601        adapted.encode(&mut self.opaque)
602    }
603
604    fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
605        let tcx = self.tcx;
606        let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
607
608        macro_rules! stat {
609            ($label:literal, $f:expr) => {{
610                let orig_pos = self.position();
611                let res = $f();
612                stats.push(($label, self.position() - orig_pos));
613                res
614            }};
615        }
616
617        // We have already encoded some things. Get their combined size from the current position.
618        stats.push(("preamble", self.position()));
619
620        let externally_implementable_items = stat!("externally-implementable-items", || self
621            .encode_externally_implementable_items());
622
623        let (crate_deps, dylib_dependency_formats) =
624            stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
625
626        let lib_features = stat!("lib-features", || self.encode_lib_features());
627
628        let stability_implications =
629            stat!("stability-implications", || self.encode_stability_implications());
630
631        let (lang_items, lang_items_missing) = stat!("lang-items", || {
632            (self.encode_lang_items(), self.encode_lang_items_missing())
633        });
634
635        let stripped_cfg_items = stat!("stripped-cfg-items", || self.encode_stripped_cfg_items());
636
637        let diagnostic_items = stat!("diagnostic-items", || self.encode_diagnostic_items());
638
639        let native_libraries = stat!("native-libs", || self.encode_native_libraries());
640
641        let foreign_modules = stat!("foreign-modules", || self.encode_foreign_modules());
642
643        _ = stat!("def-path-table", || self.encode_def_path_table());
644
645        // Encode the def IDs of traits, for rustdoc and diagnostics.
646        let traits = stat!("traits", || self.encode_traits());
647
648        // Encode the def IDs of impls, for coherence checking.
649        let impls = stat!("impls", || self.encode_impls());
650
651        let incoherent_impls = stat!("incoherent-impls", || self.encode_incoherent_impls());
652
653        _ = stat!("mir", || self.encode_mir());
654
655        _ = stat!("def-ids", || self.encode_def_ids());
656
657        let interpret_alloc_index = stat!("interpret-alloc-index", || {
658            let mut interpret_alloc_index = Vec::new();
659            let mut n = 0;
660            trace!("beginning to encode alloc ids");
661            loop {
662                let new_n = self.interpret_allocs.len();
663                // if we have found new ids, serialize those, too
664                if n == new_n {
665                    // otherwise, abort
666                    break;
667                }
668                trace!("encoding {} further alloc ids", new_n - n);
669                for idx in n..new_n {
670                    let id = self.interpret_allocs[idx];
671                    let pos = self.position() as u64;
672                    interpret_alloc_index.push(pos);
673                    interpret::specialized_encode_alloc_id(self, tcx, id);
674                }
675                n = new_n;
676            }
677            self.lazy_array(interpret_alloc_index)
678        });
679
680        // Encode the proc macro data. This affects `tables`, so we need to do this before we
681        // encode the tables. This overwrites def_keys, so it must happen after
682        // encode_def_path_table.
683        let proc_macro_data = stat!("proc-macro-data", || self.encode_proc_macros());
684
685        let tables = stat!("tables", || self.tables.encode(&mut self.opaque));
686
687        let debugger_visualizers =
688            stat!("debugger-visualizers", || self.encode_debugger_visualizers());
689
690        let exportable_items = stat!("exportable-items", || self.encode_exportable_items());
691
692        let stable_order_of_exportable_impls =
693            stat!("exportable-items", || self.encode_stable_order_of_exportable_impls());
694
695        // Encode exported symbols info. This is prefetched in `encode_metadata`.
696        let (exported_non_generic_symbols, exported_generic_symbols) =
697            stat!("exported-symbols", || {
698                (
699                    self.encode_exported_symbols(tcx.exported_non_generic_symbols(LOCAL_CRATE)),
700                    self.encode_exported_symbols(tcx.exported_generic_symbols(LOCAL_CRATE)),
701                )
702            });
703
704        // Encode the hygiene data.
705        // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The
706        // process of encoding other items (e.g. `optimized_mir`) may cause us to load data from
707        // the incremental cache. If this causes us to deserialize a `Span`, then we may load
708        // additional `SyntaxContext`s into the global `HygieneData`. Therefore, we need to encode
709        // the hygiene data last to ensure that we encode any `SyntaxContext`s that might be used.
710        let (syntax_contexts, expn_data, expn_hashes) = stat!("hygiene", || self.encode_hygiene());
711
712        let def_path_hash_map = stat!("def-path-hash-map", || self.encode_def_path_hash_map());
713
714        // Encode source_map. This needs to be done last, because encoding `Span`s tells us which
715        // `SourceFiles` we actually need to encode.
716        let source_map = stat!("source-map", || self.encode_source_map());
717        let target_modifiers = stat!("target-modifiers", || self.encode_target_modifiers());
718
719        let root = stat!("final", || {
720            let attrs = tcx.hir_krate_attrs();
721            self.lazy(CrateRoot {
722                header: CrateHeader {
723                    name: tcx.crate_name(LOCAL_CRATE),
724                    triple: tcx.sess.opts.target_triple.clone(),
725                    hash: tcx.crate_hash(LOCAL_CRATE),
726                    is_proc_macro_crate: proc_macro_data.is_some(),
727                    is_stub: false,
728                },
729                extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
730                stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
731                required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
732                panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
733                edition: tcx.sess.edition(),
734                has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
735                has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
736                has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
737                has_default_lib_allocator: ast::attr::contains_name(
738                    attrs,
739                    sym::default_lib_allocator,
740                ),
741                externally_implementable_items,
742                proc_macro_data,
743                debugger_visualizers,
744                compiler_builtins: ast::attr::contains_name(attrs, sym::compiler_builtins),
745                needs_allocator: ast::attr::contains_name(attrs, sym::needs_allocator),
746                needs_panic_runtime: ast::attr::contains_name(attrs, sym::needs_panic_runtime),
747                no_builtins: ast::attr::contains_name(attrs, sym::no_builtins),
748                panic_runtime: ast::attr::contains_name(attrs, sym::panic_runtime),
749                profiler_runtime: ast::attr::contains_name(attrs, sym::profiler_runtime),
750                symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
751
752                crate_deps,
753                dylib_dependency_formats,
754                lib_features,
755                stability_implications,
756                lang_items,
757                diagnostic_items,
758                lang_items_missing,
759                stripped_cfg_items,
760                native_libraries,
761                foreign_modules,
762                source_map,
763                target_modifiers,
764                traits,
765                impls,
766                incoherent_impls,
767                exportable_items,
768                stable_order_of_exportable_impls,
769                exported_non_generic_symbols,
770                exported_generic_symbols,
771                interpret_alloc_index,
772                tables,
773                syntax_contexts,
774                expn_data,
775                expn_hashes,
776                def_path_hash_map,
777                specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
778            })
779        });
780
781        let total_bytes = self.position();
782
783        let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
784        assert_eq!(total_bytes, computed_total_bytes);
785
786        if tcx.sess.opts.unstable_opts.meta_stats {
787            use std::fmt::Write;
788
789            self.opaque.flush();
790
791            // Rewind and re-read all the metadata to count the zero bytes we wrote.
792            let pos_before_rewind = self.opaque.file().stream_position().unwrap();
793            let mut zero_bytes = 0;
794            self.opaque.file().rewind().unwrap();
795            let file = std::io::BufReader::new(self.opaque.file());
796            for e in file.bytes() {
797                if e.unwrap() == 0 {
798                    zero_bytes += 1;
799                }
800            }
801            assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
802
803            stats.sort_by_key(|&(_, usize)| usize);
804            stats.reverse(); // bigger items first
805
806            let prefix = "meta-stats";
807            let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
808
809            let section_w = 23;
810            let size_w = 10;
811            let banner_w = 64;
812
813            // We write all the text into a string and print it with a single
814            // `eprint!`. This is an attempt to minimize interleaved text if multiple
815            // rustc processes are printing macro-stats at the same time (e.g. with
816            // `RUSTFLAGS='-Zmeta-stats' cargo build`). It still doesn't guarantee
817            // non-interleaving, though.
818            let mut s = String::new();
819            _ = writeln!(s, "{prefix} {}", "=".repeat(banner_w));
820            _ = writeln!(s, "{prefix} METADATA STATS: {}", tcx.crate_name(LOCAL_CRATE));
821            _ = writeln!(s, "{prefix} {:<section_w$}{:>size_w$}", "Section", "Size");
822            _ = writeln!(s, "{prefix} {}", "-".repeat(banner_w));
823            for (label, size) in stats {
824                _ = writeln!(
825                    s,
826                    "{prefix} {:<section_w$}{:>size_w$} ({:4.1}%)",
827                    label,
828                    usize_with_underscores(size),
829                    perc(size)
830                );
831            }
832            _ = writeln!(s, "{prefix} {}", "-".repeat(banner_w));
833            _ = writeln!(
834                s,
835                "{prefix} {:<section_w$}{:>size_w$} (of which {:.1}% are zero bytes)",
836                "Total",
837                usize_with_underscores(total_bytes),
838                perc(zero_bytes)
839            );
840            _ = writeln!(s, "{prefix} {}", "=".repeat(banner_w));
841            eprint!("{s}");
842        }
843
844        root
845    }
846}
847
848struct AnalyzeAttrState<'a> {
849    is_exported: bool,
850    is_doc_hidden: bool,
851    features: &'a Features,
852}
853
854/// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and
855/// useful in downstream crates. Local-only attributes are an obvious example, but some
856/// rustdoc-specific attributes can equally be of use while documenting the current crate only.
857///
858/// Removing these superfluous attributes speeds up compilation by making the metadata smaller.
859///
860/// Note: the `is_exported` parameter is used to cache whether the given `DefId` has a public
861/// visibility: this is a piece of data that can be computed once per defid, and not once per
862/// attribute. Some attributes would only be usable downstream if they are public.
863#[inline]
864fn analyze_attr(attr: &hir::Attribute, state: &mut AnalyzeAttrState<'_>) -> bool {
865    let mut should_encode = false;
866    if let hir::Attribute::Parsed(p) = attr
867        && p.encode_cross_crate() == EncodeCrossCrate::No
868    {
869        // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates.
870    } else if let Some(name) = attr.name()
871        && !rustc_feature::encode_cross_crate(name)
872    {
873        // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates.
874    } else if let hir::Attribute::Parsed(AttributeKind::DocComment { .. }) = attr {
875        // We keep all doc comments reachable to rustdoc because they might be "imported" into
876        // downstream crates if they use `#[doc(inline)]` to copy an item's documentation into
877        // their own.
878        if state.is_exported {
879            should_encode = true;
880        }
881    } else if let hir::Attribute::Parsed(AttributeKind::Doc(d)) = attr {
882        // If this is a `doc` attribute that doesn't have anything except maybe `inline` (as in
883        // `#[doc(inline)]`), then we can remove it. It won't be inlinable in downstream crates.
884        if d.inline.is_empty() {
885            should_encode = true;
886            if d.hidden.is_some() {
887                state.is_doc_hidden = true;
888            }
889        }
890    } else if let &[sym::diagnostic, seg] = &*attr.path() {
891        should_encode = rustc_feature::is_stable_diagnostic_attribute(seg, state.features);
892    } else {
893        should_encode = true;
894    }
895    should_encode
896}
897
898fn should_encode_span(def_kind: DefKind) -> bool {
899    match def_kind {
900        DefKind::Mod
901        | DefKind::Struct
902        | DefKind::Union
903        | DefKind::Enum
904        | DefKind::Variant
905        | DefKind::Trait
906        | DefKind::TyAlias
907        | DefKind::ForeignTy
908        | DefKind::TraitAlias
909        | DefKind::AssocTy
910        | DefKind::TyParam
911        | DefKind::ConstParam
912        | DefKind::LifetimeParam
913        | DefKind::Fn
914        | DefKind::Const
915        | DefKind::Static { .. }
916        | DefKind::Ctor(..)
917        | DefKind::AssocFn
918        | DefKind::AssocConst
919        | DefKind::Macro(_)
920        | DefKind::ExternCrate
921        | DefKind::Use
922        | DefKind::AnonConst
923        | DefKind::InlineConst
924        | DefKind::OpaqueTy
925        | DefKind::Field
926        | DefKind::Impl { .. }
927        | DefKind::Closure
928        | DefKind::SyntheticCoroutineBody => true,
929        DefKind::ForeignMod | DefKind::GlobalAsm => false,
930    }
931}
932
933fn should_encode_attrs(def_kind: DefKind) -> bool {
934    match def_kind {
935        DefKind::Mod
936        | DefKind::Struct
937        | DefKind::Union
938        | DefKind::Enum
939        | DefKind::Variant
940        | DefKind::Trait
941        | DefKind::TyAlias
942        | DefKind::ForeignTy
943        | DefKind::TraitAlias
944        | DefKind::AssocTy
945        | DefKind::Fn
946        | DefKind::Const
947        | DefKind::Static { nested: false, .. }
948        | DefKind::AssocFn
949        | DefKind::AssocConst
950        | DefKind::Macro(_)
951        | DefKind::Field
952        | DefKind::Impl { .. } => true,
953        // Tools may want to be able to detect their tool lints on
954        // closures from upstream crates, too. This is used by
955        // https://github.com/model-checking/kani and is not a performance
956        // or maintenance issue for us.
957        DefKind::Closure => true,
958        DefKind::SyntheticCoroutineBody => false,
959        DefKind::TyParam
960        | DefKind::ConstParam
961        | DefKind::Ctor(..)
962        | DefKind::ExternCrate
963        | DefKind::Use
964        | DefKind::ForeignMod
965        | DefKind::AnonConst
966        | DefKind::InlineConst
967        | DefKind::OpaqueTy
968        | DefKind::LifetimeParam
969        | DefKind::Static { nested: true, .. }
970        | DefKind::GlobalAsm => false,
971    }
972}
973
974fn should_encode_expn_that_defined(def_kind: DefKind) -> bool {
975    match def_kind {
976        DefKind::Mod
977        | DefKind::Struct
978        | DefKind::Union
979        | DefKind::Enum
980        | DefKind::Variant
981        | DefKind::Trait
982        | DefKind::Impl { .. } => true,
983        DefKind::TyAlias
984        | DefKind::ForeignTy
985        | DefKind::TraitAlias
986        | DefKind::AssocTy
987        | DefKind::TyParam
988        | DefKind::Fn
989        | DefKind::Const
990        | DefKind::ConstParam
991        | DefKind::Static { .. }
992        | DefKind::Ctor(..)
993        | DefKind::AssocFn
994        | DefKind::AssocConst
995        | DefKind::Macro(_)
996        | DefKind::ExternCrate
997        | DefKind::Use
998        | DefKind::ForeignMod
999        | DefKind::AnonConst
1000        | DefKind::InlineConst
1001        | DefKind::OpaqueTy
1002        | DefKind::Field
1003        | DefKind::LifetimeParam
1004        | DefKind::GlobalAsm
1005        | DefKind::Closure
1006        | DefKind::SyntheticCoroutineBody => false,
1007    }
1008}
1009
1010fn should_encode_visibility(def_kind: DefKind) -> bool {
1011    match def_kind {
1012        DefKind::Mod
1013        | DefKind::Struct
1014        | DefKind::Union
1015        | DefKind::Enum
1016        | DefKind::Variant
1017        | DefKind::Trait
1018        | DefKind::TyAlias
1019        | DefKind::ForeignTy
1020        | DefKind::TraitAlias
1021        | DefKind::AssocTy
1022        | DefKind::Fn
1023        | DefKind::Const
1024        | DefKind::Static { nested: false, .. }
1025        | DefKind::Ctor(..)
1026        | DefKind::AssocFn
1027        | DefKind::AssocConst
1028        | DefKind::Macro(..)
1029        | DefKind::Field => true,
1030        DefKind::Use
1031        | DefKind::ForeignMod
1032        | DefKind::TyParam
1033        | DefKind::ConstParam
1034        | DefKind::LifetimeParam
1035        | DefKind::AnonConst
1036        | DefKind::InlineConst
1037        | DefKind::Static { nested: true, .. }
1038        | DefKind::OpaqueTy
1039        | DefKind::GlobalAsm
1040        | DefKind::Impl { .. }
1041        | DefKind::Closure
1042        | DefKind::ExternCrate
1043        | DefKind::SyntheticCoroutineBody => false,
1044    }
1045}
1046
1047fn should_encode_stability(def_kind: DefKind) -> bool {
1048    match def_kind {
1049        DefKind::Mod
1050        | DefKind::Ctor(..)
1051        | DefKind::Variant
1052        | DefKind::Field
1053        | DefKind::Struct
1054        | DefKind::AssocTy
1055        | DefKind::AssocFn
1056        | DefKind::AssocConst
1057        | DefKind::TyParam
1058        | DefKind::ConstParam
1059        | DefKind::Static { .. }
1060        | DefKind::Const
1061        | DefKind::Fn
1062        | DefKind::ForeignMod
1063        | DefKind::TyAlias
1064        | DefKind::OpaqueTy
1065        | DefKind::Enum
1066        | DefKind::Union
1067        | DefKind::Impl { .. }
1068        | DefKind::Trait
1069        | DefKind::TraitAlias
1070        | DefKind::Macro(..)
1071        | DefKind::ForeignTy => true,
1072        DefKind::Use
1073        | DefKind::LifetimeParam
1074        | DefKind::AnonConst
1075        | DefKind::InlineConst
1076        | DefKind::GlobalAsm
1077        | DefKind::Closure
1078        | DefKind::ExternCrate
1079        | DefKind::SyntheticCoroutineBody => false,
1080    }
1081}
1082
1083/// Whether we should encode MIR. Return a pair, resp. for CTFE and for LLVM.
1084///
1085/// Computing, optimizing and encoding the MIR is a relatively expensive operation.
1086/// We want to avoid this work when not required. Therefore:
1087/// - we only compute `mir_for_ctfe` on items with const-eval semantics;
1088/// - we skip `optimized_mir` for check runs.
1089/// - we only encode `optimized_mir` that could be generated in other crates, that is, a code that
1090///   is either generic or has inline hint, and is reachable from the other crates (contained
1091///   in reachable set).
1092///
1093/// Note: Reachable set describes definitions that might be generated or referenced from other
1094/// crates and it can be used to limit optimized MIR that needs to be encoded. On the other hand,
1095/// the reachable set doesn't have much to say about which definitions might be evaluated at compile
1096/// time in other crates, so it cannot be used to omit CTFE MIR. For example, `f` below is
1097/// unreachable and yet it can be evaluated in other crates:
1098///
1099/// ```
1100/// const fn f() -> usize { 0 }
1101/// pub struct S { pub a: [usize; f()] }
1102/// ```
1103fn should_encode_mir(
1104    tcx: TyCtxt<'_>,
1105    reachable_set: &LocalDefIdSet,
1106    def_id: LocalDefId,
1107) -> (bool, bool) {
1108    match tcx.def_kind(def_id) {
1109        // Constructors
1110        DefKind::Ctor(_, _) => {
1111            let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
1112                || tcx.sess.opts.unstable_opts.always_encode_mir;
1113            (true, mir_opt_base)
1114        }
1115        // Constants
1116        DefKind::AnonConst | DefKind::InlineConst | DefKind::AssocConst | DefKind::Const => {
1117            (true, false)
1118        }
1119        // Coroutines require optimized MIR to compute layout.
1120        DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1121        DefKind::SyntheticCoroutineBody => (false, true),
1122        // Full-fledged functions + closures
1123        DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1124            let generics = tcx.generics_of(def_id);
1125            let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1126                || (tcx.sess.opts.output_types.should_codegen()
1127                    && reachable_set.contains(&def_id)
1128                    && (generics.requires_monomorphization(tcx)
1129                        || tcx.cross_crate_inlinable(def_id)));
1130            // The function has a `const` modifier or is in a `const trait`.
1131            let is_const_fn = tcx.is_const_fn(def_id.to_def_id());
1132            (is_const_fn, opt)
1133        }
1134        // The others don't have MIR.
1135        _ => (false, false),
1136    }
1137}
1138
1139fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1140    match def_kind {
1141        DefKind::Struct
1142        | DefKind::Union
1143        | DefKind::Enum
1144        | DefKind::OpaqueTy
1145        | DefKind::Fn
1146        | DefKind::Ctor(..)
1147        | DefKind::AssocFn => true,
1148        DefKind::AssocTy => {
1149            // Only encode variances for RPITITs (for traits)
1150            matches!(tcx.opt_rpitit_info(def_id), Some(ty::ImplTraitInTraitData::Trait { .. }))
1151        }
1152        DefKind::Mod
1153        | DefKind::Variant
1154        | DefKind::Field
1155        | DefKind::AssocConst
1156        | DefKind::TyParam
1157        | DefKind::ConstParam
1158        | DefKind::Static { .. }
1159        | DefKind::Const
1160        | DefKind::ForeignMod
1161        | DefKind::Impl { .. }
1162        | DefKind::Trait
1163        | DefKind::TraitAlias
1164        | DefKind::Macro(..)
1165        | DefKind::ForeignTy
1166        | DefKind::Use
1167        | DefKind::LifetimeParam
1168        | DefKind::AnonConst
1169        | DefKind::InlineConst
1170        | DefKind::GlobalAsm
1171        | DefKind::Closure
1172        | DefKind::ExternCrate
1173        | DefKind::SyntheticCoroutineBody => false,
1174        DefKind::TyAlias => tcx.type_alias_is_lazy(def_id),
1175    }
1176}
1177
1178fn should_encode_generics(def_kind: DefKind) -> bool {
1179    match def_kind {
1180        DefKind::Struct
1181        | DefKind::Union
1182        | DefKind::Enum
1183        | DefKind::Variant
1184        | DefKind::Trait
1185        | DefKind::TyAlias
1186        | DefKind::ForeignTy
1187        | DefKind::TraitAlias
1188        | DefKind::AssocTy
1189        | DefKind::Fn
1190        | DefKind::Const
1191        | DefKind::Static { .. }
1192        | DefKind::Ctor(..)
1193        | DefKind::AssocFn
1194        | DefKind::AssocConst
1195        | DefKind::AnonConst
1196        | DefKind::InlineConst
1197        | DefKind::OpaqueTy
1198        | DefKind::Impl { .. }
1199        | DefKind::Field
1200        | DefKind::TyParam
1201        | DefKind::Closure
1202        | DefKind::SyntheticCoroutineBody => true,
1203        DefKind::Mod
1204        | DefKind::ForeignMod
1205        | DefKind::ConstParam
1206        | DefKind::Macro(..)
1207        | DefKind::Use
1208        | DefKind::LifetimeParam
1209        | DefKind::GlobalAsm
1210        | DefKind::ExternCrate => false,
1211    }
1212}
1213
1214fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1215    match def_kind {
1216        DefKind::Struct
1217        | DefKind::Union
1218        | DefKind::Enum
1219        | DefKind::Variant
1220        | DefKind::Ctor(..)
1221        | DefKind::Field
1222        | DefKind::Fn
1223        | DefKind::Const
1224        | DefKind::Static { nested: false, .. }
1225        | DefKind::TyAlias
1226        | DefKind::ForeignTy
1227        | DefKind::Impl { .. }
1228        | DefKind::AssocFn
1229        | DefKind::AssocConst
1230        | DefKind::Closure
1231        | DefKind::ConstParam
1232        | DefKind::AnonConst
1233        | DefKind::InlineConst
1234        | DefKind::SyntheticCoroutineBody => true,
1235
1236        DefKind::OpaqueTy => {
1237            let origin = tcx.local_opaque_ty_origin(def_id);
1238            if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1239            | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1240                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1241                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1242            {
1243                false
1244            } else {
1245                true
1246            }
1247        }
1248
1249        DefKind::AssocTy => {
1250            let assoc_item = tcx.associated_item(def_id);
1251            match assoc_item.container {
1252                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1253                ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1254            }
1255        }
1256        DefKind::TyParam => {
1257            let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(def_id) else { bug!() };
1258            let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() };
1259            default.is_some()
1260        }
1261
1262        DefKind::Trait
1263        | DefKind::TraitAlias
1264        | DefKind::Mod
1265        | DefKind::ForeignMod
1266        | DefKind::Macro(..)
1267        | DefKind::Static { nested: true, .. }
1268        | DefKind::Use
1269        | DefKind::LifetimeParam
1270        | DefKind::GlobalAsm
1271        | DefKind::ExternCrate => false,
1272    }
1273}
1274
1275fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1276    match def_kind {
1277        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1278
1279        DefKind::Struct
1280        | DefKind::Union
1281        | DefKind::Enum
1282        | DefKind::Variant
1283        | DefKind::Field
1284        | DefKind::Const
1285        | DefKind::Static { .. }
1286        | DefKind::Ctor(..)
1287        | DefKind::TyAlias
1288        | DefKind::OpaqueTy
1289        | DefKind::ForeignTy
1290        | DefKind::Impl { .. }
1291        | DefKind::AssocConst
1292        | DefKind::Closure
1293        | DefKind::ConstParam
1294        | DefKind::AnonConst
1295        | DefKind::InlineConst
1296        | DefKind::AssocTy
1297        | DefKind::TyParam
1298        | DefKind::Trait
1299        | DefKind::TraitAlias
1300        | DefKind::Mod
1301        | DefKind::ForeignMod
1302        | DefKind::Macro(..)
1303        | DefKind::Use
1304        | DefKind::LifetimeParam
1305        | DefKind::GlobalAsm
1306        | DefKind::ExternCrate
1307        | DefKind::SyntheticCoroutineBody => false,
1308    }
1309}
1310
1311fn should_encode_constness(def_kind: DefKind) -> bool {
1312    match def_kind {
1313        DefKind::Fn
1314        | DefKind::AssocFn
1315        | DefKind::Closure
1316        | DefKind::Ctor(_, CtorKind::Fn)
1317        | DefKind::Impl { of_trait: false } => true,
1318
1319        DefKind::Struct
1320        | DefKind::Union
1321        | DefKind::Enum
1322        | DefKind::Field
1323        | DefKind::Const
1324        | DefKind::AssocConst
1325        | DefKind::AnonConst
1326        | DefKind::Static { .. }
1327        | DefKind::TyAlias
1328        | DefKind::OpaqueTy
1329        | DefKind::Impl { .. }
1330        | DefKind::ForeignTy
1331        | DefKind::ConstParam
1332        | DefKind::InlineConst
1333        | DefKind::AssocTy
1334        | DefKind::TyParam
1335        | DefKind::Trait
1336        | DefKind::TraitAlias
1337        | DefKind::Mod
1338        | DefKind::ForeignMod
1339        | DefKind::Macro(..)
1340        | DefKind::Use
1341        | DefKind::LifetimeParam
1342        | DefKind::GlobalAsm
1343        | DefKind::ExternCrate
1344        | DefKind::Ctor(_, CtorKind::Const)
1345        | DefKind::Variant
1346        | DefKind::SyntheticCoroutineBody => false,
1347    }
1348}
1349
1350fn should_encode_const(def_kind: DefKind) -> bool {
1351    match def_kind {
1352        // FIXME(mgca): should we remove Const and AssocConst here?
1353        DefKind::Const | DefKind::AssocConst | DefKind::AnonConst | DefKind::InlineConst => true,
1354
1355        DefKind::Struct
1356        | DefKind::Union
1357        | DefKind::Enum
1358        | DefKind::Variant
1359        | DefKind::Ctor(..)
1360        | DefKind::Field
1361        | DefKind::Fn
1362        | DefKind::Static { .. }
1363        | DefKind::TyAlias
1364        | DefKind::OpaqueTy
1365        | DefKind::ForeignTy
1366        | DefKind::Impl { .. }
1367        | DefKind::AssocFn
1368        | DefKind::Closure
1369        | DefKind::ConstParam
1370        | DefKind::AssocTy
1371        | DefKind::TyParam
1372        | DefKind::Trait
1373        | DefKind::TraitAlias
1374        | DefKind::Mod
1375        | DefKind::ForeignMod
1376        | DefKind::Macro(..)
1377        | DefKind::Use
1378        | DefKind::LifetimeParam
1379        | DefKind::GlobalAsm
1380        | DefKind::ExternCrate
1381        | DefKind::SyntheticCoroutineBody => false,
1382    }
1383}
1384
1385fn should_encode_const_of_item<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1386    matches!(def_kind, DefKind::Const | DefKind::AssocConst)
1387        && find_attr!(tcx.get_all_attrs(def_id), AttributeKind::TypeConst(_))
1388        // AssocConst ==> assoc item has value
1389        && (!matches!(def_kind, DefKind::AssocConst) || assoc_item_has_value(tcx, def_id))
1390}
1391
1392fn assoc_item_has_value<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1393    let assoc_item = tcx.associated_item(def_id);
1394    match assoc_item.container {
1395        ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1396        ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1397    }
1398}
1399
1400impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1401    fn encode_attrs(&mut self, def_id: LocalDefId) {
1402        let tcx = self.tcx;
1403        let mut state = AnalyzeAttrState {
1404            is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1405            is_doc_hidden: false,
1406            features: &tcx.features(),
1407        };
1408        let attr_iter = tcx
1409            .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
1410            .iter()
1411            .filter(|attr| analyze_attr(*attr, &mut state));
1412
1413        record_array!(self.tables.attributes[def_id.to_def_id()] <- attr_iter);
1414
1415        let mut attr_flags = AttrFlags::empty();
1416        if state.is_doc_hidden {
1417            attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1418        }
1419        self.tables.attr_flags.set(def_id.local_def_index, attr_flags);
1420    }
1421
1422    fn encode_def_ids(&mut self) {
1423        self.encode_info_for_mod(CRATE_DEF_ID);
1424
1425        // Proc-macro crates only export proc-macro items, which are looked
1426        // up using `proc_macro_data`
1427        if self.is_proc_macro {
1428            return;
1429        }
1430
1431        let tcx = self.tcx;
1432
1433        for local_id in tcx.iter_local_def_id() {
1434            let def_id = local_id.to_def_id();
1435            let def_kind = tcx.def_kind(local_id);
1436            self.tables.def_kind.set_some(def_id.index, def_kind);
1437
1438            // The `DefCollector` will sometimes create unnecessary `DefId`s
1439            // for trivial const arguments which are directly lowered to
1440            // `ConstArgKind::Path`. We never actually access this `DefId`
1441            // anywhere so we don't need to encode it for other crates.
1442            if def_kind == DefKind::AnonConst
1443                && match tcx.hir_node_by_def_id(local_id) {
1444                    hir::Node::ConstArg(hir::ConstArg { kind, .. }) => match kind {
1445                        // Skip encoding defs for these as they should not have had a `DefId` created
1446                        hir::ConstArgKind::Error(..)
1447                        | hir::ConstArgKind::Path(..)
1448                        | hir::ConstArgKind::Infer(..) => true,
1449                        hir::ConstArgKind::Anon(..) => false,
1450                    },
1451                    _ => false,
1452                }
1453            {
1454                continue;
1455            }
1456
1457            if def_kind == DefKind::Field
1458                && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1459                && let Some(anon) = field.default
1460            {
1461                record!(self.tables.default_fields[def_id] <- anon.def_id.to_def_id());
1462            }
1463
1464            if should_encode_span(def_kind) {
1465                let def_span = tcx.def_span(local_id);
1466                record!(self.tables.def_span[def_id] <- def_span);
1467            }
1468            if should_encode_attrs(def_kind) {
1469                self.encode_attrs(local_id);
1470            }
1471            if should_encode_expn_that_defined(def_kind) {
1472                record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1473            }
1474            if should_encode_span(def_kind)
1475                && let Some(ident_span) = tcx.def_ident_span(def_id)
1476            {
1477                record!(self.tables.def_ident_span[def_id] <- ident_span);
1478            }
1479            if def_kind.has_codegen_attrs() {
1480                record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1481            }
1482            if should_encode_visibility(def_kind) {
1483                let vis =
1484                    self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);
1485                record!(self.tables.visibility[def_id] <- vis);
1486            }
1487            if should_encode_stability(def_kind) {
1488                self.encode_stability(def_id);
1489                self.encode_const_stability(def_id);
1490                self.encode_default_body_stability(def_id);
1491                self.encode_deprecation(def_id);
1492            }
1493            if should_encode_variances(tcx, def_id, def_kind) {
1494                let v = self.tcx.variances_of(def_id);
1495                record_array!(self.tables.variances_of[def_id] <- v);
1496            }
1497            if should_encode_fn_sig(def_kind) {
1498                record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1499            }
1500            if should_encode_generics(def_kind) {
1501                let g = tcx.generics_of(def_id);
1502                record!(self.tables.generics_of[def_id] <- g);
1503                record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1504                let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1505                record_defaulted_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1506
1507                for param in &g.own_params {
1508                    if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1509                        let default = self.tcx.const_param_default(param.def_id);
1510                        record!(self.tables.const_param_default[param.def_id] <- default);
1511                    }
1512                }
1513            }
1514            if tcx.is_conditionally_const(def_id) {
1515                record!(self.tables.const_conditions[def_id] <- self.tcx.const_conditions(def_id));
1516            }
1517            if should_encode_type(tcx, local_id, def_kind) {
1518                record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1519            }
1520            if should_encode_constness(def_kind) {
1521                let constness = self.tcx.constness(def_id);
1522                self.tables.constness.set(def_id.index, constness);
1523            }
1524            if let DefKind::Fn | DefKind::AssocFn = def_kind {
1525                let asyncness = tcx.asyncness(def_id);
1526                self.tables.asyncness.set(def_id.index, asyncness);
1527                record_array!(self.tables.fn_arg_idents[def_id] <- tcx.fn_arg_idents(def_id));
1528            }
1529            if let Some(name) = tcx.intrinsic(def_id) {
1530                record!(self.tables.intrinsic[def_id] <- name);
1531            }
1532            if let DefKind::TyParam = def_kind {
1533                let default = self.tcx.object_lifetime_default(def_id);
1534                record!(self.tables.object_lifetime_default[def_id] <- default);
1535            }
1536            if let DefKind::Trait = def_kind {
1537                record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1538                record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1539                    self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1540                record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1541                    self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1542                let module_children = self.tcx.module_children_local(local_id);
1543                record_array!(self.tables.module_children_non_reexports[def_id] <-
1544                    module_children.iter().map(|child| child.res.def_id().index));
1545                if self.tcx.is_const_trait(def_id) {
1546                    record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1547                        <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1548                }
1549            }
1550            if let DefKind::TraitAlias = def_kind {
1551                record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1552                record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1553                    self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1554                record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1555                    self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1556            }
1557            if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1558                let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1559                record_array!(self.tables.associated_item_or_field_def_ids[def_id] <-
1560                    associated_item_def_ids.iter().map(|&def_id| {
1561                        assert!(def_id.is_local());
1562                        def_id.index
1563                    })
1564                );
1565                for &def_id in associated_item_def_ids {
1566                    self.encode_info_for_assoc_item(def_id);
1567                }
1568            }
1569            if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1570                && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id)
1571            {
1572                self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind))
1573            }
1574            if def_kind == DefKind::Closure
1575                && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1576            {
1577                let coroutine_for_closure = self.tcx.coroutine_for_closure(def_id);
1578                self.tables
1579                    .coroutine_for_closure
1580                    .set_some(def_id.index, coroutine_for_closure.into());
1581
1582                // If this async closure has a by-move body, record it too.
1583                if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1584                    self.tables.coroutine_by_move_body_def_id.set_some(
1585                        coroutine_for_closure.index,
1586                        self.tcx.coroutine_by_move_body_def_id(coroutine_for_closure).into(),
1587                    );
1588                }
1589            }
1590            if let DefKind::Static { .. } = def_kind {
1591                if !self.tcx.is_foreign_item(def_id) {
1592                    let data = self.tcx.eval_static_initializer(def_id).unwrap();
1593                    record!(self.tables.eval_static_initializer[def_id] <- data);
1594                }
1595            }
1596            if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1597                self.encode_info_for_adt(local_id);
1598            }
1599            if let DefKind::Mod = def_kind {
1600                self.encode_info_for_mod(local_id);
1601            }
1602            if let DefKind::Macro(_) = def_kind {
1603                self.encode_info_for_macro(local_id);
1604            }
1605            if let DefKind::TyAlias = def_kind {
1606                self.tables
1607                    .type_alias_is_lazy
1608                    .set(def_id.index, self.tcx.type_alias_is_lazy(def_id));
1609            }
1610            if let DefKind::OpaqueTy = def_kind {
1611                self.encode_explicit_item_bounds(def_id);
1612                self.encode_explicit_item_self_bounds(def_id);
1613                record!(self.tables.opaque_ty_origin[def_id] <- self.tcx.opaque_ty_origin(def_id));
1614                self.encode_precise_capturing_args(def_id);
1615                if tcx.is_conditionally_const(def_id) {
1616                    record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1617                        <- tcx.explicit_implied_const_bounds(def_id).skip_binder());
1618                }
1619            }
1620            if let DefKind::AnonConst = def_kind {
1621                record!(self.tables.anon_const_kind[def_id] <- self.tcx.anon_const_kind(def_id));
1622            }
1623            if should_encode_const_of_item(self.tcx, def_id, def_kind) {
1624                record!(self.tables.const_of_item[def_id] <- self.tcx.const_of_item(def_id));
1625            }
1626            if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1627                && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1628            {
1629                record!(self.tables.trait_impl_trait_tys[def_id] <- table);
1630            }
1631            if let DefKind::Impl { .. } | DefKind::Trait = def_kind {
1632                let table = tcx.associated_types_for_impl_traits_in_trait_or_impl(def_id);
1633                record!(self.tables.associated_types_for_impl_traits_in_trait_or_impl[def_id] <- table);
1634            }
1635        }
1636
1637        for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1638            record_defaulted_array!(self.tables.inherent_impls[def_id.to_def_id()] <- impls.iter().map(|def_id| {
1639                assert!(def_id.is_local());
1640                def_id.index
1641            }));
1642        }
1643
1644        for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1645            record!(self.tables.doc_link_resolutions[def_id.to_def_id()] <- res_map);
1646        }
1647
1648        for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1649            record_array!(self.tables.doc_link_traits_in_scope[def_id.to_def_id()] <- traits);
1650        }
1651    }
1652
1653    fn encode_externally_implementable_items(&mut self) -> LazyArray<EiiMapEncodedKeyValue> {
1654        empty_proc_macro!(self);
1655        let externally_implementable_items = self.tcx.externally_implementable_items(LOCAL_CRATE);
1656
1657        self.lazy_array(externally_implementable_items.iter().map(|(decl_did, (decl, impls))| {
1658            (*decl_did, (decl.clone(), impls.iter().map(|(impl_did, i)| (*impl_did, *i)).collect()))
1659        }))
1660    }
1661
1662    #[instrument(level = "trace", skip(self))]
1663    fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1664        let def_id = local_def_id.to_def_id();
1665        let tcx = self.tcx;
1666        let adt_def = tcx.adt_def(def_id);
1667        record!(self.tables.repr_options[def_id] <- adt_def.repr());
1668
1669        let params_in_repr = self.tcx.params_in_repr(def_id);
1670        record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1671
1672        if adt_def.is_enum() {
1673            let module_children = tcx.module_children_local(local_def_id);
1674            record_array!(self.tables.module_children_non_reexports[def_id] <-
1675                module_children.iter().map(|child| child.res.def_id().index));
1676        } else {
1677            // For non-enum, there is only one variant, and its def_id is the adt's.
1678            debug_assert_eq!(adt_def.variants().len(), 1);
1679            debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1680            // Therefore, the loop over variants will encode its fields as the adt's children.
1681        }
1682
1683        for (idx, variant) in adt_def.variants().iter_enumerated() {
1684            let data = VariantData {
1685                discr: variant.discr,
1686                idx,
1687                ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1688                is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1689            };
1690            record!(self.tables.variant_data[variant.def_id] <- data);
1691
1692            record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| {
1693                assert!(f.did.is_local());
1694                f.did.index
1695            }));
1696
1697            for field in &variant.fields {
1698                self.tables.safety.set(field.did.index, field.safety);
1699            }
1700
1701            if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1702                let fn_sig = tcx.fn_sig(ctor_def_id);
1703                // FIXME only encode signature for ctor_def_id
1704                record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
1705            }
1706        }
1707
1708        if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1709            record!(self.tables.adt_destructor[def_id] <- destructor);
1710        }
1711
1712        if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1713            record!(self.tables.adt_async_destructor[def_id] <- destructor);
1714        }
1715    }
1716
1717    #[instrument(level = "debug", skip(self))]
1718    fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1719        let tcx = self.tcx;
1720        let def_id = local_def_id.to_def_id();
1721
1722        // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1723        // only ever get called for the crate root. We still want to encode
1724        // the crate root for consistency with other crates (some of the resolver
1725        // code uses it). However, we skip encoding anything relating to child
1726        // items - we encode information about proc-macros later on.
1727        if self.is_proc_macro {
1728            // Encode this here because we don't do it in encode_def_ids.
1729            record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1730        } else {
1731            let module_children = tcx.module_children_local(local_def_id);
1732
1733            record_array!(self.tables.module_children_non_reexports[def_id] <-
1734                module_children.iter().filter(|child| child.reexport_chain.is_empty())
1735                    .map(|child| child.res.def_id().index));
1736
1737            record_defaulted_array!(self.tables.module_children_reexports[def_id] <-
1738                module_children.iter().filter(|child| !child.reexport_chain.is_empty()));
1739
1740            let ambig_module_children = tcx
1741                .resolutions(())
1742                .ambig_module_children
1743                .get(&local_def_id)
1744                .map_or_default(|v| &v[..]);
1745            record_defaulted_array!(self.tables.ambig_module_children[def_id] <-
1746                ambig_module_children);
1747        }
1748    }
1749
1750    fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1751        debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1752        let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1753        record_defaulted_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1754    }
1755
1756    fn encode_explicit_item_self_bounds(&mut self, def_id: DefId) {
1757        debug!("EncodeContext::encode_explicit_item_self_bounds({:?})", def_id);
1758        let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1759        record_defaulted_array!(self.tables.explicit_item_self_bounds[def_id] <- bounds);
1760    }
1761
1762    #[instrument(level = "debug", skip(self))]
1763    fn encode_info_for_assoc_item(&mut self, def_id: DefId) {
1764        let tcx = self.tcx;
1765        let item = tcx.associated_item(def_id);
1766
1767        if matches!(item.container, AssocContainer::Trait | AssocContainer::TraitImpl(_)) {
1768            self.tables.defaultness.set(def_id.index, item.defaultness(tcx));
1769        }
1770
1771        record!(self.tables.assoc_container[def_id] <- item.container);
1772
1773        if let AssocContainer::Trait = item.container
1774            && item.is_type()
1775        {
1776            self.encode_explicit_item_bounds(def_id);
1777            self.encode_explicit_item_self_bounds(def_id);
1778            if tcx.is_conditionally_const(def_id) {
1779                record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1780                    <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1781            }
1782        }
1783        if let ty::AssocKind::Type { data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
1784            record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info);
1785            if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1786                record_array!(
1787                    self.tables.assumed_wf_types_for_rpitit[def_id]
1788                        <- self.tcx.assumed_wf_types_for_rpitit(def_id)
1789                );
1790                self.encode_precise_capturing_args(def_id);
1791            }
1792        }
1793    }
1794
1795    fn encode_precise_capturing_args(&mut self, def_id: DefId) {
1796        let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1797            return;
1798        };
1799
1800        record_array!(self.tables.rendered_precise_capturing_args[def_id] <- precise_capturing_args);
1801    }
1802
1803    fn encode_mir(&mut self) {
1804        if self.is_proc_macro {
1805            return;
1806        }
1807
1808        let tcx = self.tcx;
1809        let reachable_set = tcx.reachable_set(());
1810
1811        let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1812            let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1813            if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1814        });
1815        for (def_id, encode_const, encode_opt) in keys_and_jobs {
1816            debug_assert!(encode_const || encode_opt);
1817
1818            debug!("EntryBuilder::encode_mir({:?})", def_id);
1819            if encode_opt {
1820                record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1821                self.tables
1822                    .cross_crate_inlinable
1823                    .set(def_id.to_def_id().index, self.tcx.cross_crate_inlinable(def_id));
1824                record!(self.tables.closure_saved_names_of_captured_variables[def_id.to_def_id()]
1825                    <- tcx.closure_saved_names_of_captured_variables(def_id));
1826
1827                if self.tcx.is_coroutine(def_id.to_def_id())
1828                    && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1829                {
1830                    record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1831                }
1832            }
1833            let mut is_trivial = false;
1834            if encode_const {
1835                if let Some((val, ty)) = tcx.trivial_const(def_id) {
1836                    is_trivial = true;
1837                    record!(self.tables.trivial_const[def_id.to_def_id()] <- (val, ty));
1838                } else {
1839                    is_trivial = false;
1840                    record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1841                }
1842
1843                // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1844                let abstract_const = tcx.thir_abstract_const(def_id);
1845                if let Ok(Some(abstract_const)) = abstract_const {
1846                    record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1847                }
1848
1849                if should_encode_const(tcx.def_kind(def_id)) {
1850                    let qualifs = tcx.mir_const_qualif(def_id);
1851                    record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1852                    let body = tcx.hir_maybe_body_owned_by(def_id);
1853                    if let Some(body) = body {
1854                        let const_data = rendered_const(self.tcx, &body, def_id);
1855                        record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1856                    }
1857                }
1858            }
1859            if !is_trivial {
1860                record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1861            }
1862
1863            if self.tcx.is_coroutine(def_id.to_def_id())
1864                && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1865            {
1866                record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1867            }
1868        }
1869
1870        // Encode all the deduced parameter attributes for everything that has MIR, even for items
1871        // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1872        // save the query traffic.
1873        if tcx.sess.opts.output_types.should_codegen()
1874            && tcx.sess.opts.optimize != OptLevel::No
1875            && tcx.sess.opts.incremental.is_none()
1876        {
1877            for &local_def_id in tcx.mir_keys(()) {
1878                if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1879                    record_array!(self.tables.deduced_param_attrs[local_def_id.to_def_id()] <-
1880                        self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1881                }
1882            }
1883        }
1884    }
1885
1886    #[instrument(level = "debug", skip(self))]
1887    fn encode_stability(&mut self, def_id: DefId) {
1888        // The query lookup can take a measurable amount of time in crates with many items. Check if
1889        // the stability attributes are even enabled before using their queries.
1890        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1891            if let Some(stab) = self.tcx.lookup_stability(def_id) {
1892                record!(self.tables.lookup_stability[def_id] <- stab)
1893            }
1894        }
1895    }
1896
1897    #[instrument(level = "debug", skip(self))]
1898    fn encode_const_stability(&mut self, def_id: DefId) {
1899        // The query lookup can take a measurable amount of time in crates with many items. Check if
1900        // the stability attributes are even enabled before using their queries.
1901        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1902            if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1903                record!(self.tables.lookup_const_stability[def_id] <- stab)
1904            }
1905        }
1906    }
1907
1908    #[instrument(level = "debug", skip(self))]
1909    fn encode_default_body_stability(&mut self, def_id: DefId) {
1910        // The query lookup can take a measurable amount of time in crates with many items. Check if
1911        // the stability attributes are even enabled before using their queries.
1912        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1913            if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1914                record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1915            }
1916        }
1917    }
1918
1919    #[instrument(level = "debug", skip(self))]
1920    fn encode_deprecation(&mut self, def_id: DefId) {
1921        if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1922            record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1923        }
1924    }
1925
1926    #[instrument(level = "debug", skip(self))]
1927    fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
1928        let tcx = self.tcx;
1929
1930        let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
1931        self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
1932        record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
1933    }
1934
1935    fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1936        empty_proc_macro!(self);
1937        let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1938        self.lazy_array(used_libraries.iter())
1939    }
1940
1941    fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1942        empty_proc_macro!(self);
1943        let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1944        self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1945    }
1946
1947    fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1948        let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1949        let mut expn_data_table: TableBuilder<_, _> = Default::default();
1950        let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1951
1952        self.hygiene_ctxt.encode(
1953            &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1954            |(this, syntax_contexts, _, _), index, ctxt_data| {
1955                syntax_contexts.set_some(index, this.lazy(ctxt_data));
1956            },
1957            |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1958                if let Some(index) = index.as_local() {
1959                    expn_data_table.set_some(index.as_raw(), this.lazy(expn_data));
1960                    expn_hash_table.set_some(index.as_raw(), this.lazy(hash));
1961                }
1962            },
1963        );
1964
1965        (
1966            syntax_contexts.encode(&mut self.opaque),
1967            expn_data_table.encode(&mut self.opaque),
1968            expn_hash_table.encode(&mut self.opaque),
1969        )
1970    }
1971
1972    fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1973        let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
1974        if is_proc_macro {
1975            let tcx = self.tcx;
1976            let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1977            let stability = tcx.lookup_stability(CRATE_DEF_ID);
1978            let macros =
1979                self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1980            for (i, span) in self.tcx.sess.psess.proc_macro_quoted_spans() {
1981                let span = self.lazy(span);
1982                self.tables.proc_macro_quoted_spans.set_some(i, span);
1983            }
1984
1985            self.tables.def_kind.set_some(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1986            record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1987            self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1988            let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|def_id| def_id.local_def_index);
1989            record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
1990            if let Some(stability) = stability {
1991                record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1992            }
1993            self.encode_deprecation(LOCAL_CRATE.as_def_id());
1994            if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_DEF_ID) {
1995                record!(self.tables.doc_link_resolutions[LOCAL_CRATE.as_def_id()] <- res_map);
1996            }
1997            if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_DEF_ID) {
1998                record_array!(self.tables.doc_link_traits_in_scope[LOCAL_CRATE.as_def_id()] <- traits);
1999            }
2000
2001            // Normally, this information is encoded when we walk the items
2002            // defined in this crate. However, we skip doing that for proc-macro crates,
2003            // so we manually encode just the information that we need
2004            for &proc_macro in &tcx.resolutions(()).proc_macros {
2005                let id = proc_macro;
2006                let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
2007                let mut name = tcx.hir_name(proc_macro);
2008                let span = tcx.hir_span(proc_macro);
2009                // Proc-macros may have attributes like `#[allow_internal_unstable]`,
2010                // so downstream crates need access to them.
2011                let attrs = tcx.hir_attrs(proc_macro);
2012                let macro_kind = if find_attr!(attrs, AttributeKind::ProcMacro(..)) {
2013                    MacroKind::Bang
2014                } else if find_attr!(attrs, AttributeKind::ProcMacroAttribute(..)) {
2015                    MacroKind::Attr
2016                } else if let Some(trait_name) = find_attr!(attrs, AttributeKind::ProcMacroDerive { trait_name, ..} => trait_name)
2017                {
2018                    name = *trait_name;
2019                    MacroKind::Derive
2020                } else {
2021                    bug!("Unknown proc-macro type for item {:?}", id);
2022                };
2023
2024                let mut def_key = self.tcx.hir_def_key(id);
2025                def_key.disambiguated_data.data = DefPathData::MacroNs(name);
2026
2027                let def_id = id.to_def_id();
2028                self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind.into()));
2029                self.tables.proc_macro.set_some(def_id.index, macro_kind);
2030                self.encode_attrs(id);
2031                record!(self.tables.def_keys[def_id] <- def_key);
2032                record!(self.tables.def_ident_span[def_id] <- span);
2033                record!(self.tables.def_span[def_id] <- span);
2034                record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
2035                if let Some(stability) = stability {
2036                    record!(self.tables.lookup_stability[def_id] <- stability);
2037                }
2038            }
2039
2040            Some(ProcMacroData { proc_macro_decls_static, stability, macros })
2041        } else {
2042            None
2043        }
2044    }
2045
2046    fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
2047        empty_proc_macro!(self);
2048        self.lazy_array(
2049            self.tcx
2050                .debugger_visualizers(LOCAL_CRATE)
2051                .iter()
2052                // Erase the path since it may contain privacy sensitive data
2053                // that we don't want to end up in crate metadata.
2054                // The path is only needed for the local crate because of
2055                // `--emit dep-info`.
2056                .map(DebuggerVisualizerFile::path_erased),
2057        )
2058    }
2059
2060    fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
2061        empty_proc_macro!(self);
2062
2063        let deps = self
2064            .tcx
2065            .crates(())
2066            .iter()
2067            .map(|&cnum| {
2068                let dep = CrateDep {
2069                    name: self.tcx.crate_name(cnum),
2070                    hash: self.tcx.crate_hash(cnum),
2071                    host_hash: self.tcx.crate_host_hash(cnum),
2072                    kind: self.tcx.dep_kind(cnum),
2073                    extra_filename: self.tcx.extra_filename(cnum).clone(),
2074                    is_private: self.tcx.is_private_dep(cnum),
2075                };
2076                (cnum, dep)
2077            })
2078            .collect::<Vec<_>>();
2079
2080        {
2081            // Sanity-check the crate numbers
2082            let mut expected_cnum = 1;
2083            for &(n, _) in &deps {
2084                assert_eq!(n, CrateNum::new(expected_cnum));
2085                expected_cnum += 1;
2086            }
2087        }
2088
2089        // We're just going to write a list of crate 'name-hash-version's, with
2090        // the assumption that they are numbered 1 to n.
2091        // FIXME (#2166): This is not nearly enough to support correct versioning
2092        // but is enough to get transitive crate dependencies working.
2093        self.lazy_array(deps.iter().map(|(_, dep)| dep))
2094    }
2095
2096    fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2097        empty_proc_macro!(self);
2098        let tcx = self.tcx;
2099        self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2100    }
2101
2102    fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2103        empty_proc_macro!(self);
2104        let tcx = self.tcx;
2105        let lib_features = tcx.lib_features(LOCAL_CRATE);
2106        self.lazy_array(lib_features.to_sorted_vec())
2107    }
2108
2109    fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2110        empty_proc_macro!(self);
2111        let tcx = self.tcx;
2112        let implications = tcx.stability_implications(LOCAL_CRATE);
2113        let sorted = implications.to_sorted_stable_ord();
2114        self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2115    }
2116
2117    fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2118        empty_proc_macro!(self);
2119        let tcx = self.tcx;
2120        let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2121        self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
2122    }
2123
2124    fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
2125        empty_proc_macro!(self);
2126        let lang_items = self.tcx.lang_items().iter();
2127        self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
2128            def_id.as_local().map(|id| (id.local_def_index, lang_item))
2129        }))
2130    }
2131
2132    fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2133        empty_proc_macro!(self);
2134        let tcx = self.tcx;
2135        self.lazy_array(&tcx.lang_items().missing)
2136    }
2137
2138    fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<DefIndex>> {
2139        self.lazy_array(
2140            self.tcx
2141                .stripped_cfg_items(LOCAL_CRATE)
2142                .into_iter()
2143                .map(|item| item.clone().map_mod_id(|def_id| def_id.index)),
2144        )
2145    }
2146
2147    fn encode_traits(&mut self) -> LazyArray<DefIndex> {
2148        empty_proc_macro!(self);
2149        self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2150    }
2151
2152    /// Encodes an index, mapping each trait to its (local) implementations.
2153    #[instrument(level = "debug", skip(self))]
2154    fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2155        empty_proc_macro!(self);
2156        let tcx = self.tcx;
2157        let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
2158            FxIndexMap::default();
2159
2160        for id in tcx.hir_free_items() {
2161            let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2162                continue;
2163            };
2164            let def_id = id.owner_id.to_def_id();
2165
2166            if of_trait {
2167                let header = tcx.impl_trait_header(def_id);
2168                record!(self.tables.impl_trait_header[def_id] <- header);
2169
2170                self.tables.defaultness.set(def_id.index, tcx.defaultness(def_id));
2171
2172                let trait_ref = header.trait_ref.instantiate_identity();
2173                let simplified_self_ty = fast_reject::simplify_type(
2174                    self.tcx,
2175                    trait_ref.self_ty(),
2176                    TreatParams::InstantiateWithInfer,
2177                );
2178                trait_impls
2179                    .entry(trait_ref.def_id)
2180                    .or_default()
2181                    .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
2182
2183                let trait_def = tcx.trait_def(trait_ref.def_id);
2184                if let Ok(mut an) = trait_def.ancestors(tcx, def_id)
2185                    && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1)
2186                {
2187                    self.tables.impl_parent.set_some(def_id.index, parent.into());
2188                }
2189
2190                // if this is an impl of `CoerceUnsized`, create its
2191                // "unsized info", else just store None
2192                if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2193                    let coerce_unsized_info = tcx.coerce_unsized_info(def_id).unwrap();
2194                    record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
2195                }
2196            }
2197        }
2198
2199        let trait_impls: Vec<_> = trait_impls
2200            .into_iter()
2201            .map(|(trait_def_id, impls)| TraitImpls {
2202                trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
2203                impls: self.lazy_array(&impls),
2204            })
2205            .collect();
2206
2207        self.lazy_array(&trait_impls)
2208    }
2209
2210    #[instrument(level = "debug", skip(self))]
2211    fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2212        empty_proc_macro!(self);
2213        let tcx = self.tcx;
2214
2215        let all_impls: Vec<_> = tcx
2216            .crate_inherent_impls(())
2217            .0
2218            .incoherent_impls
2219            .iter()
2220            .map(|(&simp, impls)| IncoherentImpls {
2221                self_ty: self.lazy(simp),
2222                impls: self.lazy_array(impls.iter().map(|def_id| def_id.local_def_index)),
2223            })
2224            .collect();
2225
2226        self.lazy_array(&all_impls)
2227    }
2228
2229    fn encode_exportable_items(&mut self) -> LazyArray<DefIndex> {
2230        empty_proc_macro!(self);
2231        self.lazy_array(self.tcx.exportable_items(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2232    }
2233
2234    fn encode_stable_order_of_exportable_impls(&mut self) -> LazyArray<(DefIndex, usize)> {
2235        empty_proc_macro!(self);
2236        let stable_order_of_exportable_impls =
2237            self.tcx.stable_order_of_exportable_impls(LOCAL_CRATE);
2238        self.lazy_array(
2239            stable_order_of_exportable_impls.iter().map(|(def_id, idx)| (def_id.index, *idx)),
2240        )
2241    }
2242
2243    // Encodes all symbols exported from this crate into the metadata.
2244    //
2245    // This pass is seeded off the reachability list calculated in the
2246    // middle::reachable module but filters out items that either don't have a
2247    // symbol associated with them (they weren't translated) or if they're an FFI
2248    // definition (as that's not defined in this crate).
2249    fn encode_exported_symbols(
2250        &mut self,
2251        exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2252    ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2253        empty_proc_macro!(self);
2254
2255        self.lazy_array(exported_symbols.iter().cloned())
2256    }
2257
2258    fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2259        empty_proc_macro!(self);
2260        let formats = self.tcx.dependency_formats(());
2261        if let Some(arr) = formats.get(&CrateType::Dylib) {
2262            return self.lazy_array(arr.iter().skip(1 /* skip LOCAL_CRATE */).map(
2263                |slot| match *slot {
2264                    Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2265
2266                    Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2267                    Linkage::Static => Some(LinkagePreference::RequireStatic),
2268                },
2269            ));
2270        }
2271        LazyArray::default()
2272    }
2273}
2274
2275/// Used to prefetch queries which will be needed later by metadata encoding.
2276/// Only a subset of the queries are actually prefetched to keep this code smaller.
2277fn prefetch_mir(tcx: TyCtxt<'_>) {
2278    if !tcx.sess.opts.output_types.should_codegen() {
2279        // We won't emit MIR, so don't prefetch it.
2280        return;
2281    }
2282
2283    let reachable_set = tcx.reachable_set(());
2284    par_for_each_in(tcx.mir_keys(()), |&&def_id| {
2285        if tcx.is_trivial_const(def_id) {
2286            return;
2287        }
2288        let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2289
2290        if encode_const {
2291            tcx.ensure_done().mir_for_ctfe(def_id);
2292        }
2293        if encode_opt {
2294            tcx.ensure_done().optimized_mir(def_id);
2295        }
2296        if encode_opt || encode_const {
2297            tcx.ensure_done().promoted_mir(def_id);
2298        }
2299    })
2300}
2301
2302// NOTE(eddyb) The following comment was preserved for posterity, even
2303// though it's no longer relevant as EBML (which uses nested & tagged
2304// "documents") was replaced with a scheme that can't go out of bounds.
2305//
2306// And here we run into yet another obscure archive bug: in which metadata
2307// loaded from archives may have trailing garbage bytes. Awhile back one of
2308// our tests was failing sporadically on the macOS 64-bit builders (both nopt
2309// and opt) by having ebml generate an out-of-bounds panic when looking at
2310// metadata.
2311//
2312// Upon investigation it turned out that the metadata file inside of an rlib
2313// (and ar archive) was being corrupted. Some compilations would generate a
2314// metadata file which would end in a few extra bytes, while other
2315// compilations would not have these extra bytes appended to the end. These
2316// extra bytes were interpreted by ebml as an extra tag, so they ended up
2317// being interpreted causing the out-of-bounds.
2318//
2319// The root cause of why these extra bytes were appearing was never
2320// discovered, and in the meantime the solution we're employing is to insert
2321// the length of the metadata to the start of the metadata. Later on this
2322// will allow us to slice the metadata to the precise length that we just
2323// generated regardless of trailing bytes that end up in it.
2324
2325pub struct EncodedMetadata {
2326    // The declaration order matters because `full_metadata` should be dropped
2327    // before `_temp_dir`.
2328    full_metadata: Option<Mmap>,
2329    // This is an optional stub metadata containing only the crate header.
2330    // The header should be very small, so we load it directly into memory.
2331    stub_metadata: Option<Vec<u8>>,
2332    // The path containing the metadata, to record as work product.
2333    path: Option<Box<Path>>,
2334    // We need to carry MaybeTempDir to avoid deleting the temporary
2335    // directory while accessing the Mmap.
2336    _temp_dir: Option<MaybeTempDir>,
2337}
2338
2339impl EncodedMetadata {
2340    #[inline]
2341    pub fn from_path(
2342        path: PathBuf,
2343        stub_path: Option<PathBuf>,
2344        temp_dir: Option<MaybeTempDir>,
2345    ) -> std::io::Result<Self> {
2346        let file = std::fs::File::open(&path)?;
2347        let file_metadata = file.metadata()?;
2348        if file_metadata.len() == 0 {
2349            return Ok(Self {
2350                full_metadata: None,
2351                stub_metadata: None,
2352                path: None,
2353                _temp_dir: None,
2354            });
2355        }
2356        let full_mmap = unsafe { Some(Mmap::map(file)?) };
2357
2358        let stub =
2359            if let Some(stub_path) = stub_path { Some(std::fs::read(stub_path)?) } else { None };
2360
2361        Ok(Self {
2362            full_metadata: full_mmap,
2363            stub_metadata: stub,
2364            path: Some(path.into()),
2365            _temp_dir: temp_dir,
2366        })
2367    }
2368
2369    #[inline]
2370    pub fn full(&self) -> &[u8] {
2371        &self.full_metadata.as_deref().unwrap_or_default()
2372    }
2373
2374    #[inline]
2375    pub fn stub_or_full(&self) -> &[u8] {
2376        self.stub_metadata.as_deref().unwrap_or(self.full())
2377    }
2378
2379    #[inline]
2380    pub fn path(&self) -> Option<&Path> {
2381        self.path.as_deref()
2382    }
2383}
2384
2385impl<S: Encoder> Encodable<S> for EncodedMetadata {
2386    fn encode(&self, s: &mut S) {
2387        self.stub_metadata.encode(s);
2388
2389        let slice = self.full();
2390        slice.encode(s)
2391    }
2392}
2393
2394impl<D: Decoder> Decodable<D> for EncodedMetadata {
2395    fn decode(d: &mut D) -> Self {
2396        let stub = <Option<Vec<u8>>>::decode(d);
2397
2398        let len = d.read_usize();
2399        let full_metadata = if len > 0 {
2400            let mut mmap = MmapMut::map_anon(len).unwrap();
2401            mmap.copy_from_slice(d.read_raw_bytes(len));
2402            Some(mmap.make_read_only().unwrap())
2403        } else {
2404            None
2405        };
2406
2407        Self { full_metadata, stub_metadata: stub, path: None, _temp_dir: None }
2408    }
2409}
2410
2411#[instrument(level = "trace", skip(tcx))]
2412pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path, ref_path: Option<&Path>) {
2413    // Since encoding metadata is not in a query, and nothing is cached,
2414    // there's no need to do dep-graph tracking for any of it.
2415    tcx.dep_graph.assert_ignored();
2416
2417    // Generate the metadata stub manually, as that is a small file compared to full metadata.
2418    if let Some(ref_path) = ref_path {
2419        let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
2420
2421        with_encode_metadata_header(tcx, ref_path, |ecx| {
2422            let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2423                name: tcx.crate_name(LOCAL_CRATE),
2424                triple: tcx.sess.opts.target_triple.clone(),
2425                hash: tcx.crate_hash(LOCAL_CRATE),
2426                is_proc_macro_crate: false,
2427                is_stub: true,
2428            });
2429            header.position.get()
2430        })
2431    }
2432
2433    let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2434
2435    let dep_node = tcx.metadata_dep_node();
2436
2437    // If the metadata dep-node is green, try to reuse the saved work product.
2438    if tcx.dep_graph.is_fully_enabled()
2439        && let work_product_id = WorkProductId::from_cgu_name("metadata")
2440        && let Some(work_product) = tcx.dep_graph.previous_work_product(&work_product_id)
2441        && tcx.try_mark_green(&dep_node)
2442    {
2443        let saved_path = &work_product.saved_files["rmeta"];
2444        let incr_comp_session_dir = tcx.sess.incr_comp_session_dir_opt().unwrap();
2445        let source_file = rustc_incremental::in_incr_comp_dir(&incr_comp_session_dir, saved_path);
2446        debug!("copying preexisting metadata from {source_file:?} to {path:?}");
2447        match rustc_fs_util::link_or_copy(&source_file, path) {
2448            Ok(_) => {}
2449            Err(err) => tcx.dcx().emit_fatal(FailCreateFileEncoder { err }),
2450        };
2451        return;
2452    };
2453
2454    if tcx.sess.threads() != 1 {
2455        // Prefetch some queries used by metadata encoding.
2456        // This is not necessary for correctness, but is only done for performance reasons.
2457        // It can be removed if it turns out to cause trouble or be detrimental to performance.
2458        join(
2459            || prefetch_mir(tcx),
2460            || {
2461                let _ = tcx.exported_non_generic_symbols(LOCAL_CRATE);
2462                let _ = tcx.exported_generic_symbols(LOCAL_CRATE);
2463            },
2464        );
2465    }
2466
2467    // Perform metadata encoding inside a task, so the dep-graph can check if any encoded
2468    // information changes, and maybe reuse the work product.
2469    tcx.dep_graph.with_task(
2470        dep_node,
2471        tcx,
2472        path,
2473        |tcx, path| {
2474            with_encode_metadata_header(tcx, path, |ecx| {
2475                // Encode all the entries and extra information in the crate,
2476                // culminating in the `CrateRoot` which points to all of it.
2477                let root = ecx.encode_crate_root();
2478
2479                // Flush buffer to ensure backing file has the correct size.
2480                ecx.opaque.flush();
2481                // Record metadata size for self-profiling
2482                tcx.prof.artifact_size(
2483                    "crate_metadata",
2484                    "crate_metadata",
2485                    ecx.opaque.file().metadata().unwrap().len(),
2486                );
2487
2488                root.position.get()
2489            })
2490        },
2491        None,
2492    );
2493}
2494
2495fn with_encode_metadata_header(
2496    tcx: TyCtxt<'_>,
2497    path: &Path,
2498    f: impl FnOnce(&mut EncodeContext<'_, '_>) -> usize,
2499) {
2500    let mut encoder = opaque::FileEncoder::new(path)
2501        .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2502    encoder.emit_raw_bytes(METADATA_HEADER);
2503
2504    // Will be filled with the root position after encoding everything.
2505    encoder.emit_raw_bytes(&0u64.to_le_bytes());
2506
2507    let source_map_files = tcx.sess.source_map().files();
2508    let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2509    let required_source_files = Some(FxIndexSet::default());
2510    drop(source_map_files);
2511
2512    let hygiene_ctxt = HygieneEncodeContext::default();
2513
2514    let mut ecx = EncodeContext {
2515        opaque: encoder,
2516        tcx,
2517        feat: tcx.features(),
2518        tables: Default::default(),
2519        lazy_state: LazyState::NoNode,
2520        span_shorthands: Default::default(),
2521        type_shorthands: Default::default(),
2522        predicate_shorthands: Default::default(),
2523        source_file_cache,
2524        interpret_allocs: Default::default(),
2525        required_source_files,
2526        is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2527        hygiene_ctxt: &hygiene_ctxt,
2528        symbol_index_table: Default::default(),
2529    };
2530
2531    // Encode the rustc version string in a predictable location.
2532    rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2533
2534    let root_position = f(&mut ecx);
2535
2536    // Make sure we report any errors from writing to the file.
2537    // If we forget this, compilation can succeed with an incomplete rmeta file,
2538    // causing an ICE when the rmeta file is read by another compilation.
2539    if let Err((path, err)) = ecx.opaque.finish() {
2540        tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2541    }
2542
2543    let file = ecx.opaque.file();
2544    if let Err(err) = encode_root_position(file, root_position) {
2545        tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2546    }
2547}
2548
2549fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2550    // We will return to this position after writing the root position.
2551    let pos_before_seek = file.stream_position().unwrap();
2552
2553    // Encode the root position.
2554    let header = METADATA_HEADER.len();
2555    file.seek(std::io::SeekFrom::Start(header as u64))?;
2556    file.write_all(&pos.to_le_bytes())?;
2557
2558    // Return to the position where we are before writing the root position.
2559    file.seek(std::io::SeekFrom::Start(pos_before_seek))?;
2560    Ok(())
2561}
2562
2563pub(crate) fn provide(providers: &mut Providers) {
2564    *providers = Providers {
2565        doc_link_resolutions: |tcx, def_id| {
2566            tcx.resolutions(())
2567                .doc_link_resolutions
2568                .get(&def_id)
2569                .unwrap_or_else(|| span_bug!(tcx.def_span(def_id), "no resolutions for a doc link"))
2570        },
2571        doc_link_traits_in_scope: |tcx, def_id| {
2572            tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2573                span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link")
2574            })
2575        },
2576
2577        ..*providers
2578    }
2579}
2580
2581/// Build a textual representation of an unevaluated constant expression.
2582///
2583/// If the const expression is too complex, an underscore `_` is returned.
2584/// For const arguments, it's `{ _ }` to be precise.
2585/// This means that the output is not necessarily valid Rust code.
2586///
2587/// Currently, only
2588///
2589/// * literals (optionally with a leading `-`)
2590/// * unit `()`
2591/// * blocks (`{ … }`) around simple expressions and
2592/// * paths without arguments
2593///
2594/// are considered simple enough. Simple blocks are included since they are
2595/// necessary to disambiguate unit from the unit type.
2596/// This list might get extended in the future.
2597///
2598/// Without this censoring, in a lot of cases the output would get too large
2599/// and verbose. Consider `match` expressions, blocks and deeply nested ADTs.
2600/// Further, private and `doc(hidden)` fields of structs would get leaked
2601/// since HIR datatypes like the `body` parameter do not contain enough
2602/// semantic information for this function to be able to hide them –
2603/// at least not without significant performance overhead.
2604///
2605/// Whenever possible, prefer to evaluate the constant first and try to
2606/// use a different method for pretty-printing. Ideally this function
2607/// should only ever be used as a fallback.
2608pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2609    let value = body.value;
2610
2611    #[derive(PartialEq, Eq)]
2612    enum Classification {
2613        Literal,
2614        Simple,
2615        Complex,
2616    }
2617
2618    use Classification::*;
2619
2620    fn classify(expr: &hir::Expr<'_>) -> Classification {
2621        match &expr.kind {
2622            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2623                if matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2624            }
2625            hir::ExprKind::Lit(_) => Literal,
2626            hir::ExprKind::Tup([]) => Simple,
2627            hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2628                if classify(expr) == Complex { Complex } else { Simple }
2629            }
2630            // Paths with a self-type or arguments are too “complex” following our measure since
2631            // they may leak private fields of structs (with feature `adt_const_params`).
2632            // Consider: `<Self as Trait<{ Struct { private: () } }>>::CONSTANT`.
2633            // Paths without arguments are definitely harmless though.
2634            hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2635                if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2636            }
2637            // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty
2638            //        contains const arguments. Is there a *concise* way to check for this?
2639            hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2640            _ => Complex,
2641        }
2642    }
2643
2644    match classify(value) {
2645        // For non-macro literals, we avoid invoking the pretty-printer and use the source snippet
2646        // instead to preserve certain stylistic choices the user likely made for the sake of
2647        // legibility, like:
2648        //
2649        // * hexadecimal notation
2650        // * underscores
2651        // * character escapes
2652        //
2653        // FIXME: This passes through `-/*spacer*/0` verbatim.
2654        Literal
2655            if !value.span.from_expansion()
2656                && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2657        {
2658            snippet
2659        }
2660
2661        // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
2662        // other formatting artifacts.
2663        Literal | Simple => id_to_string(&tcx, body.id().hir_id),
2664
2665        // FIXME: Omit the curly braces if the enclosing expression is an array literal
2666        //        with a repeated element (an `ExprKind::Repeat`) as in such case it
2667        //        would not actually need any disambiguation.
2668        Complex => {
2669            if tcx.def_kind(def_id) == DefKind::AnonConst {
2670                "{ _ }".to_owned()
2671            } else {
2672                "_".to_owned()
2673            }
2674        }
2675    }
2676}