1 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
2 use crate::rmeta::table::TableBuilder;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
7 use rustc_data_structures::memmap::{Mmap, MmapMut};
8 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
9 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
10 use rustc_data_structures::temp_dir::MaybeTempDir;
12 use rustc_hir::def::DefKind;
13 use rustc_hir::def_id::{
14 CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
16 use rustc_hir::definitions::DefPathData;
17 use rustc_hir::intravisit::{self, Visitor};
18 use rustc_hir::lang_items;
19 use rustc_hir::{AnonConst, GenericParamKind};
20 use rustc_middle::hir::nested_filter;
21 use rustc_middle::middle::dependency_format::Linkage;
22 use rustc_middle::middle::exported_symbols::{
23 metadata_symbol_name, ExportedSymbol, SymbolExportInfo,
25 use rustc_middle::mir::interpret;
26 use rustc_middle::traits::specialization_graph;
27 use rustc_middle::ty::codec::TyEncoder;
28 use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams};
29 use rustc_middle::ty::query::Providers;
30 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
31 use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder};
32 use rustc_session::config::CrateType;
33 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
34 use rustc_span::hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind};
35 use rustc_span::symbol::{sym, Symbol};
37 self, DebuggerVisualizerFile, ExternalSource, FileName, SourceFile, Span, SyntaxContext,
39 use rustc_target::abi::VariantIdx;
40 use std::borrow::Borrow;
41 use std::collections::hash_map::Entry;
43 use std::io::{Read, Seek, Write};
45 use std::num::NonZeroUsize;
46 use std::path::{Path, PathBuf};
48 pub(super) struct EncodeContext<'a, 'tcx> {
49 opaque: opaque::FileEncoder,
51 feat: &'tcx rustc_feature::Features,
53 tables: TableBuilders,
55 lazy_state: LazyState,
56 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
57 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
59 interpret_allocs: FxIndexSet<interpret::AllocId>,
61 // This is used to speed up Span encoding.
62 // The `usize` is an index into the `MonotonicVec`
63 // that stores the `SourceFile`
64 source_file_cache: (Lrc<SourceFile>, usize),
65 // The indices (into the `SourceMap`'s `MonotonicVec`)
66 // of all of the `SourceFiles` that we need to serialize.
67 // When we serialize a `Span`, we insert the index of its
68 // `SourceFile` into the `FxIndexSet`.
69 // The order inside the `FxIndexSet` is used as on-disk
70 // order of `SourceFiles`, and encoded inside `Span`s.
71 required_source_files: Option<FxIndexSet<usize>>,
73 hygiene_ctxt: &'a HygieneEncodeContext,
74 symbol_table: FxHashMap<Symbol, usize>,
77 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
78 /// This is useful for skipping the encoding of things that aren't needed
79 /// for proc-macro crates.
80 macro_rules! empty_proc_macro {
82 if $self.is_proc_macro {
83 return LazyArray::empty();
88 macro_rules! encoder_methods {
89 ($($name:ident($ty:ty);)*) => {
90 $(fn $name(&mut self, value: $ty) {
91 self.opaque.$name(value)
96 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
117 emit_raw_bytes(&[u8]);
121 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
122 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
123 e.emit_lazy_distance(self.position);
127 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
128 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
129 e.emit_usize(self.num_elems);
130 if self.num_elems > 0 {
131 e.emit_lazy_distance(self.position)
136 impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
137 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
138 e.emit_usize(self.encoded_size);
139 e.emit_lazy_distance(self.position);
143 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
144 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
145 if *self != LOCAL_CRATE && s.is_proc_macro {
146 panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
148 s.emit_u32(self.as_u32());
152 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
153 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
154 s.emit_u32(self.as_u32());
158 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
159 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
160 s.emit_u32(self.as_u32());
164 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
165 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
166 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s);
170 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
171 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
172 if self.krate == LOCAL_CRATE {
173 // We will only write details for local expansions. Non-local expansions will fetch
174 // data from the corresponding crate's metadata.
175 // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
176 // metadata from proc-macro crates.
177 s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
179 self.krate.encode(s);
180 self.local_id.encode(s);
184 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
185 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
186 let span = self.data();
188 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
189 // since we don't load proc-macro dependencies during serialization.
190 // This means that any hygiene information from macros used *within*
191 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
192 // definition) will be lost.
194 // This can show up in two ways:
196 // 1. Any hygiene information associated with identifier of
197 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
198 // Since proc-macros can only be invoked from a different crate,
199 // real code should never need to care about this.
201 // 2. Using `Span::def_site` or `Span::mixed_site` will not
202 // include any hygiene information associated with the definition
203 // site. This means that a proc-macro cannot emit a `$crate`
204 // identifier which resolves to one of its dependencies,
205 // which also should never come up in practice.
207 // Additionally, this affects `Span::parent`, and any other
208 // span inspection APIs that would otherwise allow traversing
209 // the `SyntaxContexts` associated with a span.
211 // None of these user-visible effects should result in any
212 // cross-crate inconsistencies (getting one behavior in the same
213 // crate, and a different behavior in another crate) due to the
214 // limited surface that proc-macros can expose.
216 // IMPORTANT: If this is ever changed, be sure to update
217 // `rustc_span::hygiene::raw_encode_expn_id` to handle
218 // encoding `ExpnData` for proc-macro crates.
220 SyntaxContext::root().encode(s);
226 return TAG_PARTIAL_SPAN.encode(s);
229 // The Span infrastructure should make sure that this invariant holds:
230 debug_assert!(span.lo <= span.hi);
232 if !s.source_file_cache.0.contains(span.lo) {
233 let source_map = s.tcx.sess.source_map();
234 let source_file_index = source_map.lookup_source_file_idx(span.lo);
235 s.source_file_cache =
236 (source_map.files()[source_file_index].clone(), source_file_index);
238 let (ref source_file, source_file_index) = s.source_file_cache;
239 debug_assert!(source_file.contains(span.lo));
241 if !source_file.contains(span.hi) {
242 // Unfortunately, macro expansion still sometimes generates Spans
243 // that malformed in this way.
244 return TAG_PARTIAL_SPAN.encode(s);
247 // There are two possible cases here:
248 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
249 // crate we are writing metadata for. When the metadata for *this* crate gets
250 // deserialized, the deserializer will need to know which crate it originally came
251 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
252 // be deserialized after the rest of the span data, which tells the deserializer
253 // which crate contains the source map information.
254 // 2. This span comes from our own crate. No special handling is needed - we just
255 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
256 // our own source map information.
258 // If we're a proc-macro crate, we always treat this as a local `Span`.
259 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
260 // if we're a proc-macro crate.
261 // This allows us to avoid loading the dependencies of proc-macro crates: all of
262 // the information we need to decode `Span`s is stored in the proc-macro crate.
263 let (tag, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
264 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
265 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
266 // are relative to the source map information for the 'foreign' crate whose CrateNum
267 // we write into the metadata. This allows `imported_source_files` to binary
268 // search through the 'foreign' crate's source map information, using the
269 // deserialized 'lo' and 'hi' values directly.
271 // All of this logic ensures that the final result of deserialization is a 'normal'
272 // Span that can be used without any additional trouble.
273 let metadata_index = {
274 // Introduce a new scope so that we drop the 'lock()' temporary
275 match &*source_file.external_src.lock() {
276 ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
277 src => panic!("Unexpected external source {:?}", src),
281 (TAG_VALID_SPAN_FOREIGN, metadata_index)
283 // Record the fact that we need to encode the data for this `SourceFile`
285 s.required_source_files.as_mut().expect("Already encoded SourceMap!");
286 let (metadata_index, _) = source_files.insert_full(source_file_index);
287 let metadata_index: u32 =
288 metadata_index.try_into().expect("cannot export more than U32_MAX files");
290 (TAG_VALID_SPAN_LOCAL, metadata_index)
293 // Encode the start position relative to the file start, so we profit more from the
294 // variable-length integer encoding.
295 let lo = span.lo - source_file.start_pos;
297 // Encode length which is usually less than span.hi and profits more
298 // from the variable-length integer encoding that we use.
299 let len = span.hi - span.lo;
305 // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
306 metadata_index.encode(s);
308 if tag == TAG_VALID_SPAN_FOREIGN {
309 // This needs to be two lines to avoid holding the `s.source_file_cache`
310 // while calling `cnum.encode(s)`
311 let cnum = s.source_file_cache.0.cnum;
317 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Symbol {
318 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
319 // if symbol preinterned, emit tag and symbol index
320 if self.is_preinterned() {
321 s.opaque.emit_u8(SYMBOL_PREINTERNED);
322 s.opaque.emit_u32(self.as_u32());
324 // otherwise write it as string or as offset to it
325 match s.symbol_table.entry(*self) {
326 Entry::Vacant(o) => {
327 s.opaque.emit_u8(SYMBOL_STR);
328 let pos = s.opaque.position();
330 s.emit_str(self.as_str());
332 Entry::Occupied(o) => {
333 let x = o.get().clone();
334 s.emit_u8(SYMBOL_OFFSET);
342 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
343 const CLEAR_CROSS_CRATE: bool = true;
345 type I = TyCtxt<'tcx>;
347 fn position(&self) -> usize {
348 self.opaque.position()
351 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
352 &mut self.type_shorthands
355 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
356 &mut self.predicate_shorthands
359 fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
360 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
366 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
367 // normally need extra variables to avoid errors about multiple mutable borrows.
368 macro_rules! record {
369 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
372 let lazy = $self.lazy(value);
373 $self.$tables.$table.set($def_id.index, lazy);
378 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
379 // normally need extra variables to avoid errors about multiple mutable borrows.
380 macro_rules! record_array {
381 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
384 let lazy = $self.lazy_array(value);
385 $self.$tables.$table.set($def_id.index, lazy);
390 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
391 fn emit_lazy_distance(&mut self, position: NonZeroUsize) {
392 let pos = position.get();
393 let distance = match self.lazy_state {
394 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
395 LazyState::NodeStart(start) => {
396 let start = start.get();
397 assert!(pos <= start);
400 LazyState::Previous(last_pos) => {
402 last_pos <= position,
403 "make sure that the calls to `lazy*` \
404 are in the same order as the metadata fields",
406 position.get() - last_pos.get()
409 self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap());
410 self.emit_usize(distance);
413 fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
415 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
417 let pos = NonZeroUsize::new(self.position()).unwrap();
419 assert_eq!(self.lazy_state, LazyState::NoNode);
420 self.lazy_state = LazyState::NodeStart(pos);
421 value.borrow().encode(self);
422 self.lazy_state = LazyState::NoNode;
424 assert!(pos.get() <= self.position());
426 LazyValue::from_position(pos)
429 fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
434 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
436 let pos = NonZeroUsize::new(self.position()).unwrap();
438 assert_eq!(self.lazy_state, LazyState::NoNode);
439 self.lazy_state = LazyState::NodeStart(pos);
440 let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
441 self.lazy_state = LazyState::NoNode;
443 assert!(pos.get() <= self.position());
445 LazyArray::from_position_and_num_elems(pos, len)
448 fn encode_info_for_items(&mut self) {
449 self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
451 // Proc-macro crates only export proc-macro items, which are looked
452 // up using `proc_macro_data`
453 if self.is_proc_macro {
457 self.tcx.hir().visit_all_item_likes_in_crate(self);
460 fn encode_def_path_table(&mut self) {
461 let table = self.tcx.def_path_table();
462 if self.is_proc_macro {
463 for def_index in std::iter::once(CRATE_DEF_INDEX)
464 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
466 let def_key = self.lazy(table.def_key(def_index));
467 let def_path_hash = table.def_path_hash(def_index);
468 self.tables.def_keys.set(def_index, def_key);
469 self.tables.def_path_hashes.set(def_index, def_path_hash);
472 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
473 let def_key = self.lazy(def_key);
474 self.tables.def_keys.set(def_index, def_key);
475 self.tables.def_path_hashes.set(def_index, *def_path_hash);
480 fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
481 self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
484 fn encode_source_map(&mut self) -> LazyTable<u32, LazyValue<rustc_span::SourceFile>> {
485 let source_map = self.tcx.sess.source_map();
486 let all_source_files = source_map.files();
488 // By replacing the `Option` with `None`, we ensure that we can't
489 // accidentally serialize any more `Span`s after the source map encoding
491 let required_source_files = self.required_source_files.take().unwrap();
493 let working_directory = &self.tcx.sess.opts.working_dir;
495 let mut adapted = TableBuilder::default();
497 // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
499 // The order in which we encode source files is important here: the on-disk format for
500 // `Span` contains the index of the corresponding `SourceFile`.
501 for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
502 let source_file = &all_source_files[source_file_index];
503 // Don't serialize imported `SourceFile`s, unless we're in a proc-macro crate.
504 assert!(!source_file.is_imported() || self.is_proc_macro);
506 // At export time we expand all source file paths to absolute paths because
507 // downstream compilation sessions can have a different compiler working
508 // directory, so relative paths from this or any other upstream crate
509 // won't be valid anymore.
511 // At this point we also erase the actual on-disk path and only keep
512 // the remapped version -- as is necessary for reproducible builds.
513 let mut source_file = match source_file.name {
514 FileName::Real(ref original_file_name) => {
515 let adapted_file_name = source_map
517 .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
519 if adapted_file_name != *original_file_name {
520 let mut adapted: SourceFile = (**source_file).clone();
521 adapted.name = FileName::Real(adapted_file_name);
522 adapted.name_hash = {
523 let mut hasher: StableHasher = StableHasher::new();
524 adapted.name.hash(&mut hasher);
525 hasher.finish::<u128>()
533 // expanded code, not from a file
534 _ => source_file.clone(),
537 // We're serializing this `SourceFile` into our crate metadata,
538 // so mark it as coming from this crate.
539 // This also ensures that we don't try to deserialize the
540 // `CrateNum` for a proc-macro dependency - since proc macro
541 // dependencies aren't loaded when we deserialize a proc-macro,
542 // trying to remap the `CrateNum` would fail.
543 if self.is_proc_macro {
544 Lrc::make_mut(&mut source_file).cnum = LOCAL_CRATE;
547 let on_disk_index: u32 =
548 on_disk_index.try_into().expect("cannot export more than U32_MAX files");
549 adapted.set(on_disk_index, self.lazy(source_file));
552 adapted.encode(&mut self.opaque)
555 fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
558 let preamble_bytes = self.position() - i;
560 // Encode the crate deps
562 let crate_deps = self.encode_crate_deps();
563 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
564 let dep_bytes = self.position() - i;
566 // Encode the lib features.
568 let lib_features = self.encode_lib_features();
569 let lib_feature_bytes = self.position() - i;
571 // Encode the stability implications.
573 let stability_implications = self.encode_stability_implications();
574 let stability_implications_bytes = self.position() - i;
576 // Encode the language items.
578 let lang_items = self.encode_lang_items();
579 let lang_items_missing = self.encode_lang_items_missing();
580 let lang_item_bytes = self.position() - i;
582 // Encode the diagnostic items.
584 let diagnostic_items = self.encode_diagnostic_items();
585 let diagnostic_item_bytes = self.position() - i;
587 // Encode the native libraries used
589 let native_libraries = self.encode_native_libraries();
590 let native_lib_bytes = self.position() - i;
593 let foreign_modules = self.encode_foreign_modules();
594 let foreign_modules_bytes = self.position() - i;
596 // Encode DefPathTable
598 self.encode_def_path_table();
599 let def_path_table_bytes = self.position() - i;
601 // Encode the def IDs of traits, for rustdoc and diagnostics.
603 let traits = self.encode_traits();
604 let traits_bytes = self.position() - i;
606 // Encode the def IDs of impls, for coherence checking.
608 let impls = self.encode_impls();
609 let impls_bytes = self.position() - i;
612 let incoherent_impls = self.encode_incoherent_impls();
613 let incoherent_impls_bytes = self.position() - i;
618 let mir_bytes = self.position() - i;
622 self.encode_def_ids();
623 self.encode_info_for_items();
624 let item_bytes = self.position() - i;
626 // Encode the allocation index
628 let interpret_alloc_index = {
629 let mut interpret_alloc_index = Vec::new();
631 trace!("beginning to encode alloc ids");
633 let new_n = self.interpret_allocs.len();
634 // if we have found new ids, serialize those, too
639 trace!("encoding {} further alloc ids", new_n - n);
640 for idx in n..new_n {
641 let id = self.interpret_allocs[idx];
642 let pos = self.position() as u32;
643 interpret_alloc_index.push(pos);
644 interpret::specialized_encode_alloc_id(self, tcx, id);
648 self.lazy_array(interpret_alloc_index)
650 let interpret_alloc_index_bytes = self.position() - i;
652 // Encode the proc macro data. This affects 'tables',
653 // so we need to do this before we encode the tables.
654 // This overwrites def_keys, so it must happen after encode_def_path_table.
656 let proc_macro_data = self.encode_proc_macros();
657 let proc_macro_data_bytes = self.position() - i;
660 let tables = self.tables.encode(&mut self.opaque);
661 let tables_bytes = self.position() - i;
664 let debugger_visualizers = self.encode_debugger_visualizers();
665 let debugger_visualizers_bytes = self.position() - i;
667 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
668 // this as late as possible to give the prefetching as much time as possible to complete.
670 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
671 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
672 let exported_symbols_bytes = self.position() - i;
674 // Encode the hygiene data,
675 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
676 // of encoding other items (e.g. `optimized_mir`) may cause us to load
677 // data from the incremental cache. If this causes us to deserialize a `Span`,
678 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
679 // Therefore, we need to encode the hygiene data last to ensure that we encode
680 // any `SyntaxContext`s that might be used.
682 let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene();
683 let hygiene_bytes = self.position() - i;
686 let def_path_hash_map = self.encode_def_path_hash_map();
687 let def_path_hash_map_bytes = self.position() - i;
689 // Encode source_map. This needs to be done last,
690 // since encoding `Span`s tells us which `SourceFiles` we actually
693 let source_map = self.encode_source_map();
694 let source_map_bytes = self.position() - i;
697 let attrs = tcx.hir().krate_attrs();
698 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
699 let root = self.lazy(CrateRoot {
700 name: tcx.crate_name(LOCAL_CRATE),
701 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
702 triple: tcx.sess.opts.target_triple.clone(),
703 hash: tcx.crate_hash(LOCAL_CRATE),
704 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
705 required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
706 panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
707 edition: tcx.sess.edition(),
708 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
709 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
710 has_default_lib_allocator,
712 debugger_visualizers,
713 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
714 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
715 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
716 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
717 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
718 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
719 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
722 dylib_dependency_formats,
724 stability_implications,
735 interpret_alloc_index,
742 let final_bytes = self.position() - i;
744 let total_bytes = self.position();
746 let computed_total_bytes = preamble_bytes
749 + stability_implications_bytes
751 + diagnostic_item_bytes
753 + foreign_modules_bytes
754 + def_path_table_bytes
757 + incoherent_impls_bytes
760 + interpret_alloc_index_bytes
761 + proc_macro_data_bytes
763 + debugger_visualizers_bytes
764 + exported_symbols_bytes
766 + def_path_hash_map_bytes
769 assert_eq!(total_bytes, computed_total_bytes);
771 if tcx.sess.meta_stats() {
774 // Rewind and re-read all the metadata to count the zero bytes we wrote.
775 let pos_before_rewind = self.opaque.file().stream_position().unwrap();
776 let mut zero_bytes = 0;
777 self.opaque.file().rewind().unwrap();
778 let file = std::io::BufReader::new(self.opaque.file());
779 for e in file.bytes() {
784 assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
786 let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
787 let p = |label, bytes| {
788 eprintln!("{:>21}: {:>8} bytes ({:4.1}%)", label, bytes, perc(bytes));
793 "{} metadata bytes, of which {} bytes ({:.1}%) are zero",
798 p("preamble", preamble_bytes);
800 p("lib feature", lib_feature_bytes);
801 p("stability_implications", stability_implications_bytes);
802 p("lang item", lang_item_bytes);
803 p("diagnostic item", diagnostic_item_bytes);
804 p("native lib", native_lib_bytes);
805 p("foreign modules", foreign_modules_bytes);
806 p("def-path table", def_path_table_bytes);
807 p("traits", traits_bytes);
808 p("impls", impls_bytes);
809 p("incoherent_impls", incoherent_impls_bytes);
811 p("item", item_bytes);
812 p("interpret_alloc_index", interpret_alloc_index_bytes);
813 p("proc-macro-data", proc_macro_data_bytes);
814 p("tables", tables_bytes);
815 p("debugger visualizers", debugger_visualizers_bytes);
816 p("exported symbols", exported_symbols_bytes);
817 p("hygiene", hygiene_bytes);
818 p("def-path hashes", def_path_hash_map_bytes);
819 p("source_map", source_map_bytes);
820 p("final", final_bytes);
828 fn should_encode_visibility(def_kind: DefKind) -> bool {
838 | DefKind::TraitAlias
842 | DefKind::Static(..)
845 | DefKind::AssocConst
848 | DefKind::ForeignMod
851 | DefKind::Field => true,
853 | DefKind::ConstParam
854 | DefKind::LifetimeParam
856 | DefKind::InlineConst
860 | DefKind::ExternCrate => false,
864 fn should_encode_stability(def_kind: DefKind) -> bool {
873 | DefKind::AssocConst
875 | DefKind::ConstParam
876 | DefKind::Static(..)
879 | DefKind::ForeignMod
886 | DefKind::TraitAlias
888 | DefKind::ForeignTy => true,
890 | DefKind::LifetimeParam
892 | DefKind::InlineConst
896 | DefKind::ExternCrate => false,
900 /// Whether we should encode MIR.
902 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
903 /// We want to avoid this work when not required. Therefore:
904 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
905 /// - we skip `optimized_mir` for check runs.
907 /// Return a pair, resp. for CTFE and for LLVM.
908 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
909 match tcx.def_kind(def_id) {
911 DefKind::Ctor(_, _) => {
912 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
913 || tcx.sess.opts.unstable_opts.always_encode_mir;
918 | DefKind::InlineConst
919 | DefKind::AssocConst
920 | DefKind::Static(..)
921 | DefKind::Const => (true, false),
922 // Full-fledged functions
923 DefKind::AssocFn | DefKind::Fn => {
924 let generics = tcx.generics_of(def_id);
925 let needs_inline = (generics.requires_monomorphization(tcx)
926 || tcx.codegen_fn_attrs(def_id).requests_inline())
927 && tcx.sess.opts.output_types.should_codegen();
928 // The function has a `const` modifier or is in a `#[const_trait]`.
929 let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id())
930 || tcx.is_const_default_method(def_id.to_def_id());
931 let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
932 (is_const_fn, needs_inline || always_encode_mir)
934 // Closures can't be const fn.
935 DefKind::Closure => {
936 let generics = tcx.generics_of(def_id);
937 let needs_inline = (generics.requires_monomorphization(tcx)
938 || tcx.codegen_fn_attrs(def_id).requests_inline())
939 && tcx.sess.opts.output_types.should_codegen();
940 let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
941 (false, needs_inline || always_encode_mir)
943 // Generators require optimized MIR to compute layout.
944 DefKind::Generator => (false, true),
945 // The others don't have MIR.
950 fn should_encode_variances(def_kind: DefKind) -> bool {
958 | DefKind::AssocFn => true,
962 | DefKind::AssocConst
964 | DefKind::ConstParam
965 | DefKind::Static(..)
967 | DefKind::ForeignMod
972 | DefKind::TraitAlias
976 | DefKind::LifetimeParam
978 | DefKind::InlineConst
982 | DefKind::ExternCrate => false,
986 fn should_encode_generics(def_kind: DefKind) -> bool {
995 | DefKind::TraitAlias
999 | DefKind::Static(..)
1002 | DefKind::AssocConst
1003 | DefKind::AnonConst
1004 | DefKind::InlineConst
1010 | DefKind::Generator => true,
1012 | DefKind::ForeignMod
1013 | DefKind::ConstParam
1014 | DefKind::Macro(..)
1016 | DefKind::LifetimeParam
1017 | DefKind::GlobalAsm
1018 | DefKind::ExternCrate => false,
1022 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1023 fn encode_attrs(&mut self, def_id: LocalDefId) {
1024 let mut attrs = self
1027 .attrs(self.tcx.hir().local_def_id_to_hir_id(def_id))
1029 .filter(|attr| !rustc_feature::is_builtin_only_local(attr.name_or_empty()));
1031 record_array!(self.tables.attributes[def_id.to_def_id()] <- attrs.clone());
1032 if attrs.any(|attr| attr.may_have_doc_links()) {
1033 self.tables.may_have_doc_links.set(def_id.local_def_index, ());
1037 fn encode_def_ids(&mut self) {
1038 if self.is_proc_macro {
1042 for local_id in tcx.iter_local_def_id() {
1043 let def_id = local_id.to_def_id();
1044 let def_kind = tcx.opt_def_kind(local_id);
1045 let Some(def_kind) = def_kind else { continue };
1046 self.tables.opt_def_kind.set(def_id.index, def_kind);
1047 record!(self.tables.def_span[def_id] <- tcx.def_span(def_id));
1048 self.encode_attrs(local_id);
1049 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1050 if let Some(ident_span) = tcx.def_ident_span(def_id) {
1051 record!(self.tables.def_ident_span[def_id] <- ident_span);
1053 if def_kind.has_codegen_attrs() {
1054 record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1056 if should_encode_visibility(def_kind) {
1057 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1059 if should_encode_stability(def_kind) {
1060 self.encode_stability(def_id);
1061 self.encode_const_stability(def_id);
1062 self.encode_default_body_stability(def_id);
1063 self.encode_deprecation(def_id);
1065 if should_encode_variances(def_kind) {
1066 let v = self.tcx.variances_of(def_id);
1067 record_array!(self.tables.variances_of[def_id] <- v);
1069 if should_encode_generics(def_kind) {
1070 let g = tcx.generics_of(def_id);
1071 record!(self.tables.generics_of[def_id] <- g);
1072 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1073 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1074 if !inferred_outlives.is_empty() {
1075 record_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1078 if let DefKind::TyParam | DefKind::ConstParam = def_kind {
1079 if let Some(default) = self.tcx.object_lifetime_default(def_id) {
1080 record!(self.tables.object_lifetime_default[def_id] <- default);
1083 if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1084 record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id));
1087 let inherent_impls = tcx.crate_inherent_impls(());
1088 for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
1089 if implementations.is_empty() {
1092 record_array!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1093 assert!(def_id.is_local());
1099 fn encode_item_type(&mut self, def_id: DefId) {
1100 debug!("EncodeContext::encode_item_type({:?})", def_id);
1101 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1104 fn encode_enum_variant_info(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1106 let variant = &def.variant(index);
1107 let def_id = variant.def_id;
1108 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1110 let data = VariantData {
1111 ctor_kind: variant.ctor_kind,
1112 discr: variant.discr,
1113 ctor: variant.ctor_def_id.map(|did| did.index),
1114 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1117 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1118 self.tables.constness.set(def_id.index, hir::Constness::Const);
1119 record_array!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1120 assert!(f.did.is_local());
1123 self.encode_item_type(def_id);
1124 if variant.ctor_kind == CtorKind::Fn {
1125 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1126 if let Some(ctor_def_id) = variant.ctor_def_id {
1127 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1132 fn encode_enum_variant_ctor(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1134 let variant = &def.variant(index);
1135 let def_id = variant.ctor_def_id.unwrap();
1136 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1138 // FIXME(eddyb) encode only the `CtorKind` for constructors.
1139 let data = VariantData {
1140 ctor_kind: variant.ctor_kind,
1141 discr: variant.discr,
1142 ctor: Some(def_id.index),
1143 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1146 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1147 self.tables.constness.set(def_id.index, hir::Constness::Const);
1148 self.encode_item_type(def_id);
1149 if variant.ctor_kind == CtorKind::Fn {
1150 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1154 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1156 let def_id = local_def_id.to_def_id();
1157 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1159 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1160 // only ever get called for the crate root. We still want to encode
1161 // the crate root for consistency with other crates (some of the resolver
1162 // code uses it). However, we skip encoding anything relating to child
1163 // items - we encode information about proc-macros later on.
1164 let reexports = if !self.is_proc_macro {
1165 match tcx.module_reexports(local_def_id) {
1166 Some(exports) => self.lazy_array(exports),
1167 _ => LazyArray::empty(),
1173 record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports));
1174 if self.is_proc_macro {
1175 // Encode this here because we don't do it in encode_def_ids.
1176 record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1178 record_array!(self.tables.children[def_id] <- iter::from_generator(|| {
1179 for item_id in md.item_ids {
1180 match tcx.hir().item(*item_id).kind {
1181 // Foreign items are planted into their parent modules
1182 // from name resolution point of view.
1183 hir::ItemKind::ForeignMod { items, .. } => {
1184 for foreign_item in items {
1185 yield foreign_item.id.def_id.local_def_index;
1188 // Only encode named non-reexport children, reexports are encoded
1189 // separately and unnamed items are not used by name resolution.
1190 hir::ItemKind::ExternCrate(..) => continue,
1191 _ if tcx.def_key(item_id.def_id.to_def_id()).get_opt_name().is_some() => {
1192 yield item_id.def_id.local_def_index;
1203 adt_def: ty::AdtDef<'tcx>,
1204 variant_index: VariantIdx,
1207 let variant = &adt_def.variant(variant_index);
1208 let field = &variant.fields[field_index];
1210 let def_id = field.did;
1211 debug!("EncodeContext::encode_field({:?})", def_id);
1213 record!(self.tables.kind[def_id] <- EntryKind::Field);
1214 self.encode_item_type(def_id);
1217 fn encode_struct_ctor(&mut self, adt_def: ty::AdtDef<'tcx>, def_id: DefId) {
1218 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1220 let variant = adt_def.non_enum_variant();
1222 let data = VariantData {
1223 ctor_kind: variant.ctor_kind,
1224 discr: variant.discr,
1225 ctor: Some(def_id.index),
1226 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1229 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1230 self.tables.constness.set(def_id.index, hir::Constness::Const);
1231 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data)));
1232 self.encode_item_type(def_id);
1233 if variant.ctor_kind == CtorKind::Fn {
1234 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1238 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1239 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1240 let bounds = self.tcx.explicit_item_bounds(def_id);
1241 if !bounds.is_empty() {
1242 record_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1246 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1247 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1250 let ast_item = tcx.hir().expect_trait_item(def_id.expect_local());
1251 self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
1252 let trait_item = tcx.associated_item(def_id);
1254 match trait_item.kind {
1255 ty::AssocKind::Const => {
1256 let rendered = rustc_hir_pretty::to_string(
1257 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
1258 |s| s.print_trait_item(ast_item),
1261 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(ty::AssocItemContainer::TraitContainer));
1262 record!(self.tables.mir_const_qualif[def_id] <- mir::ConstQualifs::default());
1263 record!(self.tables.rendered_const[def_id] <- rendered);
1265 ty::AssocKind::Fn => {
1266 let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind else { bug!() };
1268 hir::TraitFn::Required(ref names) => {
1269 record_array!(self.tables.fn_arg_names[def_id] <- *names)
1271 hir::TraitFn::Provided(body) => {
1272 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body))
1275 self.tables.asyncness.set(def_id.index, m_sig.header.asyncness);
1276 self.tables.constness.set(def_id.index, hir::Constness::NotConst);
1277 record!(self.tables.kind[def_id] <- EntryKind::AssocFn {
1278 container: ty::AssocItemContainer::TraitContainer,
1279 has_self: trait_item.fn_has_self_parameter,
1282 ty::AssocKind::Type => {
1283 self.encode_explicit_item_bounds(def_id);
1284 record!(self.tables.kind[def_id] <- EntryKind::AssocType(ty::AssocItemContainer::TraitContainer));
1287 match trait_item.kind {
1288 ty::AssocKind::Const | ty::AssocKind::Fn => {
1289 self.encode_item_type(def_id);
1291 ty::AssocKind::Type => {
1292 if ast_item.defaultness.has_value() {
1293 self.encode_item_type(def_id);
1297 if trait_item.kind == ty::AssocKind::Fn {
1298 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1302 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1303 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1306 let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local());
1307 self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
1308 let impl_item = self.tcx.associated_item(def_id);
1310 match impl_item.kind {
1311 ty::AssocKind::Const => {
1312 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1313 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1314 let const_data = self.encode_rendered_const_for_body(body_id);
1316 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(ty::AssocItemContainer::ImplContainer));
1317 record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1318 record!(self.tables.rendered_const[def_id] <- const_data);
1323 ty::AssocKind::Fn => {
1324 let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() };
1325 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1326 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1327 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1328 let constness = if self.tcx.is_const_fn_raw(def_id) {
1329 hir::Constness::Const
1331 hir::Constness::NotConst
1333 self.tables.constness.set(def_id.index, constness);
1334 record!(self.tables.kind[def_id] <- EntryKind::AssocFn {
1335 container: ty::AssocItemContainer::ImplContainer,
1336 has_self: impl_item.fn_has_self_parameter,
1339 ty::AssocKind::Type => {
1340 record!(self.tables.kind[def_id] <- EntryKind::AssocType(ty::AssocItemContainer::ImplContainer));
1343 self.encode_item_type(def_id);
1344 if let Some(trait_item_def_id) = impl_item.trait_item_def_id {
1345 self.tables.trait_item_def_id.set(def_id.index, trait_item_def_id.into());
1347 if impl_item.kind == ty::AssocKind::Fn {
1348 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1349 if tcx.is_intrinsic(def_id) {
1350 self.tables.is_intrinsic.set(def_id.index, ());
1355 fn encode_mir(&mut self) {
1356 if self.is_proc_macro {
1360 let keys_and_jobs = self
1364 .filter_map(|&def_id| {
1365 let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id);
1366 if encode_const || encode_opt {
1367 Some((def_id, encode_const, encode_opt))
1372 .collect::<Vec<_>>();
1373 for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() {
1374 debug_assert!(encode_const || encode_opt);
1376 debug!("EntryBuilder::encode_mir({:?})", def_id);
1378 record!(self.tables.optimized_mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1381 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id));
1383 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1384 let abstract_const = self.tcx.thir_abstract_const(def_id);
1385 if let Ok(Some(abstract_const)) = abstract_const {
1386 record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1389 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1392 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1393 let unused = self.tcx.unused_generic_params(instance);
1394 if !unused.is_empty() {
1395 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1400 fn encode_stability(&mut self, def_id: DefId) {
1401 debug!("EncodeContext::encode_stability({:?})", def_id);
1403 // The query lookup can take a measurable amount of time in crates with many items. Check if
1404 // the stability attributes are even enabled before using their queries.
1405 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1406 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1407 record!(self.tables.lookup_stability[def_id] <- stab)
1412 fn encode_const_stability(&mut self, def_id: DefId) {
1413 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1415 // The query lookup can take a measurable amount of time in crates with many items. Check if
1416 // the stability attributes are even enabled before using their queries.
1417 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1418 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1419 record!(self.tables.lookup_const_stability[def_id] <- stab)
1424 fn encode_default_body_stability(&mut self, def_id: DefId) {
1425 debug!("EncodeContext::encode_default_body_stability({:?})", def_id);
1427 // The query lookup can take a measurable amount of time in crates with many items. Check if
1428 // the stability attributes are even enabled before using their queries.
1429 if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1430 if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1431 record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1436 fn encode_deprecation(&mut self, def_id: DefId) {
1437 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1438 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1439 record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1443 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> String {
1444 let hir = self.tcx.hir();
1445 let body = hir.body(body_id);
1446 rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1447 s.print_expr(&body.value)
1451 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1454 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1456 let entry_kind = match item.kind {
1457 hir::ItemKind::Static(..) => EntryKind::Static,
1458 hir::ItemKind::Const(_, body_id) => {
1459 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1460 let const_data = self.encode_rendered_const_for_body(body_id);
1461 record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1462 record!(self.tables.rendered_const[def_id] <- const_data);
1465 hir::ItemKind::Fn(ref sig, .., body) => {
1466 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1467 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1468 self.tables.constness.set(def_id.index, sig.header.constness);
1471 hir::ItemKind::Macro(ref macro_def, _) => {
1472 EntryKind::MacroDef(self.lazy(&*macro_def.body), macro_def.macro_rules)
1474 hir::ItemKind::Mod(ref m) => {
1475 return self.encode_info_for_mod(item.def_id, m);
1477 hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1478 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1479 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1480 hir::ItemKind::OpaqueTy(..) => {
1481 self.encode_explicit_item_bounds(def_id);
1484 hir::ItemKind::Enum(..) => {
1485 let adt_def = self.tcx.adt_def(def_id);
1486 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1489 hir::ItemKind::Struct(ref struct_def, _) => {
1490 let adt_def = self.tcx.adt_def(def_id);
1491 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1492 self.tables.constness.set(def_id.index, hir::Constness::Const);
1494 // Encode def_ids for each field and method
1495 // for methods, write all the stuff get_trait_method
1497 let ctor = struct_def
1499 .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1501 let variant = adt_def.non_enum_variant();
1502 EntryKind::Struct(self.lazy(VariantData {
1503 ctor_kind: variant.ctor_kind,
1504 discr: variant.discr,
1506 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1509 hir::ItemKind::Union(..) => {
1510 let adt_def = self.tcx.adt_def(def_id);
1511 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1513 let variant = adt_def.non_enum_variant();
1514 EntryKind::Union(self.lazy(VariantData {
1515 ctor_kind: variant.ctor_kind,
1516 discr: variant.discr,
1518 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1521 hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1522 self.tables.impl_defaultness.set(def_id.index, *defaultness);
1523 self.tables.constness.set(def_id.index, *constness);
1525 let trait_ref = self.tcx.impl_trait_ref(def_id);
1526 if let Some(trait_ref) = trait_ref {
1527 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1528 if let Some(mut an) = trait_def.ancestors(self.tcx, def_id).ok() {
1529 if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
1530 self.tables.impl_parent.set(def_id.index, parent.into());
1534 // if this is an impl of `CoerceUnsized`, create its
1535 // "unsized info", else just store None
1536 if Some(trait_ref.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1537 let coerce_unsized_info =
1538 self.tcx.at(item.span).coerce_unsized_info(def_id);
1539 record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
1543 let polarity = self.tcx.impl_polarity(def_id);
1544 self.tables.impl_polarity.set(def_id.index, polarity);
1548 hir::ItemKind::Trait(..) => {
1549 let trait_def = self.tcx.trait_def(def_id);
1550 record!(self.tables.trait_def[def_id] <- trait_def);
1554 hir::ItemKind::TraitAlias(..) => {
1555 let trait_def = self.tcx.trait_def(def_id);
1556 record!(self.tables.trait_def[def_id] <- trait_def);
1558 EntryKind::TraitAlias
1560 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1561 bug!("cannot encode info for item {:?}", item)
1564 record!(self.tables.kind[def_id] <- entry_kind);
1565 // FIXME(eddyb) there should be a nicer way to do this.
1567 hir::ItemKind::Enum(..) => record_array!(self.tables.children[def_id] <-
1568 self.tcx.adt_def(def_id).variants().iter().map(|v| {
1569 assert!(v.def_id.is_local());
1573 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1574 record_array!(self.tables.children[def_id] <-
1575 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1576 assert!(f.did.is_local());
1581 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1582 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1583 record_array!(self.tables.children[def_id] <-
1584 associated_item_def_ids.iter().map(|&def_id| {
1585 assert!(def_id.is_local());
1593 hir::ItemKind::Static(..)
1594 | hir::ItemKind::Const(..)
1595 | hir::ItemKind::Fn(..)
1596 | hir::ItemKind::TyAlias(..)
1597 | hir::ItemKind::OpaqueTy(..)
1598 | hir::ItemKind::Enum(..)
1599 | hir::ItemKind::Struct(..)
1600 | hir::ItemKind::Union(..)
1601 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1604 if let hir::ItemKind::Fn(..) = item.kind {
1605 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1606 if tcx.is_intrinsic(def_id) {
1607 self.tables.is_intrinsic.set(def_id.index, ());
1610 if let hir::ItemKind::Impl { .. } = item.kind {
1611 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1612 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1617 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1618 record!(self.tables.kind[def_id] <- kind);
1620 self.encode_item_type(def_id);
1624 fn encode_info_for_closure(&mut self, hir_id: hir::HirId) {
1625 let def_id = self.tcx.hir().local_def_id(hir_id);
1626 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1627 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1628 // including on the signature, which is inferred in `typeck.
1629 let typeck_result: &'tcx ty::TypeckResults<'tcx> = self.tcx.typeck(def_id);
1630 let ty = typeck_result.node_type(hir_id);
1632 ty::Generator(..) => {
1633 let data = self.tcx.generator_kind(def_id).unwrap();
1634 let generator_diagnostic_data = typeck_result.get_generator_diagnostic_data();
1635 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator);
1636 record!(self.tables.generator_kind[def_id.to_def_id()] <- data);
1637 record!(self.tables.generator_diagnostic_data[def_id.to_def_id()] <- generator_diagnostic_data);
1640 ty::Closure(..) => {
1641 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1644 _ => bug!("closure that is neither generator nor closure"),
1646 self.encode_item_type(def_id.to_def_id());
1647 if let ty::Closure(def_id, substs) = *ty.kind() {
1648 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1652 fn encode_info_for_anon_const(&mut self, id: hir::HirId) {
1653 let def_id = self.tcx.hir().local_def_id(id);
1654 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1655 let body_id = self.tcx.hir().body_owned_by(def_id);
1656 let const_data = self.encode_rendered_const_for_body(body_id);
1657 let qualifs = self.tcx.mir_const_qualif(def_id);
1659 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst);
1660 record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1661 record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1662 self.encode_item_type(def_id.to_def_id());
1665 fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1666 empty_proc_macro!(self);
1667 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1668 self.lazy_array(used_libraries.iter())
1671 fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1672 empty_proc_macro!(self);
1673 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1674 self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1677 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1678 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1679 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1680 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1682 self.hygiene_ctxt.encode(
1683 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1684 |(this, syntax_contexts, _, _), index, ctxt_data| {
1685 syntax_contexts.set(index, this.lazy(ctxt_data));
1687 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1688 if let Some(index) = index.as_local() {
1689 expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1690 expn_hash_table.set(index.as_raw(), this.lazy(hash));
1696 syntax_contexts.encode(&mut self.opaque),
1697 expn_data_table.encode(&mut self.opaque),
1698 expn_hash_table.encode(&mut self.opaque),
1702 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1703 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1706 let hir = tcx.hir();
1708 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1709 let stability = tcx.lookup_stability(CRATE_DEF_ID);
1711 self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1712 let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1713 for (i, span) in spans.into_iter().enumerate() {
1714 let span = self.lazy(span);
1715 self.tables.proc_macro_quoted_spans.set(i, span);
1718 self.tables.opt_def_kind.set(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1719 record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1720 self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1721 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1722 if let Some(stability) = stability {
1723 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1725 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1727 // Normally, this information is encoded when we walk the items
1728 // defined in this crate. However, we skip doing that for proc-macro crates,
1729 // so we manually encode just the information that we need
1730 for &proc_macro in &tcx.resolutions(()).proc_macros {
1731 let id = proc_macro;
1732 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1733 let mut name = hir.name(proc_macro);
1734 let span = hir.span(proc_macro);
1735 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1736 // so downstream crates need access to them.
1737 let attrs = hir.attrs(proc_macro);
1738 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1740 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1742 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1743 // This unwrap chain should have been checked by the proc-macro harness.
1744 name = attr.meta_item_list().unwrap()[0]
1752 bug!("Unknown proc-macro type for item {:?}", id);
1755 let mut def_key = self.tcx.hir().def_key(id);
1756 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1758 let def_id = id.to_def_id();
1759 self.tables.opt_def_kind.set(def_id.index, DefKind::Macro(macro_kind));
1760 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1761 self.encode_attrs(id);
1762 record!(self.tables.def_keys[def_id] <- def_key);
1763 record!(self.tables.def_ident_span[def_id] <- span);
1764 record!(self.tables.def_span[def_id] <- span);
1765 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1766 if let Some(stability) = stability {
1767 record!(self.tables.lookup_stability[def_id] <- stability);
1771 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1777 fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1778 empty_proc_macro!(self);
1779 self.lazy_array(self.tcx.debugger_visualizers(LOCAL_CRATE).iter())
1782 fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1783 empty_proc_macro!(self);
1790 let dep = CrateDep {
1791 name: self.tcx.crate_name(cnum),
1792 hash: self.tcx.crate_hash(cnum),
1793 host_hash: self.tcx.crate_host_hash(cnum),
1794 kind: self.tcx.dep_kind(cnum),
1795 extra_filename: self.tcx.extra_filename(cnum).clone(),
1799 .collect::<Vec<_>>();
1802 // Sanity-check the crate numbers
1803 let mut expected_cnum = 1;
1804 for &(n, _) in &deps {
1805 assert_eq!(n, CrateNum::new(expected_cnum));
1810 // We're just going to write a list of crate 'name-hash-version's, with
1811 // the assumption that they are numbered 1 to n.
1812 // FIXME (#2166): This is not nearly enough to support correct versioning
1813 // but is enough to get transitive crate dependencies working.
1814 self.lazy_array(deps.iter().map(|&(_, ref dep)| dep))
1817 fn encode_lib_features(&mut self) -> LazyArray<(Symbol, Option<Symbol>)> {
1818 empty_proc_macro!(self);
1820 let lib_features = tcx.lib_features(());
1821 self.lazy_array(lib_features.to_vec())
1824 fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
1825 empty_proc_macro!(self);
1827 let implications = tcx.stability_implications(LOCAL_CRATE);
1828 self.lazy_array(implications.iter().map(|(k, v)| (*k, *v)))
1831 fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
1832 empty_proc_macro!(self);
1834 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1835 self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1838 fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, usize)> {
1839 empty_proc_macro!(self);
1841 let lang_items = tcx.lang_items();
1842 let lang_items = lang_items.items().iter();
1843 self.lazy_array(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1844 if let Some(def_id) = opt_def_id {
1845 if def_id.is_local() {
1846 return Some((def_id.index, i));
1853 fn encode_lang_items_missing(&mut self) -> LazyArray<lang_items::LangItem> {
1854 empty_proc_macro!(self);
1856 self.lazy_array(&tcx.lang_items().missing)
1859 fn encode_traits(&mut self) -> LazyArray<DefIndex> {
1860 empty_proc_macro!(self);
1861 self.lazy_array(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index))
1864 /// Encodes an index, mapping each trait to its (local) implementations.
1865 fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
1866 debug!("EncodeContext::encode_traits_and_impls()");
1867 empty_proc_macro!(self);
1869 let mut fx_hash_map: FxHashMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
1870 FxHashMap::default();
1872 for id in tcx.hir().items() {
1873 if matches!(tcx.def_kind(id.def_id), DefKind::Impl) {
1874 if let Some(trait_ref) = tcx.impl_trait_ref(id.def_id.to_def_id()) {
1875 let simplified_self_ty = fast_reject::simplify_type(
1877 trait_ref.self_ty(),
1878 TreatParams::AsInfer,
1882 .entry(trait_ref.def_id)
1884 .push((id.def_id.local_def_index, simplified_self_ty));
1889 let mut all_impls: Vec<_> = fx_hash_map.into_iter().collect();
1891 // Bring everything into deterministic order for hashing
1892 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1894 let all_impls: Vec<_> = all_impls
1896 .map(|(trait_def_id, mut impls)| {
1897 // Bring everything into deterministic order for hashing
1898 impls.sort_by_cached_key(|&(index, _)| {
1899 tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1903 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1904 impls: self.lazy_array(&impls),
1909 self.lazy_array(&all_impls)
1912 fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
1913 debug!("EncodeContext::encode_traits_and_impls()");
1914 empty_proc_macro!(self);
1916 let mut all_impls: Vec<_> = tcx.crate_inherent_impls(()).incoherent_impls.iter().collect();
1917 tcx.with_stable_hashing_context(|mut ctx| {
1918 all_impls.sort_by_cached_key(|&(&simp, _)| {
1919 let mut hasher = StableHasher::new();
1920 simp.hash_stable(&mut ctx, &mut hasher);
1921 hasher.finish::<Fingerprint>()
1924 let all_impls: Vec<_> = all_impls
1926 .map(|(&simp, impls)| {
1927 let mut impls: Vec<_> =
1928 impls.into_iter().map(|def_id| def_id.local_def_index).collect();
1929 impls.sort_by_cached_key(|&local_def_index| {
1930 tcx.hir().def_path_hash(LocalDefId { local_def_index })
1933 IncoherentImpls { self_ty: simp, impls: self.lazy_array(impls) }
1937 self.lazy_array(&all_impls)
1940 // Encodes all symbols exported from this crate into the metadata.
1942 // This pass is seeded off the reachability list calculated in the
1943 // middle::reachable module but filters out items that either don't have a
1944 // symbol associated with them (they weren't translated) or if they're an FFI
1945 // definition (as that's not defined in this crate).
1946 fn encode_exported_symbols(
1948 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
1949 ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
1950 empty_proc_macro!(self);
1951 // The metadata symbol name is special. It should not show up in
1952 // downstream crates.
1953 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1958 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1959 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1966 fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
1967 empty_proc_macro!(self);
1968 let formats = self.tcx.dependency_formats(());
1969 for (ty, arr) in formats.iter() {
1970 if *ty != CrateType::Dylib {
1973 return self.lazy_array(arr.iter().map(|slot| match *slot {
1974 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1976 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1977 Linkage::Static => Some(LinkagePreference::RequireStatic),
1983 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1986 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1989 hir::ForeignItemKind::Fn(_, ref names, _) => {
1990 self.tables.asyncness.set(def_id.index, hir::IsAsync::NotAsync);
1991 record_array!(self.tables.fn_arg_names[def_id] <- *names);
1992 let constness = if self.tcx.is_const_fn_raw(def_id) {
1993 hir::Constness::Const
1995 hir::Constness::NotConst
1997 self.tables.constness.set(def_id.index, constness);
1998 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn);
2000 hir::ForeignItemKind::Static(..) => {
2001 record!(self.tables.kind[def_id] <- EntryKind::ForeignStatic);
2003 hir::ForeignItemKind::Type => {
2004 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
2007 self.encode_item_type(def_id);
2008 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
2009 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
2010 if tcx.is_intrinsic(def_id) {
2011 self.tables.is_intrinsic.set(def_id.index, ());
2017 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
2018 impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> {
2019 type NestedFilter = nested_filter::OnlyBodies;
2021 fn nested_visit_map(&mut self) -> Self::Map {
2024 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2025 intravisit::walk_expr(self, ex);
2026 self.encode_info_for_expr(ex);
2028 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
2029 intravisit::walk_anon_const(self, c);
2030 self.encode_info_for_anon_const(c.hir_id);
2032 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
2033 intravisit::walk_item(self, item);
2035 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
2036 _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
2038 self.encode_addl_info_for_item(item);
2040 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
2041 intravisit::walk_foreign_item(self, ni);
2042 self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
2044 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
2045 intravisit::walk_generics(self, generics);
2046 self.encode_info_for_generics(generics);
2050 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
2051 fn encode_fields(&mut self, adt_def: ty::AdtDef<'tcx>) {
2052 for (variant_index, variant) in adt_def.variants().iter_enumerated() {
2053 for (field_index, _field) in variant.fields.iter().enumerate() {
2054 self.encode_field(adt_def, variant_index, field_index);
2059 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
2060 for param in generics.params {
2061 let def_id = self.tcx.hir().local_def_id(param.hir_id);
2063 GenericParamKind::Lifetime { .. } => continue,
2064 GenericParamKind::Type { default, .. } => {
2065 self.encode_info_for_generic_param(
2067 EntryKind::TypeParam,
2071 GenericParamKind::Const { ref default, .. } => {
2072 let def_id = def_id.to_def_id();
2073 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
2074 if default.is_some() {
2075 record!(self.tables.const_param_default[def_id] <- self.tcx.const_param_default(def_id))
2082 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
2083 if let hir::ExprKind::Closure { .. } = expr.kind {
2084 self.encode_info_for_closure(expr.hir_id);
2088 /// In some cases, along with the item itself, we also
2089 /// encode some sub-items. Usually we want some info from the item
2090 /// so it's easier to do that here then to wait until we would encounter
2091 /// normally in the visitor walk.
2092 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
2094 hir::ItemKind::Static(..)
2095 | hir::ItemKind::Const(..)
2096 | hir::ItemKind::Fn(..)
2097 | hir::ItemKind::Macro(..)
2098 | hir::ItemKind::Mod(..)
2099 | hir::ItemKind::ForeignMod { .. }
2100 | hir::ItemKind::GlobalAsm(..)
2101 | hir::ItemKind::ExternCrate(..)
2102 | hir::ItemKind::Use(..)
2103 | hir::ItemKind::TyAlias(..)
2104 | hir::ItemKind::OpaqueTy(..)
2105 | hir::ItemKind::TraitAlias(..) => {
2106 // no sub-item recording needed in these cases
2108 hir::ItemKind::Enum(..) => {
2109 let def = self.tcx.adt_def(item.def_id.to_def_id());
2110 self.encode_fields(def);
2112 for (i, variant) in def.variants().iter_enumerated() {
2113 self.encode_enum_variant_info(def, i);
2115 if let Some(_ctor_def_id) = variant.ctor_def_id {
2116 self.encode_enum_variant_ctor(def, i);
2120 hir::ItemKind::Struct(ref struct_def, _) => {
2121 let def = self.tcx.adt_def(item.def_id.to_def_id());
2122 self.encode_fields(def);
2124 // If the struct has a constructor, encode it.
2125 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
2126 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
2127 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
2130 hir::ItemKind::Union(..) => {
2131 let def = self.tcx.adt_def(item.def_id.to_def_id());
2132 self.encode_fields(def);
2134 hir::ItemKind::Impl { .. } => {
2135 for &trait_item_def_id in
2136 self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2138 self.encode_info_for_impl_item(trait_item_def_id);
2141 hir::ItemKind::Trait(..) => {
2142 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2144 self.encode_info_for_trait_item(item_def_id);
2151 /// Used to prefetch queries which will be needed later by metadata encoding.
2152 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2153 fn prefetch_mir(tcx: TyCtxt<'_>) {
2154 if !tcx.sess.opts.output_types.should_codegen() {
2155 // We won't emit MIR, so don't prefetch it.
2159 par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2160 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2163 tcx.ensure().mir_for_ctfe(def_id);
2166 tcx.ensure().optimized_mir(def_id);
2168 if encode_opt || encode_const {
2169 tcx.ensure().promoted_mir(def_id);
2174 // NOTE(eddyb) The following comment was preserved for posterity, even
2175 // though it's no longer relevant as EBML (which uses nested & tagged
2176 // "documents") was replaced with a scheme that can't go out of bounds.
2178 // And here we run into yet another obscure archive bug: in which metadata
2179 // loaded from archives may have trailing garbage bytes. Awhile back one of
2180 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2181 // and opt) by having ebml generate an out-of-bounds panic when looking at
2184 // Upon investigation it turned out that the metadata file inside of an rlib
2185 // (and ar archive) was being corrupted. Some compilations would generate a
2186 // metadata file which would end in a few extra bytes, while other
2187 // compilations would not have these extra bytes appended to the end. These
2188 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2189 // being interpreted causing the out-of-bounds.
2191 // The root cause of why these extra bytes were appearing was never
2192 // discovered, and in the meantime the solution we're employing is to insert
2193 // the length of the metadata to the start of the metadata. Later on this
2194 // will allow us to slice the metadata to the precise length that we just
2195 // generated regardless of trailing bytes that end up in it.
2197 pub struct EncodedMetadata {
2198 // The declaration order matters because `mmap` should be dropped before `_temp_dir`.
2200 // We need to carry MaybeTempDir to avoid deleting the temporary
2201 // directory while accessing the Mmap.
2202 _temp_dir: Option<MaybeTempDir>,
2205 impl EncodedMetadata {
2207 pub fn from_path(path: PathBuf, temp_dir: Option<MaybeTempDir>) -> std::io::Result<Self> {
2208 let file = std::fs::File::open(&path)?;
2209 let file_metadata = file.metadata()?;
2210 if file_metadata.len() == 0 {
2211 return Ok(Self { mmap: None, _temp_dir: None });
2213 let mmap = unsafe { Some(Mmap::map(file)?) };
2214 Ok(Self { mmap, _temp_dir: temp_dir })
2218 pub fn raw_data(&self) -> &[u8] {
2219 self.mmap.as_ref().map(|mmap| mmap.as_ref()).unwrap_or_default()
2223 impl<S: Encoder> Encodable<S> for EncodedMetadata {
2224 fn encode(&self, s: &mut S) {
2225 let slice = self.raw_data();
2230 impl<D: Decoder> Decodable<D> for EncodedMetadata {
2231 fn decode(d: &mut D) -> Self {
2232 let len = d.read_usize();
2233 let mmap = if len > 0 {
2234 let mut mmap = MmapMut::map_anon(len).unwrap();
2236 (&mut mmap[..]).write(&[d.read_u8()]).unwrap();
2238 mmap.flush().unwrap();
2239 Some(mmap.make_read_only().unwrap())
2244 Self { mmap, _temp_dir: None }
2248 pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path) {
2249 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2251 // Since encoding metadata is not in a query, and nothing is cached,
2252 // there's no need to do dep-graph tracking for any of it.
2253 tcx.dep_graph.assert_ignored();
2256 || encode_metadata_impl(tcx, path),
2258 if tcx.sess.threads() == 1 {
2261 // Prefetch some queries used by metadata encoding.
2262 // This is not necessary for correctness, but is only done for performance reasons.
2263 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2264 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2269 fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) {
2270 let mut encoder = opaque::FileEncoder::new(path)
2271 .unwrap_or_else(|err| tcx.sess.fatal(&format!("failed to create file encoder: {}", err)));
2272 encoder.emit_raw_bytes(METADATA_HEADER);
2274 // Will be filled with the root position after encoding everything.
2275 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2277 let source_map_files = tcx.sess.source_map().files();
2278 let source_file_cache = (source_map_files[0].clone(), 0);
2279 let required_source_files = Some(FxIndexSet::default());
2280 drop(source_map_files);
2282 let hygiene_ctxt = HygieneEncodeContext::default();
2284 let mut ecx = EncodeContext {
2287 feat: tcx.features(),
2288 tables: Default::default(),
2289 lazy_state: LazyState::NoNode,
2290 type_shorthands: Default::default(),
2291 predicate_shorthands: Default::default(),
2293 interpret_allocs: Default::default(),
2294 required_source_files,
2295 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2296 hygiene_ctxt: &hygiene_ctxt,
2297 symbol_table: Default::default(),
2300 // Encode the rustc version string in a predictable location.
2301 rustc_version().encode(&mut ecx);
2303 // Encode all the entries and extra information in the crate,
2304 // culminating in the `CrateRoot` which points to all of it.
2305 let root = ecx.encode_crate_root();
2309 let mut file = ecx.opaque.file();
2310 // We will return to this position after writing the root position.
2311 let pos_before_seek = file.stream_position().unwrap();
2313 // Encode the root position.
2314 let header = METADATA_HEADER.len();
2315 file.seek(std::io::SeekFrom::Start(header as u64))
2316 .unwrap_or_else(|err| tcx.sess.fatal(&format!("failed to seek the file: {}", err)));
2317 let pos = root.position.get();
2318 file.write_all(&[(pos >> 24) as u8, (pos >> 16) as u8, (pos >> 8) as u8, (pos >> 0) as u8])
2319 .unwrap_or_else(|err| tcx.sess.fatal(&format!("failed to write to the file: {}", err)));
2321 // Return to the position where we are before writing the root position.
2322 file.seek(std::io::SeekFrom::Start(pos_before_seek)).unwrap();
2324 // Record metadata size for self-profiling
2325 tcx.prof.artifact_size(
2328 file.metadata().unwrap().len() as u64,
2332 pub fn provide(providers: &mut Providers) {
2333 *providers = Providers {
2334 traits_in_crate: |tcx, cnum| {
2335 assert_eq!(cnum, LOCAL_CRATE);
2337 let mut traits = Vec::new();
2338 for id in tcx.hir().items() {
2339 if matches!(tcx.def_kind(id.def_id), DefKind::Trait | DefKind::TraitAlias) {
2340 traits.push(id.def_id.to_def_id())
2344 // Bring everything into deterministic order.
2345 traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
2346 tcx.arena.alloc_slice(&traits)