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_ast::attr::AttributeExt;
9use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
10use rustc_data_structures::memmap::{Mmap, MmapMut};
11use rustc_data_structures::sync::{join, par_for_each_in};
12use rustc_data_structures::temp_dir::MaybeTempDir;
13use rustc_data_structures::thousands::format_with_underscores;
14use rustc_feature::Features;
15use rustc_hir as hir;
16use rustc_hir::def_id::{CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE, LocalDefId, LocalDefIdSet};
17use rustc_hir::definitions::DefPathData;
18use rustc_hir_pretty::id_to_string;
19use rustc_middle::middle::dependency_format::Linkage;
20use rustc_middle::middle::exported_symbols::metadata_symbol_name;
21use rustc_middle::mir::interpret;
22use rustc_middle::query::Providers;
23use rustc_middle::traits::specialization_graph;
24use rustc_middle::ty::codec::TyEncoder;
25use rustc_middle::ty::fast_reject::{self, TreatParams};
26use rustc_middle::ty::{AssocItemContainer, SymbolName};
27use rustc_middle::{bug, span_bug};
28use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque};
29use rustc_session::config::{CrateType, OptLevel, TargetModifier};
30use rustc_span::hygiene::HygieneEncodeContext;
31use rustc_span::{
32 ExternalSource, FileName, SourceFile, SpanData, SpanEncoder, StableSourceFileId, SyntaxContext,
33 sym,
34};
35use tracing::{debug, instrument, trace};
36
37use crate::errors::{FailCreateFileEncoder, FailWriteFile};
38use crate::rmeta::*;
39
40pub(super) struct EncodeContext<'a, 'tcx> {
41 opaque: opaque::FileEncoder,
42 tcx: TyCtxt<'tcx>,
43 feat: &'tcx rustc_feature::Features,
44 tables: TableBuilders,
45
46 lazy_state: LazyState,
47 span_shorthands: FxHashMap<Span, usize>,
48 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
49 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
50
51 interpret_allocs: FxIndexSet<interpret::AllocId>,
52
53 source_file_cache: (Arc<SourceFile>, usize),
57 required_source_files: Option<FxIndexSet<usize>>,
64 is_proc_macro: bool,
65 hygiene_ctxt: &'a HygieneEncodeContext,
66 symbol_table: FxHashMap<Symbol, usize>,
67}
68
69macro_rules! empty_proc_macro {
73 ($self:ident) => {
74 if $self.is_proc_macro {
75 return LazyArray::default();
76 }
77 };
78}
79
80macro_rules! encoder_methods {
81 ($($name:ident($ty:ty);)*) => {
82 $(fn $name(&mut self, value: $ty) {
83 self.opaque.$name(value)
84 })*
85 }
86}
87
88impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
89 encoder_methods! {
90 emit_usize(usize);
91 emit_u128(u128);
92 emit_u64(u64);
93 emit_u32(u32);
94 emit_u16(u16);
95 emit_u8(u8);
96
97 emit_isize(isize);
98 emit_i128(i128);
99 emit_i64(i64);
100 emit_i32(i32);
101 emit_i16(i16);
102
103 emit_raw_bytes(&[u8]);
104 }
105}
106
107impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
108 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
109 e.emit_lazy_distance(self.position);
110 }
111}
112
113impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
114 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
115 e.emit_usize(self.num_elems);
116 if self.num_elems > 0 {
117 e.emit_lazy_distance(self.position)
118 }
119 }
120}
121
122impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
123 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
124 e.emit_usize(self.width);
125 e.emit_usize(self.len);
126 e.emit_lazy_distance(self.position);
127 }
128}
129
130impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
131 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
132 s.emit_u32(self.as_u32());
133 }
134}
135
136impl<'a, 'tcx> SpanEncoder for EncodeContext<'a, 'tcx> {
137 fn encode_crate_num(&mut self, crate_num: CrateNum) {
138 if crate_num != LOCAL_CRATE && self.is_proc_macro {
139 panic!("Attempted to encode non-local CrateNum {crate_num:?} for proc-macro crate");
140 }
141 self.emit_u32(crate_num.as_u32());
142 }
143
144 fn encode_def_index(&mut self, def_index: DefIndex) {
145 self.emit_u32(def_index.as_u32());
146 }
147
148 fn encode_def_id(&mut self, def_id: DefId) {
149 def_id.krate.encode(self);
150 def_id.index.encode(self);
151 }
152
153 fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
154 rustc_span::hygiene::raw_encode_syntax_context(syntax_context, self.hygiene_ctxt, self);
155 }
156
157 fn encode_expn_id(&mut self, expn_id: ExpnId) {
158 if expn_id.krate == LOCAL_CRATE {
159 self.hygiene_ctxt.schedule_expn_data_for_encoding(expn_id);
164 }
165 expn_id.krate.encode(self);
166 expn_id.local_id.encode(self);
167 }
168
169 fn encode_span(&mut self, span: Span) {
170 match self.span_shorthands.entry(span) {
171 Entry::Occupied(o) => {
172 let last_location = *o.get();
175 let offset = self.opaque.position() - last_location;
178 if offset < last_location {
179 let needed = bytes_needed(offset);
180 SpanTag::indirect(true, needed as u8).encode(self);
181 self.opaque.write_with(|dest| {
182 *dest = offset.to_le_bytes();
183 needed
184 });
185 } else {
186 let needed = bytes_needed(last_location);
187 SpanTag::indirect(false, needed as u8).encode(self);
188 self.opaque.write_with(|dest| {
189 *dest = last_location.to_le_bytes();
190 needed
191 });
192 }
193 }
194 Entry::Vacant(v) => {
195 let position = self.opaque.position();
196 v.insert(position);
197 span.data().encode(self);
199 }
200 }
201 }
202
203 fn encode_symbol(&mut self, symbol: Symbol) {
204 if symbol.is_preinterned() {
206 self.opaque.emit_u8(SYMBOL_PREINTERNED);
207 self.opaque.emit_u32(symbol.as_u32());
208 } else {
209 match self.symbol_table.entry(symbol) {
211 Entry::Vacant(o) => {
212 self.opaque.emit_u8(SYMBOL_STR);
213 let pos = self.opaque.position();
214 o.insert(pos);
215 self.emit_str(symbol.as_str());
216 }
217 Entry::Occupied(o) => {
218 let x = *o.get();
219 self.emit_u8(SYMBOL_OFFSET);
220 self.emit_usize(x);
221 }
222 }
223 }
224 }
225}
226
227fn bytes_needed(n: usize) -> usize {
228 (usize::BITS - n.leading_zeros()).div_ceil(u8::BITS) as usize
229}
230
231impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SpanData {
232 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
233 let ctxt = if s.is_proc_macro { SyntaxContext::root() } else { self.ctxt };
265
266 if self.is_dummy() {
267 let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
268 tag.encode(s);
269 if tag.context().is_none() {
270 ctxt.encode(s);
271 }
272 return;
273 }
274
275 debug_assert!(self.lo <= self.hi);
277
278 if !s.source_file_cache.0.contains(self.lo) {
279 let source_map = s.tcx.sess.source_map();
280 let source_file_index = source_map.lookup_source_file_idx(self.lo);
281 s.source_file_cache =
282 (Arc::clone(&source_map.files()[source_file_index]), source_file_index);
283 }
284 let (ref source_file, source_file_index) = s.source_file_cache;
285 debug_assert!(source_file.contains(self.lo));
286
287 if !source_file.contains(self.hi) {
288 let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
291 tag.encode(s);
292 if tag.context().is_none() {
293 ctxt.encode(s);
294 }
295 return;
296 }
297
298 let (kind, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
315 let metadata_index = {
325 match &*source_file.external_src.read() {
327 ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
328 src => panic!("Unexpected external source {src:?}"),
329 }
330 };
331
332 (SpanKind::Foreign, metadata_index)
333 } else {
334 let source_files =
336 s.required_source_files.as_mut().expect("Already encoded SourceMap!");
337 let (metadata_index, _) = source_files.insert_full(source_file_index);
338 let metadata_index: u32 =
339 metadata_index.try_into().expect("cannot export more than U32_MAX files");
340
341 (SpanKind::Local, metadata_index)
342 };
343
344 let lo = self.lo - source_file.start_pos;
347
348 let len = self.hi - self.lo;
351
352 let tag = SpanTag::new(kind, ctxt, len.0 as usize);
353 tag.encode(s);
354 if tag.context().is_none() {
355 ctxt.encode(s);
356 }
357 lo.encode(s);
358 if tag.length().is_none() {
359 len.encode(s);
360 }
361
362 metadata_index.encode(s);
364
365 if kind == SpanKind::Foreign {
366 let cnum = s.source_file_cache.0.cnum;
369 cnum.encode(s);
370 }
371 }
372}
373
374impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for [u8] {
375 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
376 Encoder::emit_usize(e, self.len());
377 e.emit_raw_bytes(self);
378 }
379}
380
381impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
382 const CLEAR_CROSS_CRATE: bool = true;
383
384 fn position(&self) -> usize {
385 self.opaque.position()
386 }
387
388 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
389 &mut self.type_shorthands
390 }
391
392 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
393 &mut self.predicate_shorthands
394 }
395
396 fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
397 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
398
399 index.encode(self);
400 }
401}
402
403macro_rules! record {
406 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
407 {
408 let value = $value;
409 let lazy = $self.lazy(value);
410 $self.$tables.$table.set_some($def_id.index, lazy);
411 }
412 }};
413}
414
415macro_rules! record_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_some($def_id.index, lazy);
423 }
424 }};
425}
426
427macro_rules! record_defaulted_array {
428 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
429 {
430 let value = $value;
431 let lazy = $self.lazy_array(value);
432 $self.$tables.$table.set($def_id.index, lazy);
433 }
434 }};
435}
436
437impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
438 fn emit_lazy_distance(&mut self, position: NonZero<usize>) {
439 let pos = position.get();
440 let distance = match self.lazy_state {
441 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
442 LazyState::NodeStart(start) => {
443 let start = start.get();
444 assert!(pos <= start);
445 start - pos
446 }
447 LazyState::Previous(last_pos) => {
448 assert!(
449 last_pos <= position,
450 "make sure that the calls to `lazy*` \
451 are in the same order as the metadata fields",
452 );
453 position.get() - last_pos.get()
454 }
455 };
456 self.lazy_state = LazyState::Previous(NonZero::new(pos).unwrap());
457 self.emit_usize(distance);
458 }
459
460 fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
461 where
462 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
463 {
464 let pos = NonZero::new(self.position()).unwrap();
465
466 assert_eq!(self.lazy_state, LazyState::NoNode);
467 self.lazy_state = LazyState::NodeStart(pos);
468 value.borrow().encode(self);
469 self.lazy_state = LazyState::NoNode;
470
471 assert!(pos.get() <= self.position());
472
473 LazyValue::from_position(pos)
474 }
475
476 fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
477 &mut self,
478 values: I,
479 ) -> LazyArray<T>
480 where
481 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
482 {
483 let pos = NonZero::new(self.position()).unwrap();
484
485 assert_eq!(self.lazy_state, LazyState::NoNode);
486 self.lazy_state = LazyState::NodeStart(pos);
487 let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
488 self.lazy_state = LazyState::NoNode;
489
490 assert!(pos.get() <= self.position());
491
492 LazyArray::from_position_and_num_elems(pos, len)
493 }
494
495 fn encode_def_path_table(&mut self) {
496 let table = self.tcx.def_path_table();
497 if self.is_proc_macro {
498 for def_index in std::iter::once(CRATE_DEF_INDEX)
499 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
500 {
501 let def_key = self.lazy(table.def_key(def_index));
502 let def_path_hash = table.def_path_hash(def_index);
503 self.tables.def_keys.set_some(def_index, def_key);
504 self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
505 }
506 } else {
507 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
508 let def_key = self.lazy(def_key);
509 self.tables.def_keys.set_some(def_index, def_key);
510 self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
511 }
512 }
513 }
514
515 fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
516 self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
517 }
518
519 fn encode_source_map(&mut self) -> LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>> {
520 let source_map = self.tcx.sess.source_map();
521 let all_source_files = source_map.files();
522
523 let required_source_files = self.required_source_files.take().unwrap();
527
528 let working_directory = &self.tcx.sess.opts.working_dir;
529
530 let mut adapted = TableBuilder::default();
531
532 let local_crate_stable_id = self.tcx.stable_crate_id(LOCAL_CRATE);
533
534 for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
539 let source_file = &all_source_files[source_file_index];
540 assert!(!source_file.is_imported() || self.is_proc_macro);
542
543 let mut adapted_source_file = (**source_file).clone();
551
552 match source_file.name {
553 FileName::Real(ref original_file_name) => {
554 let adapted_file_name = source_map
557 .path_mapping()
558 .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
559
560 adapted_source_file.name = FileName::Real(adapted_file_name);
561 }
562 _ => {
563 }
565 };
566
567 if self.is_proc_macro {
574 adapted_source_file.cnum = LOCAL_CRATE;
575 }
576
577 adapted_source_file.stable_id = StableSourceFileId::from_filename_for_export(
581 &adapted_source_file.name,
582 local_crate_stable_id,
583 );
584
585 let on_disk_index: u32 =
586 on_disk_index.try_into().expect("cannot export more than U32_MAX files");
587 adapted.set_some(on_disk_index, self.lazy(adapted_source_file));
588 }
589
590 adapted.encode(&mut self.opaque)
591 }
592
593 fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
594 let tcx = self.tcx;
595 let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
596
597 macro_rules! stat {
598 ($label:literal, $f:expr) => {{
599 let orig_pos = self.position();
600 let res = $f();
601 stats.push(($label, self.position() - orig_pos));
602 res
603 }};
604 }
605
606 stats.push(("preamble", self.position()));
608
609 let (crate_deps, dylib_dependency_formats) =
610 stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
611
612 let lib_features = stat!("lib-features", || self.encode_lib_features());
613
614 let stability_implications =
615 stat!("stability-implications", || self.encode_stability_implications());
616
617 let (lang_items, lang_items_missing) = stat!("lang-items", || {
618 (self.encode_lang_items(), self.encode_lang_items_missing())
619 });
620
621 let stripped_cfg_items = stat!("stripped-cfg-items", || self.encode_stripped_cfg_items());
622
623 let diagnostic_items = stat!("diagnostic-items", || self.encode_diagnostic_items());
624
625 let native_libraries = stat!("native-libs", || self.encode_native_libraries());
626
627 let foreign_modules = stat!("foreign-modules", || self.encode_foreign_modules());
628
629 _ = stat!("def-path-table", || self.encode_def_path_table());
630
631 let traits = stat!("traits", || self.encode_traits());
633
634 let impls = stat!("impls", || self.encode_impls());
636
637 let incoherent_impls = stat!("incoherent-impls", || self.encode_incoherent_impls());
638
639 _ = stat!("mir", || self.encode_mir());
640
641 _ = stat!("def-ids", || self.encode_def_ids());
642
643 let interpret_alloc_index = stat!("interpret-alloc-index", || {
644 let mut interpret_alloc_index = Vec::new();
645 let mut n = 0;
646 trace!("beginning to encode alloc ids");
647 loop {
648 let new_n = self.interpret_allocs.len();
649 if n == new_n {
651 break;
653 }
654 trace!("encoding {} further alloc ids", new_n - n);
655 for idx in n..new_n {
656 let id = self.interpret_allocs[idx];
657 let pos = self.position() as u64;
658 interpret_alloc_index.push(pos);
659 interpret::specialized_encode_alloc_id(self, tcx, id);
660 }
661 n = new_n;
662 }
663 self.lazy_array(interpret_alloc_index)
664 });
665
666 let proc_macro_data = stat!("proc-macro-data", || self.encode_proc_macros());
670
671 let tables = stat!("tables", || self.tables.encode(&mut self.opaque));
672
673 let debugger_visualizers =
674 stat!("debugger-visualizers", || self.encode_debugger_visualizers());
675
676 let exported_symbols = stat!("exported-symbols", || {
678 self.encode_exported_symbols(tcx.exported_symbols(LOCAL_CRATE))
679 });
680
681 let (syntax_contexts, expn_data, expn_hashes) = stat!("hygiene", || self.encode_hygiene());
688
689 let def_path_hash_map = stat!("def-path-hash-map", || self.encode_def_path_hash_map());
690
691 let source_map = stat!("source-map", || self.encode_source_map());
694 let target_modifiers = stat!("target-modifiers", || self.encode_target_modifiers());
695
696 let root = stat!("final", || {
697 let attrs = tcx.hir_krate_attrs();
698 self.lazy(CrateRoot {
699 header: CrateHeader {
700 name: tcx.crate_name(LOCAL_CRATE),
701 triple: tcx.sess.opts.target_triple.clone(),
702 hash: tcx.crate_hash(LOCAL_CRATE),
703 is_proc_macro_crate: proc_macro_data.is_some(),
704 },
705 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
706 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
707 required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
708 panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
709 edition: tcx.sess.edition(),
710 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
711 has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
712 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
713 has_default_lib_allocator: ast::attr::contains_name(
714 attrs,
715 sym::default_lib_allocator,
716 ),
717 proc_macro_data,
718 debugger_visualizers,
719 compiler_builtins: ast::attr::contains_name(attrs, sym::compiler_builtins),
720 needs_allocator: ast::attr::contains_name(attrs, sym::needs_allocator),
721 needs_panic_runtime: ast::attr::contains_name(attrs, sym::needs_panic_runtime),
722 no_builtins: ast::attr::contains_name(attrs, sym::no_builtins),
723 panic_runtime: ast::attr::contains_name(attrs, sym::panic_runtime),
724 profiler_runtime: ast::attr::contains_name(attrs, sym::profiler_runtime),
725 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
726
727 crate_deps,
728 dylib_dependency_formats,
729 lib_features,
730 stability_implications,
731 lang_items,
732 diagnostic_items,
733 lang_items_missing,
734 stripped_cfg_items,
735 native_libraries,
736 foreign_modules,
737 source_map,
738 target_modifiers,
739 traits,
740 impls,
741 incoherent_impls,
742 exported_symbols,
743 interpret_alloc_index,
744 tables,
745 syntax_contexts,
746 expn_data,
747 expn_hashes,
748 def_path_hash_map,
749 specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
750 })
751 });
752
753 let total_bytes = self.position();
754
755 let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
756 assert_eq!(total_bytes, computed_total_bytes);
757
758 if tcx.sess.opts.unstable_opts.meta_stats {
759 self.opaque.flush();
760
761 let pos_before_rewind = self.opaque.file().stream_position().unwrap();
763 let mut zero_bytes = 0;
764 self.opaque.file().rewind().unwrap();
765 let file = std::io::BufReader::new(self.opaque.file());
766 for e in file.bytes() {
767 if e.unwrap() == 0 {
768 zero_bytes += 1;
769 }
770 }
771 assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
772
773 stats.sort_by_key(|&(_, usize)| usize);
774
775 let prefix = "meta-stats";
776 let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
777
778 eprintln!("{prefix} METADATA STATS");
779 eprintln!("{} {:<23}{:>10}", prefix, "Section", "Size");
780 eprintln!("{prefix} ----------------------------------------------------------------");
781 for (label, size) in stats {
782 eprintln!(
783 "{} {:<23}{:>10} ({:4.1}%)",
784 prefix,
785 label,
786 format_with_underscores(size),
787 perc(size)
788 );
789 }
790 eprintln!("{prefix} ----------------------------------------------------------------");
791 eprintln!(
792 "{} {:<23}{:>10} (of which {:.1}% are zero bytes)",
793 prefix,
794 "Total",
795 format_with_underscores(total_bytes),
796 perc(zero_bytes)
797 );
798 eprintln!("{prefix}");
799 }
800
801 root
802 }
803}
804
805struct AnalyzeAttrState<'a> {
806 is_exported: bool,
807 is_doc_hidden: bool,
808 features: &'a Features,
809}
810
811#[inline]
821fn analyze_attr(attr: &impl AttributeExt, state: &mut AnalyzeAttrState<'_>) -> bool {
822 let mut should_encode = false;
823 if !rustc_feature::encode_cross_crate(attr.name_or_empty()) {
824 } else if attr.doc_str().is_some() {
826 if state.is_exported {
830 should_encode = true;
831 }
832 } else if attr.has_name(sym::doc) {
833 if let Some(item_list) = attr.meta_item_list() {
836 for item in item_list {
837 if !item.has_name(sym::inline) {
838 should_encode = true;
839 if item.has_name(sym::hidden) {
840 state.is_doc_hidden = true;
841 break;
842 }
843 }
844 }
845 }
846 } else if let &[sym::diagnostic, seg] = &*attr.path() {
847 should_encode = rustc_feature::is_stable_diagnostic_attribute(seg, state.features);
848 } else {
849 should_encode = true;
850 }
851 should_encode
852}
853
854fn should_encode_span(def_kind: DefKind) -> bool {
855 match def_kind {
856 DefKind::Mod
857 | DefKind::Struct
858 | DefKind::Union
859 | DefKind::Enum
860 | DefKind::Variant
861 | DefKind::Trait
862 | DefKind::TyAlias
863 | DefKind::ForeignTy
864 | DefKind::TraitAlias
865 | DefKind::AssocTy
866 | DefKind::TyParam
867 | DefKind::ConstParam
868 | DefKind::LifetimeParam
869 | DefKind::Fn
870 | DefKind::Const
871 | DefKind::Static { .. }
872 | DefKind::Ctor(..)
873 | DefKind::AssocFn
874 | DefKind::AssocConst
875 | DefKind::Macro(_)
876 | DefKind::ExternCrate
877 | DefKind::Use
878 | DefKind::AnonConst
879 | DefKind::InlineConst
880 | DefKind::OpaqueTy
881 | DefKind::Field
882 | DefKind::Impl { .. }
883 | DefKind::Closure
884 | DefKind::SyntheticCoroutineBody => true,
885 DefKind::ForeignMod | DefKind::GlobalAsm => false,
886 }
887}
888
889fn should_encode_attrs(def_kind: DefKind) -> bool {
890 match def_kind {
891 DefKind::Mod
892 | DefKind::Struct
893 | DefKind::Union
894 | DefKind::Enum
895 | DefKind::Variant
896 | DefKind::Trait
897 | DefKind::TyAlias
898 | DefKind::ForeignTy
899 | DefKind::TraitAlias
900 | DefKind::AssocTy
901 | DefKind::Fn
902 | DefKind::Const
903 | DefKind::Static { nested: false, .. }
904 | DefKind::AssocFn
905 | DefKind::AssocConst
906 | DefKind::Macro(_)
907 | DefKind::Field
908 | DefKind::Impl { .. } => true,
909 DefKind::Closure => true,
914 DefKind::SyntheticCoroutineBody => false,
915 DefKind::TyParam
916 | DefKind::ConstParam
917 | DefKind::Ctor(..)
918 | DefKind::ExternCrate
919 | DefKind::Use
920 | DefKind::ForeignMod
921 | DefKind::AnonConst
922 | DefKind::InlineConst
923 | DefKind::OpaqueTy
924 | DefKind::LifetimeParam
925 | DefKind::Static { nested: true, .. }
926 | DefKind::GlobalAsm => false,
927 }
928}
929
930fn should_encode_expn_that_defined(def_kind: DefKind) -> bool {
931 match def_kind {
932 DefKind::Mod
933 | DefKind::Struct
934 | DefKind::Union
935 | DefKind::Enum
936 | DefKind::Variant
937 | DefKind::Trait
938 | DefKind::Impl { .. } => true,
939 DefKind::TyAlias
940 | DefKind::ForeignTy
941 | DefKind::TraitAlias
942 | DefKind::AssocTy
943 | DefKind::TyParam
944 | DefKind::Fn
945 | DefKind::Const
946 | DefKind::ConstParam
947 | DefKind::Static { .. }
948 | DefKind::Ctor(..)
949 | DefKind::AssocFn
950 | DefKind::AssocConst
951 | DefKind::Macro(_)
952 | DefKind::ExternCrate
953 | DefKind::Use
954 | DefKind::ForeignMod
955 | DefKind::AnonConst
956 | DefKind::InlineConst
957 | DefKind::OpaqueTy
958 | DefKind::Field
959 | DefKind::LifetimeParam
960 | DefKind::GlobalAsm
961 | DefKind::Closure
962 | DefKind::SyntheticCoroutineBody => false,
963 }
964}
965
966fn should_encode_visibility(def_kind: DefKind) -> bool {
967 match def_kind {
968 DefKind::Mod
969 | DefKind::Struct
970 | DefKind::Union
971 | DefKind::Enum
972 | DefKind::Variant
973 | DefKind::Trait
974 | DefKind::TyAlias
975 | DefKind::ForeignTy
976 | DefKind::TraitAlias
977 | DefKind::AssocTy
978 | DefKind::Fn
979 | DefKind::Const
980 | DefKind::Static { nested: false, .. }
981 | DefKind::Ctor(..)
982 | DefKind::AssocFn
983 | DefKind::AssocConst
984 | DefKind::Macro(..)
985 | DefKind::Field => true,
986 DefKind::Use
987 | DefKind::ForeignMod
988 | DefKind::TyParam
989 | DefKind::ConstParam
990 | DefKind::LifetimeParam
991 | DefKind::AnonConst
992 | DefKind::InlineConst
993 | DefKind::Static { nested: true, .. }
994 | DefKind::OpaqueTy
995 | DefKind::GlobalAsm
996 | DefKind::Impl { .. }
997 | DefKind::Closure
998 | DefKind::ExternCrate
999 | DefKind::SyntheticCoroutineBody => false,
1000 }
1001}
1002
1003fn should_encode_stability(def_kind: DefKind) -> bool {
1004 match def_kind {
1005 DefKind::Mod
1006 | DefKind::Ctor(..)
1007 | DefKind::Variant
1008 | DefKind::Field
1009 | DefKind::Struct
1010 | DefKind::AssocTy
1011 | DefKind::AssocFn
1012 | DefKind::AssocConst
1013 | DefKind::TyParam
1014 | DefKind::ConstParam
1015 | DefKind::Static { .. }
1016 | DefKind::Const
1017 | DefKind::Fn
1018 | DefKind::ForeignMod
1019 | DefKind::TyAlias
1020 | DefKind::OpaqueTy
1021 | DefKind::Enum
1022 | DefKind::Union
1023 | DefKind::Impl { .. }
1024 | DefKind::Trait
1025 | DefKind::TraitAlias
1026 | DefKind::Macro(..)
1027 | DefKind::ForeignTy => true,
1028 DefKind::Use
1029 | DefKind::LifetimeParam
1030 | DefKind::AnonConst
1031 | DefKind::InlineConst
1032 | DefKind::GlobalAsm
1033 | DefKind::Closure
1034 | DefKind::ExternCrate
1035 | DefKind::SyntheticCoroutineBody => false,
1036 }
1037}
1038
1039fn should_encode_mir(
1060 tcx: TyCtxt<'_>,
1061 reachable_set: &LocalDefIdSet,
1062 def_id: LocalDefId,
1063) -> (bool, bool) {
1064 match tcx.def_kind(def_id) {
1065 DefKind::Ctor(_, _) => {
1067 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
1068 || tcx.sess.opts.unstable_opts.always_encode_mir;
1069 (true, mir_opt_base)
1070 }
1071 DefKind::AnonConst | DefKind::InlineConst | DefKind::AssocConst | DefKind::Const => {
1073 (true, false)
1074 }
1075 DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1077 DefKind::SyntheticCoroutineBody => (false, true),
1078 DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1080 let generics = tcx.generics_of(def_id);
1081 let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1082 || (tcx.sess.opts.output_types.should_codegen()
1083 && reachable_set.contains(&def_id)
1084 && (generics.requires_monomorphization(tcx)
1085 || tcx.cross_crate_inlinable(def_id)));
1086 let is_const_fn = tcx.is_const_fn(def_id.to_def_id())
1088 || tcx.is_const_default_method(def_id.to_def_id());
1089 (is_const_fn, opt)
1090 }
1091 _ => (false, false),
1093 }
1094}
1095
1096fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1097 match def_kind {
1098 DefKind::Struct
1099 | DefKind::Union
1100 | DefKind::Enum
1101 | DefKind::Variant
1102 | DefKind::OpaqueTy
1103 | DefKind::Fn
1104 | DefKind::Ctor(..)
1105 | DefKind::AssocFn => true,
1106 DefKind::AssocTy => {
1107 matches!(tcx.opt_rpitit_info(def_id), Some(ty::ImplTraitInTraitData::Trait { .. }))
1109 }
1110 DefKind::Mod
1111 | DefKind::Field
1112 | DefKind::AssocConst
1113 | DefKind::TyParam
1114 | DefKind::ConstParam
1115 | DefKind::Static { .. }
1116 | DefKind::Const
1117 | DefKind::ForeignMod
1118 | DefKind::Impl { .. }
1119 | DefKind::Trait
1120 | DefKind::TraitAlias
1121 | DefKind::Macro(..)
1122 | DefKind::ForeignTy
1123 | DefKind::Use
1124 | DefKind::LifetimeParam
1125 | DefKind::AnonConst
1126 | DefKind::InlineConst
1127 | DefKind::GlobalAsm
1128 | DefKind::Closure
1129 | DefKind::ExternCrate
1130 | DefKind::SyntheticCoroutineBody => false,
1131 DefKind::TyAlias => tcx.type_alias_is_lazy(def_id),
1132 }
1133}
1134
1135fn should_encode_generics(def_kind: DefKind) -> bool {
1136 match def_kind {
1137 DefKind::Struct
1138 | DefKind::Union
1139 | DefKind::Enum
1140 | DefKind::Variant
1141 | DefKind::Trait
1142 | DefKind::TyAlias
1143 | DefKind::ForeignTy
1144 | DefKind::TraitAlias
1145 | DefKind::AssocTy
1146 | DefKind::Fn
1147 | DefKind::Const
1148 | DefKind::Static { .. }
1149 | DefKind::Ctor(..)
1150 | DefKind::AssocFn
1151 | DefKind::AssocConst
1152 | DefKind::AnonConst
1153 | DefKind::InlineConst
1154 | DefKind::OpaqueTy
1155 | DefKind::Impl { .. }
1156 | DefKind::Field
1157 | DefKind::TyParam
1158 | DefKind::Closure
1159 | DefKind::SyntheticCoroutineBody => true,
1160 DefKind::Mod
1161 | DefKind::ForeignMod
1162 | DefKind::ConstParam
1163 | DefKind::Macro(..)
1164 | DefKind::Use
1165 | DefKind::LifetimeParam
1166 | DefKind::GlobalAsm
1167 | DefKind::ExternCrate => false,
1168 }
1169}
1170
1171fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1172 match def_kind {
1173 DefKind::Struct
1174 | DefKind::Union
1175 | DefKind::Enum
1176 | DefKind::Variant
1177 | DefKind::Ctor(..)
1178 | DefKind::Field
1179 | DefKind::Fn
1180 | DefKind::Const
1181 | DefKind::Static { nested: false, .. }
1182 | DefKind::TyAlias
1183 | DefKind::ForeignTy
1184 | DefKind::Impl { .. }
1185 | DefKind::AssocFn
1186 | DefKind::AssocConst
1187 | DefKind::Closure
1188 | DefKind::ConstParam
1189 | DefKind::AnonConst
1190 | DefKind::InlineConst
1191 | DefKind::SyntheticCoroutineBody => true,
1192
1193 DefKind::OpaqueTy => {
1194 let origin = tcx.local_opaque_ty_origin(def_id);
1195 if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1196 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1197 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1198 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1199 {
1200 false
1201 } else {
1202 true
1203 }
1204 }
1205
1206 DefKind::AssocTy => {
1207 let assoc_item = tcx.associated_item(def_id);
1208 match assoc_item.container {
1209 ty::AssocItemContainer::Impl => true,
1210 ty::AssocItemContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1211 }
1212 }
1213 DefKind::TyParam => {
1214 let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(def_id) else { bug!() };
1215 let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() };
1216 default.is_some()
1217 }
1218
1219 DefKind::Trait
1220 | DefKind::TraitAlias
1221 | DefKind::Mod
1222 | DefKind::ForeignMod
1223 | DefKind::Macro(..)
1224 | DefKind::Static { nested: true, .. }
1225 | DefKind::Use
1226 | DefKind::LifetimeParam
1227 | DefKind::GlobalAsm
1228 | DefKind::ExternCrate => false,
1229 }
1230}
1231
1232fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1233 match def_kind {
1234 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1235
1236 DefKind::Struct
1237 | DefKind::Union
1238 | DefKind::Enum
1239 | DefKind::Variant
1240 | DefKind::Field
1241 | DefKind::Const
1242 | DefKind::Static { .. }
1243 | DefKind::Ctor(..)
1244 | DefKind::TyAlias
1245 | DefKind::OpaqueTy
1246 | DefKind::ForeignTy
1247 | DefKind::Impl { .. }
1248 | DefKind::AssocConst
1249 | DefKind::Closure
1250 | DefKind::ConstParam
1251 | DefKind::AnonConst
1252 | DefKind::InlineConst
1253 | DefKind::AssocTy
1254 | DefKind::TyParam
1255 | DefKind::Trait
1256 | DefKind::TraitAlias
1257 | DefKind::Mod
1258 | DefKind::ForeignMod
1259 | DefKind::Macro(..)
1260 | DefKind::Use
1261 | DefKind::LifetimeParam
1262 | DefKind::GlobalAsm
1263 | DefKind::ExternCrate
1264 | DefKind::SyntheticCoroutineBody => false,
1265 }
1266}
1267
1268fn should_encode_constness(def_kind: DefKind) -> bool {
1269 match def_kind {
1270 DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Ctor(_, CtorKind::Fn) => true,
1271
1272 DefKind::Struct
1273 | DefKind::Union
1274 | DefKind::Enum
1275 | DefKind::Field
1276 | DefKind::Const
1277 | DefKind::AssocConst
1278 | DefKind::AnonConst
1279 | DefKind::Static { .. }
1280 | DefKind::TyAlias
1281 | DefKind::OpaqueTy
1282 | DefKind::Impl { .. }
1283 | DefKind::ForeignTy
1284 | DefKind::ConstParam
1285 | DefKind::InlineConst
1286 | DefKind::AssocTy
1287 | DefKind::TyParam
1288 | DefKind::Trait
1289 | DefKind::TraitAlias
1290 | DefKind::Mod
1291 | DefKind::ForeignMod
1292 | DefKind::Macro(..)
1293 | DefKind::Use
1294 | DefKind::LifetimeParam
1295 | DefKind::GlobalAsm
1296 | DefKind::ExternCrate
1297 | DefKind::Ctor(_, CtorKind::Const)
1298 | DefKind::Variant
1299 | DefKind::SyntheticCoroutineBody => false,
1300 }
1301}
1302
1303fn should_encode_const(def_kind: DefKind) -> bool {
1304 match def_kind {
1305 DefKind::Const | DefKind::AssocConst | DefKind::AnonConst | DefKind::InlineConst => true,
1306
1307 DefKind::Struct
1308 | DefKind::Union
1309 | DefKind::Enum
1310 | DefKind::Variant
1311 | DefKind::Ctor(..)
1312 | DefKind::Field
1313 | DefKind::Fn
1314 | DefKind::Static { .. }
1315 | DefKind::TyAlias
1316 | DefKind::OpaqueTy
1317 | DefKind::ForeignTy
1318 | DefKind::Impl { .. }
1319 | DefKind::AssocFn
1320 | DefKind::Closure
1321 | DefKind::ConstParam
1322 | DefKind::AssocTy
1323 | DefKind::TyParam
1324 | DefKind::Trait
1325 | DefKind::TraitAlias
1326 | DefKind::Mod
1327 | DefKind::ForeignMod
1328 | DefKind::Macro(..)
1329 | DefKind::Use
1330 | DefKind::LifetimeParam
1331 | DefKind::GlobalAsm
1332 | DefKind::ExternCrate
1333 | DefKind::SyntheticCoroutineBody => false,
1334 }
1335}
1336
1337fn should_encode_fn_impl_trait_in_trait<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1338 if let Some(assoc_item) = tcx.opt_associated_item(def_id)
1339 && assoc_item.container == ty::AssocItemContainer::Trait
1340 && assoc_item.kind == ty::AssocKind::Fn
1341 {
1342 true
1343 } else {
1344 false
1345 }
1346}
1347
1348impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1349 fn encode_attrs(&mut self, def_id: LocalDefId) {
1350 let tcx = self.tcx;
1351 let mut state = AnalyzeAttrState {
1352 is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1353 is_doc_hidden: false,
1354 features: &tcx.features(),
1355 };
1356 let attr_iter = tcx
1357 .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
1358 .iter()
1359 .filter(|attr| analyze_attr(*attr, &mut state));
1360
1361 record_array!(self.tables.attributes[def_id.to_def_id()] <- attr_iter);
1362
1363 let mut attr_flags = AttrFlags::empty();
1364 if state.is_doc_hidden {
1365 attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1366 }
1367 self.tables.attr_flags.set(def_id.local_def_index, attr_flags);
1368 }
1369
1370 fn encode_def_ids(&mut self) {
1371 self.encode_info_for_mod(CRATE_DEF_ID);
1372
1373 if self.is_proc_macro {
1376 return;
1377 }
1378
1379 let tcx = self.tcx;
1380
1381 for local_id in tcx.iter_local_def_id() {
1382 let def_id = local_id.to_def_id();
1383 let def_kind = tcx.def_kind(local_id);
1384 self.tables.def_kind.set_some(def_id.index, def_kind);
1385
1386 if def_kind == DefKind::AnonConst
1391 && match tcx.hir_node_by_def_id(local_id) {
1392 hir::Node::ConstArg(hir::ConstArg { kind, .. }) => match kind {
1393 hir::ConstArgKind::Path(..) | hir::ConstArgKind::Infer(..) => true,
1395 hir::ConstArgKind::Anon(..) => false,
1396 },
1397 _ => false,
1398 }
1399 {
1400 continue;
1401 }
1402
1403 if def_kind == DefKind::Field
1404 && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1405 && let Some(anon) = field.default
1406 {
1407 record!(self.tables.default_fields[def_id] <- anon.def_id.to_def_id());
1408 }
1409
1410 if should_encode_span(def_kind) {
1411 let def_span = tcx.def_span(local_id);
1412 record!(self.tables.def_span[def_id] <- def_span);
1413 }
1414 if should_encode_attrs(def_kind) {
1415 self.encode_attrs(local_id);
1416 }
1417 if should_encode_expn_that_defined(def_kind) {
1418 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1419 }
1420 if should_encode_span(def_kind)
1421 && let Some(ident_span) = tcx.def_ident_span(def_id)
1422 {
1423 record!(self.tables.def_ident_span[def_id] <- ident_span);
1424 }
1425 if def_kind.has_codegen_attrs() {
1426 record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1427 }
1428 if should_encode_visibility(def_kind) {
1429 let vis =
1430 self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);
1431 record!(self.tables.visibility[def_id] <- vis);
1432 }
1433 if should_encode_stability(def_kind) {
1434 self.encode_stability(def_id);
1435 self.encode_const_stability(def_id);
1436 self.encode_default_body_stability(def_id);
1437 self.encode_deprecation(def_id);
1438 }
1439 if should_encode_variances(tcx, def_id, def_kind) {
1440 let v = self.tcx.variances_of(def_id);
1441 record_array!(self.tables.variances_of[def_id] <- v);
1442 }
1443 if should_encode_fn_sig(def_kind) {
1444 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1445 }
1446 if should_encode_generics(def_kind) {
1447 let g = tcx.generics_of(def_id);
1448 record!(self.tables.generics_of[def_id] <- g);
1449 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1450 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1451 record_defaulted_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1452
1453 for param in &g.own_params {
1454 if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1455 let default = self.tcx.const_param_default(param.def_id);
1456 record!(self.tables.const_param_default[param.def_id] <- default);
1457 }
1458 }
1459 }
1460 if tcx.is_conditionally_const(def_id) {
1461 record!(self.tables.const_conditions[def_id] <- self.tcx.const_conditions(def_id));
1462 }
1463 if should_encode_type(tcx, local_id, def_kind) {
1464 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1465 }
1466 if should_encode_constness(def_kind) {
1467 self.tables.constness.set_some(def_id.index, self.tcx.constness(def_id));
1468 }
1469 if let DefKind::Fn | DefKind::AssocFn = def_kind {
1470 self.tables.asyncness.set_some(def_id.index, tcx.asyncness(def_id));
1471 record_array!(self.tables.fn_arg_names[def_id] <- tcx.fn_arg_names(def_id));
1472 }
1473 if let Some(name) = tcx.intrinsic(def_id) {
1474 record!(self.tables.intrinsic[def_id] <- name);
1475 }
1476 if let DefKind::TyParam = def_kind {
1477 let default = self.tcx.object_lifetime_default(def_id);
1478 record!(self.tables.object_lifetime_default[def_id] <- default);
1479 }
1480 if let DefKind::Trait = def_kind {
1481 record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1482 record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1483 self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1484 record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1485 self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1486 let module_children = self.tcx.module_children_local(local_id);
1487 record_array!(self.tables.module_children_non_reexports[def_id] <-
1488 module_children.iter().map(|child| child.res.def_id().index));
1489 if self.tcx.is_const_trait(def_id) {
1490 record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1491 <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1492 }
1493 }
1494 if let DefKind::TraitAlias = def_kind {
1495 record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1496 record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1497 self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1498 record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1499 self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1500 }
1501 if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1502 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1503 record_array!(self.tables.associated_item_or_field_def_ids[def_id] <-
1504 associated_item_def_ids.iter().map(|&def_id| {
1505 assert!(def_id.is_local());
1506 def_id.index
1507 })
1508 );
1509 for &def_id in associated_item_def_ids {
1510 self.encode_info_for_assoc_item(def_id);
1511 }
1512 }
1513 if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1514 && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id)
1515 {
1516 self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind))
1517 }
1518 if def_kind == DefKind::Closure
1519 && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1520 {
1521 let coroutine_for_closure = self.tcx.coroutine_for_closure(def_id);
1522 self.tables
1523 .coroutine_for_closure
1524 .set_some(def_id.index, coroutine_for_closure.into());
1525
1526 if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1528 self.tables.coroutine_by_move_body_def_id.set_some(
1529 coroutine_for_closure.index,
1530 self.tcx.coroutine_by_move_body_def_id(coroutine_for_closure).into(),
1531 );
1532 }
1533 }
1534 if let DefKind::Static { .. } = def_kind {
1535 if !self.tcx.is_foreign_item(def_id) {
1536 let data = self.tcx.eval_static_initializer(def_id).unwrap();
1537 record!(self.tables.eval_static_initializer[def_id] <- data);
1538 }
1539 }
1540 if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1541 self.encode_info_for_adt(local_id);
1542 }
1543 if let DefKind::Mod = def_kind {
1544 self.encode_info_for_mod(local_id);
1545 }
1546 if let DefKind::Macro(_) = def_kind {
1547 self.encode_info_for_macro(local_id);
1548 }
1549 if let DefKind::TyAlias = def_kind {
1550 self.tables
1551 .type_alias_is_lazy
1552 .set(def_id.index, self.tcx.type_alias_is_lazy(def_id));
1553 }
1554 if let DefKind::OpaqueTy = def_kind {
1555 self.encode_explicit_item_bounds(def_id);
1556 self.encode_explicit_item_self_bounds(def_id);
1557 record!(self.tables.opaque_ty_origin[def_id] <- self.tcx.opaque_ty_origin(def_id));
1558 self.encode_precise_capturing_args(def_id);
1559 if tcx.is_conditionally_const(def_id) {
1560 record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1561 <- tcx.explicit_implied_const_bounds(def_id).skip_binder());
1562 }
1563 }
1564 if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1565 && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1566 {
1567 record!(self.tables.trait_impl_trait_tys[def_id] <- table);
1568 }
1569 if should_encode_fn_impl_trait_in_trait(tcx, def_id) {
1570 let table = tcx.associated_types_for_impl_traits_in_associated_fn(def_id);
1571 record_defaulted_array!(self.tables.associated_types_for_impl_traits_in_associated_fn[def_id] <- table);
1572 }
1573 }
1574
1575 for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1576 record_defaulted_array!(self.tables.inherent_impls[def_id.to_def_id()] <- impls.iter().map(|def_id| {
1577 assert!(def_id.is_local());
1578 def_id.index
1579 }));
1580 }
1581
1582 for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1583 record!(self.tables.doc_link_resolutions[def_id.to_def_id()] <- res_map);
1584 }
1585
1586 for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1587 record_array!(self.tables.doc_link_traits_in_scope[def_id.to_def_id()] <- traits);
1588 }
1589 }
1590
1591 #[instrument(level = "trace", skip(self))]
1592 fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1593 let def_id = local_def_id.to_def_id();
1594 let tcx = self.tcx;
1595 let adt_def = tcx.adt_def(def_id);
1596 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1597
1598 let params_in_repr = self.tcx.params_in_repr(def_id);
1599 record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1600
1601 if adt_def.is_enum() {
1602 let module_children = tcx.module_children_local(local_def_id);
1603 record_array!(self.tables.module_children_non_reexports[def_id] <-
1604 module_children.iter().map(|child| child.res.def_id().index));
1605 } else {
1606 debug_assert_eq!(adt_def.variants().len(), 1);
1608 debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1609 }
1611
1612 for (idx, variant) in adt_def.variants().iter_enumerated() {
1613 let data = VariantData {
1614 discr: variant.discr,
1615 idx,
1616 ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1617 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1618 };
1619 record!(self.tables.variant_data[variant.def_id] <- data);
1620
1621 record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| {
1622 assert!(f.did.is_local());
1623 f.did.index
1624 }));
1625
1626 for field in &variant.fields {
1627 self.tables.safety.set_some(field.did.index, field.safety);
1628 }
1629
1630 if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1631 let fn_sig = tcx.fn_sig(ctor_def_id);
1632 record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
1634 }
1635 }
1636 }
1637
1638 #[instrument(level = "debug", skip(self))]
1639 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1640 let tcx = self.tcx;
1641 let def_id = local_def_id.to_def_id();
1642
1643 if self.is_proc_macro {
1649 record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1651 } else {
1652 let module_children = tcx.module_children_local(local_def_id);
1653
1654 record_array!(self.tables.module_children_non_reexports[def_id] <-
1655 module_children.iter().filter(|child| child.reexport_chain.is_empty())
1656 .map(|child| child.res.def_id().index));
1657
1658 record_defaulted_array!(self.tables.module_children_reexports[def_id] <-
1659 module_children.iter().filter(|child| !child.reexport_chain.is_empty()));
1660 }
1661 }
1662
1663 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1664 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1665 let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1666 record_defaulted_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1667 }
1668
1669 fn encode_explicit_item_self_bounds(&mut self, def_id: DefId) {
1670 debug!("EncodeContext::encode_explicit_item_self_bounds({:?})", def_id);
1671 let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1672 record_defaulted_array!(self.tables.explicit_item_self_bounds[def_id] <- bounds);
1673 }
1674
1675 #[instrument(level = "debug", skip(self))]
1676 fn encode_info_for_assoc_item(&mut self, def_id: DefId) {
1677 let tcx = self.tcx;
1678 let item = tcx.associated_item(def_id);
1679
1680 self.tables.defaultness.set_some(def_id.index, item.defaultness(tcx));
1681 self.tables.assoc_container.set_some(def_id.index, item.container);
1682
1683 match item.container {
1684 AssocItemContainer::Trait => {
1685 if let ty::AssocKind::Type = item.kind {
1686 self.encode_explicit_item_bounds(def_id);
1687 self.encode_explicit_item_self_bounds(def_id);
1688 if tcx.is_conditionally_const(def_id) {
1689 record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1690 <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1691 }
1692 }
1693 }
1694 AssocItemContainer::Impl => {
1695 if let Some(trait_item_def_id) = item.trait_item_def_id {
1696 self.tables.trait_item_def_id.set_some(def_id.index, trait_item_def_id.into());
1697 }
1698 }
1699 }
1700 if let Some(rpitit_info) = item.opt_rpitit_info {
1701 record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info);
1702 if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1703 record_array!(
1704 self.tables.assumed_wf_types_for_rpitit[def_id]
1705 <- self.tcx.assumed_wf_types_for_rpitit(def_id)
1706 );
1707 self.encode_precise_capturing_args(def_id);
1708 }
1709 }
1710 }
1711
1712 fn encode_precise_capturing_args(&mut self, def_id: DefId) {
1713 let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1714 return;
1715 };
1716
1717 record_array!(self.tables.rendered_precise_capturing_args[def_id] <- precise_capturing_args);
1718 }
1719
1720 fn encode_mir(&mut self) {
1721 if self.is_proc_macro {
1722 return;
1723 }
1724
1725 let tcx = self.tcx;
1726 let reachable_set = tcx.reachable_set(());
1727
1728 let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1729 let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1730 if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1731 });
1732 for (def_id, encode_const, encode_opt) in keys_and_jobs {
1733 debug_assert!(encode_const || encode_opt);
1734
1735 debug!("EntryBuilder::encode_mir({:?})", def_id);
1736 if encode_opt {
1737 record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1738 self.tables
1739 .cross_crate_inlinable
1740 .set(def_id.to_def_id().index, self.tcx.cross_crate_inlinable(def_id));
1741 record!(self.tables.closure_saved_names_of_captured_variables[def_id.to_def_id()]
1742 <- tcx.closure_saved_names_of_captured_variables(def_id));
1743
1744 if self.tcx.is_coroutine(def_id.to_def_id())
1745 && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1746 {
1747 record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1748 }
1749 }
1750 if encode_const {
1751 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1752
1753 let abstract_const = tcx.thir_abstract_const(def_id);
1755 if let Ok(Some(abstract_const)) = abstract_const {
1756 record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1757 }
1758
1759 if should_encode_const(tcx.def_kind(def_id)) {
1760 let qualifs = tcx.mir_const_qualif(def_id);
1761 record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1762 let body = tcx.hir_maybe_body_owned_by(def_id);
1763 if let Some(body) = body {
1764 let const_data = rendered_const(self.tcx, &body, def_id);
1765 record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1766 }
1767 }
1768 }
1769 record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1770
1771 if self.tcx.is_coroutine(def_id.to_def_id())
1772 && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1773 {
1774 record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1775 }
1776 }
1777
1778 if tcx.sess.opts.output_types.should_codegen()
1782 && tcx.sess.opts.optimize != OptLevel::No
1783 && tcx.sess.opts.incremental.is_none()
1784 {
1785 for &local_def_id in tcx.mir_keys(()) {
1786 if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1787 record_array!(self.tables.deduced_param_attrs[local_def_id.to_def_id()] <-
1788 self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1789 }
1790 }
1791 }
1792 }
1793
1794 #[instrument(level = "debug", skip(self))]
1795 fn encode_stability(&mut self, def_id: DefId) {
1796 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1799 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1800 record!(self.tables.lookup_stability[def_id] <- stab)
1801 }
1802 }
1803 }
1804
1805 #[instrument(level = "debug", skip(self))]
1806 fn encode_const_stability(&mut self, def_id: DefId) {
1807 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1810 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1811 record!(self.tables.lookup_const_stability[def_id] <- stab)
1812 }
1813 }
1814 }
1815
1816 #[instrument(level = "debug", skip(self))]
1817 fn encode_default_body_stability(&mut self, def_id: DefId) {
1818 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1821 if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1822 record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1823 }
1824 }
1825 }
1826
1827 #[instrument(level = "debug", skip(self))]
1828 fn encode_deprecation(&mut self, def_id: DefId) {
1829 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1830 record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1831 }
1832 }
1833
1834 #[instrument(level = "debug", skip(self))]
1835 fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
1836 let tcx = self.tcx;
1837
1838 let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
1839 self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
1840 record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
1841 }
1842
1843 fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1844 empty_proc_macro!(self);
1845 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1846 self.lazy_array(used_libraries.iter())
1847 }
1848
1849 fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1850 empty_proc_macro!(self);
1851 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1852 self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1853 }
1854
1855 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1856 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1857 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1858 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1859
1860 self.hygiene_ctxt.encode(
1861 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1862 |(this, syntax_contexts, _, _), index, ctxt_data| {
1863 syntax_contexts.set_some(index, this.lazy(ctxt_data));
1864 },
1865 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1866 if let Some(index) = index.as_local() {
1867 expn_data_table.set_some(index.as_raw(), this.lazy(expn_data));
1868 expn_hash_table.set_some(index.as_raw(), this.lazy(hash));
1869 }
1870 },
1871 );
1872
1873 (
1874 syntax_contexts.encode(&mut self.opaque),
1875 expn_data_table.encode(&mut self.opaque),
1876 expn_hash_table.encode(&mut self.opaque),
1877 )
1878 }
1879
1880 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1881 let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
1882 if is_proc_macro {
1883 let tcx = self.tcx;
1884 let hir = tcx.hir();
1885
1886 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1887 let stability = tcx.lookup_stability(CRATE_DEF_ID);
1888 let macros =
1889 self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1890 for (i, span) in self.tcx.sess.psess.proc_macro_quoted_spans() {
1891 let span = self.lazy(span);
1892 self.tables.proc_macro_quoted_spans.set_some(i, span);
1893 }
1894
1895 self.tables.def_kind.set_some(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1896 record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1897 self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1898 let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|def_id| def_id.local_def_index);
1899 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
1900 if let Some(stability) = stability {
1901 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1902 }
1903 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1904 if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_DEF_ID) {
1905 record!(self.tables.doc_link_resolutions[LOCAL_CRATE.as_def_id()] <- res_map);
1906 }
1907 if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_DEF_ID) {
1908 record_array!(self.tables.doc_link_traits_in_scope[LOCAL_CRATE.as_def_id()] <- traits);
1909 }
1910
1911 for &proc_macro in &tcx.resolutions(()).proc_macros {
1915 let id = proc_macro;
1916 let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
1917 let mut name = tcx.hir_name(proc_macro);
1918 let span = hir.span(proc_macro);
1919 let attrs = tcx.hir_attrs(proc_macro);
1922 let macro_kind = if ast::attr::contains_name(attrs, sym::proc_macro) {
1923 MacroKind::Bang
1924 } else if ast::attr::contains_name(attrs, sym::proc_macro_attribute) {
1925 MacroKind::Attr
1926 } else if let Some(attr) = ast::attr::find_by_name(attrs, sym::proc_macro_derive) {
1927 name = attr.meta_item_list().unwrap()[0]
1929 .meta_item()
1930 .unwrap()
1931 .ident()
1932 .unwrap()
1933 .name;
1934 MacroKind::Derive
1935 } else {
1936 bug!("Unknown proc-macro type for item {:?}", id);
1937 };
1938
1939 let mut def_key = self.tcx.hir_def_key(id);
1940 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1941
1942 let def_id = id.to_def_id();
1943 self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind));
1944 self.tables.proc_macro.set_some(def_id.index, macro_kind);
1945 self.encode_attrs(id);
1946 record!(self.tables.def_keys[def_id] <- def_key);
1947 record!(self.tables.def_ident_span[def_id] <- span);
1948 record!(self.tables.def_span[def_id] <- span);
1949 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1950 if let Some(stability) = stability {
1951 record!(self.tables.lookup_stability[def_id] <- stability);
1952 }
1953 }
1954
1955 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1956 } else {
1957 None
1958 }
1959 }
1960
1961 fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1962 empty_proc_macro!(self);
1963 self.lazy_array(
1964 self.tcx
1965 .debugger_visualizers(LOCAL_CRATE)
1966 .iter()
1967 .map(DebuggerVisualizerFile::path_erased),
1972 )
1973 }
1974
1975 fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1976 empty_proc_macro!(self);
1977
1978 let deps = self
1979 .tcx
1980 .crates(())
1981 .iter()
1982 .map(|&cnum| {
1983 let dep = CrateDep {
1984 name: self.tcx.crate_name(cnum),
1985 hash: self.tcx.crate_hash(cnum),
1986 host_hash: self.tcx.crate_host_hash(cnum),
1987 kind: self.tcx.dep_kind(cnum),
1988 extra_filename: self.tcx.extra_filename(cnum).clone(),
1989 is_private: self.tcx.is_private_dep(cnum),
1990 };
1991 (cnum, dep)
1992 })
1993 .collect::<Vec<_>>();
1994
1995 {
1996 let mut expected_cnum = 1;
1998 for &(n, _) in &deps {
1999 assert_eq!(n, CrateNum::new(expected_cnum));
2000 expected_cnum += 1;
2001 }
2002 }
2003
2004 self.lazy_array(deps.iter().map(|(_, dep)| dep))
2009 }
2010
2011 fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2012 empty_proc_macro!(self);
2013 let tcx = self.tcx;
2014 self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2015 }
2016
2017 fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2018 empty_proc_macro!(self);
2019 let tcx = self.tcx;
2020 let lib_features = tcx.lib_features(LOCAL_CRATE);
2021 self.lazy_array(lib_features.to_sorted_vec())
2022 }
2023
2024 fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2025 empty_proc_macro!(self);
2026 let tcx = self.tcx;
2027 let implications = tcx.stability_implications(LOCAL_CRATE);
2028 let sorted = implications.to_sorted_stable_ord();
2029 self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2030 }
2031
2032 fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2033 empty_proc_macro!(self);
2034 let tcx = self.tcx;
2035 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2036 self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
2037 }
2038
2039 fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
2040 empty_proc_macro!(self);
2041 let lang_items = self.tcx.lang_items().iter();
2042 self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
2043 def_id.as_local().map(|id| (id.local_def_index, lang_item))
2044 }))
2045 }
2046
2047 fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2048 empty_proc_macro!(self);
2049 let tcx = self.tcx;
2050 self.lazy_array(&tcx.lang_items().missing)
2051 }
2052
2053 fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<DefIndex>> {
2054 self.lazy_array(
2055 self.tcx
2056 .stripped_cfg_items(LOCAL_CRATE)
2057 .into_iter()
2058 .map(|item| item.clone().map_mod_id(|def_id| def_id.index)),
2059 )
2060 }
2061
2062 fn encode_traits(&mut self) -> LazyArray<DefIndex> {
2063 empty_proc_macro!(self);
2064 self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2065 }
2066
2067 #[instrument(level = "debug", skip(self))]
2069 fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2070 empty_proc_macro!(self);
2071 let tcx = self.tcx;
2072 let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
2073 FxIndexMap::default();
2074
2075 for id in tcx.hir_free_items() {
2076 let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2077 continue;
2078 };
2079 let def_id = id.owner_id.to_def_id();
2080
2081 self.tables.defaultness.set_some(def_id.index, tcx.defaultness(def_id));
2082
2083 if of_trait && let Some(header) = tcx.impl_trait_header(def_id) {
2084 record!(self.tables.impl_trait_header[def_id] <- header);
2085
2086 let trait_ref = header.trait_ref.instantiate_identity();
2087 let simplified_self_ty = fast_reject::simplify_type(
2088 self.tcx,
2089 trait_ref.self_ty(),
2090 TreatParams::InstantiateWithInfer,
2091 );
2092 trait_impls
2093 .entry(trait_ref.def_id)
2094 .or_default()
2095 .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
2096
2097 let trait_def = tcx.trait_def(trait_ref.def_id);
2098 if let Ok(mut an) = trait_def.ancestors(tcx, def_id) {
2099 if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
2100 self.tables.impl_parent.set_some(def_id.index, parent.into());
2101 }
2102 }
2103
2104 if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2107 let coerce_unsized_info = tcx.coerce_unsized_info(def_id).unwrap();
2108 record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
2109 }
2110 }
2111 }
2112
2113 let trait_impls: Vec<_> = trait_impls
2114 .into_iter()
2115 .map(|(trait_def_id, impls)| TraitImpls {
2116 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
2117 impls: self.lazy_array(&impls),
2118 })
2119 .collect();
2120
2121 self.lazy_array(&trait_impls)
2122 }
2123
2124 #[instrument(level = "debug", skip(self))]
2125 fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2126 empty_proc_macro!(self);
2127 let tcx = self.tcx;
2128
2129 let all_impls: Vec<_> = tcx
2130 .crate_inherent_impls(())
2131 .0
2132 .incoherent_impls
2133 .iter()
2134 .map(|(&simp, impls)| IncoherentImpls {
2135 self_ty: simp,
2136 impls: self.lazy_array(impls.iter().map(|def_id| def_id.local_def_index)),
2137 })
2138 .collect();
2139
2140 self.lazy_array(&all_impls)
2141 }
2142
2143 fn encode_exported_symbols(
2150 &mut self,
2151 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2152 ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2153 empty_proc_macro!(self);
2154 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
2157
2158 self.lazy_array(
2159 exported_symbols
2160 .iter()
2161 .filter(|&(exported_symbol, _)| match *exported_symbol {
2162 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
2163 _ => true,
2164 })
2165 .cloned(),
2166 )
2167 }
2168
2169 fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2170 empty_proc_macro!(self);
2171 let formats = self.tcx.dependency_formats(());
2172 if let Some(arr) = formats.get(&CrateType::Dylib) {
2173 return self.lazy_array(arr.iter().skip(1 ).map(
2174 |slot| match *slot {
2175 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2176
2177 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2178 Linkage::Static => Some(LinkagePreference::RequireStatic),
2179 },
2180 ));
2181 }
2182 LazyArray::default()
2183 }
2184}
2185
2186fn prefetch_mir(tcx: TyCtxt<'_>) {
2189 if !tcx.sess.opts.output_types.should_codegen() {
2190 return;
2192 }
2193
2194 let reachable_set = tcx.reachable_set(());
2195 par_for_each_in(tcx.mir_keys(()), |&def_id| {
2196 let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2197
2198 if encode_const {
2199 tcx.ensure_done().mir_for_ctfe(def_id);
2200 }
2201 if encode_opt {
2202 tcx.ensure_done().optimized_mir(def_id);
2203 }
2204 if encode_opt || encode_const {
2205 tcx.ensure_done().promoted_mir(def_id);
2206 }
2207 })
2208}
2209
2210pub struct EncodedMetadata {
2234 mmap: Option<Mmap>,
2236 _temp_dir: Option<MaybeTempDir>,
2239}
2240
2241impl EncodedMetadata {
2242 #[inline]
2243 pub fn from_path(path: PathBuf, temp_dir: Option<MaybeTempDir>) -> std::io::Result<Self> {
2244 let file = std::fs::File::open(&path)?;
2245 let file_metadata = file.metadata()?;
2246 if file_metadata.len() == 0 {
2247 return Ok(Self { mmap: None, _temp_dir: None });
2248 }
2249 let mmap = unsafe { Some(Mmap::map(file)?) };
2250 Ok(Self { mmap, _temp_dir: temp_dir })
2251 }
2252
2253 #[inline]
2254 pub fn raw_data(&self) -> &[u8] {
2255 self.mmap.as_deref().unwrap_or_default()
2256 }
2257}
2258
2259impl<S: Encoder> Encodable<S> for EncodedMetadata {
2260 fn encode(&self, s: &mut S) {
2261 let slice = self.raw_data();
2262 slice.encode(s)
2263 }
2264}
2265
2266impl<D: Decoder> Decodable<D> for EncodedMetadata {
2267 fn decode(d: &mut D) -> Self {
2268 let len = d.read_usize();
2269 let mmap = if len > 0 {
2270 let mut mmap = MmapMut::map_anon(len).unwrap();
2271 mmap.copy_from_slice(d.read_raw_bytes(len));
2272 Some(mmap.make_read_only().unwrap())
2273 } else {
2274 None
2275 };
2276
2277 Self { mmap, _temp_dir: None }
2278 }
2279}
2280
2281pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path) {
2282 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2283
2284 tcx.dep_graph.assert_ignored();
2287
2288 if tcx.sess.threads() != 1 {
2289 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2293 }
2294
2295 let mut encoder = opaque::FileEncoder::new(path)
2296 .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2297 encoder.emit_raw_bytes(METADATA_HEADER);
2298
2299 encoder.emit_raw_bytes(&0u64.to_le_bytes());
2301
2302 let source_map_files = tcx.sess.source_map().files();
2303 let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2304 let required_source_files = Some(FxIndexSet::default());
2305 drop(source_map_files);
2306
2307 let hygiene_ctxt = HygieneEncodeContext::default();
2308
2309 let mut ecx = EncodeContext {
2310 opaque: encoder,
2311 tcx,
2312 feat: tcx.features(),
2313 tables: Default::default(),
2314 lazy_state: LazyState::NoNode,
2315 span_shorthands: Default::default(),
2316 type_shorthands: Default::default(),
2317 predicate_shorthands: Default::default(),
2318 source_file_cache,
2319 interpret_allocs: Default::default(),
2320 required_source_files,
2321 is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2322 hygiene_ctxt: &hygiene_ctxt,
2323 symbol_table: Default::default(),
2324 };
2325
2326 rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2328
2329 let root = ecx.encode_crate_root();
2332
2333 if let Err((path, err)) = ecx.opaque.finish() {
2337 tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2338 }
2339
2340 let file = ecx.opaque.file();
2341 if let Err(err) = encode_root_position(file, root.position.get()) {
2342 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2343 }
2344
2345 tcx.prof.artifact_size("crate_metadata", "crate_metadata", file.metadata().unwrap().len());
2347}
2348
2349fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2350 let pos_before_seek = file.stream_position().unwrap();
2352
2353 let header = METADATA_HEADER.len();
2355 file.seek(std::io::SeekFrom::Start(header as u64))?;
2356 file.write_all(&pos.to_le_bytes())?;
2357
2358 file.seek(std::io::SeekFrom::Start(pos_before_seek))?;
2360 Ok(())
2361}
2362
2363pub(crate) fn provide(providers: &mut Providers) {
2364 *providers = Providers {
2365 doc_link_resolutions: |tcx, def_id| {
2366 tcx.resolutions(())
2367 .doc_link_resolutions
2368 .get(&def_id)
2369 .unwrap_or_else(|| span_bug!(tcx.def_span(def_id), "no resolutions for a doc link"))
2370 },
2371 doc_link_traits_in_scope: |tcx, def_id| {
2372 tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2373 span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link")
2374 })
2375 },
2376
2377 ..*providers
2378 }
2379}
2380
2381pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2409 let value = body.value;
2410
2411 #[derive(PartialEq, Eq)]
2412 enum Classification {
2413 Literal,
2414 Simple,
2415 Complex,
2416 }
2417
2418 use Classification::*;
2419
2420 fn classify(expr: &hir::Expr<'_>) -> Classification {
2421 match &expr.kind {
2422 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2423 if matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2424 }
2425 hir::ExprKind::Lit(_) => Literal,
2426 hir::ExprKind::Tup([]) => Simple,
2427 hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2428 if classify(expr) == Complex { Complex } else { Simple }
2429 }
2430 hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2435 if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2436 }
2437 hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2440 hir::ExprKind::Path(hir::QPath::LangItem(..)) => Simple,
2442 _ => Complex,
2443 }
2444 }
2445
2446 match classify(value) {
2447 Literal
2457 if !value.span.from_expansion()
2458 && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2459 {
2460 snippet
2461 }
2462
2463 Literal | Simple => id_to_string(&tcx, body.id().hir_id),
2466
2467 Complex => {
2471 if tcx.def_kind(def_id) == DefKind::AnonConst {
2472 "{ _ }".to_owned()
2473 } else {
2474 "_".to_owned()
2475 }
2476 }
2477 }
2478}