1 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
2 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
5 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
6 use rustc_data_structures::stable_hasher::StableHasher;
7 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
9 use rustc_hir::def::{CtorOf, DefKind};
10 use rustc_hir::def_id::{
11 CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
13 use rustc_hir::definitions::DefPathData;
14 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
15 use rustc_hir::itemlikevisit::ItemLikeVisitor;
16 use rustc_hir::lang_items;
17 use rustc_hir::{AnonConst, GenericParamKind};
18 use rustc_index::bit_set::GrowableBitSet;
19 use rustc_index::vec::Idx;
20 use rustc_middle::hir::map::Map;
21 use rustc_middle::middle::dependency_format::Linkage;
22 use rustc_middle::middle::exported_symbols::{
23 metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
25 use rustc_middle::mir::interpret;
26 use rustc_middle::thir;
27 use rustc_middle::traits::specialization_graph;
28 use rustc_middle::ty::codec::TyEncoder;
29 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
30 use rustc_serialize::{opaque, Encodable, Encoder};
31 use rustc_session::config::CrateType;
32 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
33 use rustc_span::symbol::{sym, Ident, Symbol};
34 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
36 hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind},
39 use rustc_target::abi::VariantIdx;
41 use std::num::NonZeroUsize;
43 use tracing::{debug, trace};
45 pub(super) struct EncodeContext<'a, 'tcx> {
46 opaque: opaque::Encoder,
48 feat: &'tcx rustc_feature::Features,
50 tables: TableBuilders<'tcx>,
52 lazy_state: LazyState,
53 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
54 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
56 interpret_allocs: FxIndexSet<interpret::AllocId>,
58 // This is used to speed up Span encoding.
59 // The `usize` is an index into the `MonotonicVec`
60 // that stores the `SourceFile`
61 source_file_cache: (Lrc<SourceFile>, usize),
62 // The indices (into the `SourceMap`'s `MonotonicVec`)
63 // of all of the `SourceFiles` that we need to serialize.
64 // When we serialize a `Span`, we insert the index of its
65 // `SourceFile` into the `GrowableBitSet`.
67 // This needs to be a `GrowableBitSet` and not a
68 // regular `BitSet` because we may actually import new `SourceFiles`
69 // during metadata encoding, due to executing a query
70 // with a result containing a foreign `Span`.
71 required_source_files: Option<GrowableBitSet<usize>>,
73 hygiene_ctxt: &'a HygieneEncodeContext,
76 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
77 /// This is useful for skipping the encoding of things that aren't needed
78 /// for proc-macro crates.
79 macro_rules! empty_proc_macro {
81 if $self.is_proc_macro {
87 macro_rules! encoder_methods {
88 ($($name:ident($ty:ty);)*) => {
89 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
90 self.opaque.$name(value)
95 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
96 type Error = <opaque::Encoder as Encoder>::Error;
99 fn emit_unit(&mut self) -> Result<(), Self::Error> {
123 emit_raw_bytes(&[u8]);
127 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
130 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
131 e.emit_lazy_distance(*self)
135 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
138 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
139 e.emit_usize(self.meta)?;
143 e.emit_lazy_distance(*self)
147 impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
148 for Lazy<Table<I, T>>
150 Option<T>: FixedSizeEncoding,
152 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
153 e.emit_usize(self.meta)?;
154 e.emit_lazy_distance(*self)
158 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
159 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
160 if *self != LOCAL_CRATE && s.is_proc_macro {
161 panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
163 s.emit_u32(self.as_u32())
167 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
168 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
169 s.emit_u32(self.as_u32())
173 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
174 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
175 s.emit_u32(self.as_u32())
179 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
180 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
181 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
185 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
186 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
187 if self.krate == LOCAL_CRATE {
188 // We will only write details for local expansions. Non-local expansions will fetch
189 // data from the corresponding crate's metadata.
190 // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
191 // metadata from proc-macro crates.
192 s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
194 self.krate.encode(s)?;
195 self.local_id.encode(s)
199 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
200 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
201 let span = self.data();
203 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
204 // since we don't load proc-macro dependencies during serialization.
205 // This means that any hygiene information from macros used *within*
206 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
207 // definition) will be lost.
209 // This can show up in two ways:
211 // 1. Any hygiene information associated with identifier of
212 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
213 // Since proc-macros can only be invoked from a different crate,
214 // real code should never need to care about this.
216 // 2. Using `Span::def_site` or `Span::mixed_site` will not
217 // include any hygiene information associated with the definition
218 // site. This means that a proc-macro cannot emit a `$crate`
219 // identifier which resolves to one of its dependencies,
220 // which also should never come up in practice.
222 // Additionally, this affects `Span::parent`, and any other
223 // span inspection APIs that would otherwise allow traversing
224 // the `SyntaxContexts` associated with a span.
226 // None of these user-visible effects should result in any
227 // cross-crate inconsistencies (getting one behavior in the same
228 // crate, and a different behavior in another crate) due to the
229 // limited surface that proc-macros can expose.
231 // IMPORTANT: If this is ever changed, be sure to update
232 // `rustc_span::hygiene::raw_encode_expn_id` to handle
233 // encoding `ExpnData` for proc-macro crates.
235 SyntaxContext::root().encode(s)?;
237 span.ctxt.encode(s)?;
241 return TAG_PARTIAL_SPAN.encode(s);
244 // The Span infrastructure should make sure that this invariant holds:
245 debug_assert!(span.lo <= span.hi);
247 if !s.source_file_cache.0.contains(span.lo) {
248 let source_map = s.tcx.sess.source_map();
249 let source_file_index = source_map.lookup_source_file_idx(span.lo);
250 s.source_file_cache =
251 (source_map.files()[source_file_index].clone(), source_file_index);
254 if !s.source_file_cache.0.contains(span.hi) {
255 // Unfortunately, macro expansion still sometimes generates Spans
256 // that malformed in this way.
257 return TAG_PARTIAL_SPAN.encode(s);
260 let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
261 // Record the fact that we need to encode the data for this `SourceFile`
262 source_files.insert(s.source_file_cache.1);
264 // There are two possible cases here:
265 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
266 // crate we are writing metadata for. When the metadata for *this* crate gets
267 // deserialized, the deserializer will need to know which crate it originally came
268 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
269 // be deserialized after the rest of the span data, which tells the deserializer
270 // which crate contains the source map information.
271 // 2. This span comes from our own crate. No special hamdling is needed - we just
272 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
273 // our own source map information.
275 // If we're a proc-macro crate, we always treat this as a local `Span`.
276 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
277 // if we're a proc-macro crate.
278 // This allows us to avoid loading the dependencies of proc-macro crates: all of
279 // the information we need to decode `Span`s is stored in the proc-macro crate.
280 let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
281 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
282 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
283 // are relative to the source map information for the 'foreign' crate whose CrateNum
284 // we write into the metadata. This allows `imported_source_files` to binary
285 // search through the 'foreign' crate's source map information, using the
286 // deserialized 'lo' and 'hi' values directly.
288 // All of this logic ensures that the final result of deserialization is a 'normal'
289 // Span that can be used without any additional trouble.
290 let external_start_pos = {
291 // Introduce a new scope so that we drop the 'lock()' temporary
292 match &*s.source_file_cache.0.external_src.lock() {
293 ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
294 src => panic!("Unexpected external source {:?}", src),
297 let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
298 let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
300 (TAG_VALID_SPAN_FOREIGN, lo, hi)
302 (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
308 // Encode length which is usually less than span.hi and profits more
309 // from the variable-length integer encoding that we use.
313 if tag == TAG_VALID_SPAN_FOREIGN {
314 // This needs to be two lines to avoid holding the `s.source_file_cache`
315 // while calling `cnum.encode(s)`
316 let cnum = s.source_file_cache.0.cnum;
324 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
325 const CLEAR_CROSS_CRATE: bool = true;
327 fn position(&self) -> usize {
328 self.opaque.position()
331 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
332 &mut self.type_shorthands
335 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
336 &mut self.predicate_shorthands
341 alloc_id: &rustc_middle::mir::interpret::AllocId,
342 ) -> Result<(), Self::Error> {
343 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
349 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [thir::abstract_const::Node<'tcx>] {
350 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
355 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
356 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
361 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
362 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
363 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
366 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
367 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
368 self.encode(ecx).unwrap()
372 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
373 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
374 self.encode(ecx).unwrap()
378 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
381 I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
383 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
384 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
388 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
389 // normally need extra variables to avoid errors about multiple mutable borrows.
390 macro_rules! record {
391 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
394 let lazy = $self.lazy(value);
395 $self.$tables.$table.set($def_id.index, lazy);
400 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
401 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
404 ) -> Result<(), <Self as Encoder>::Error> {
405 let min_end = lazy.position.get() + T::min_size(lazy.meta);
406 let distance = match self.lazy_state {
407 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
408 LazyState::NodeStart(start) => {
409 let start = start.get();
410 assert!(min_end <= start);
413 LazyState::Previous(last_min_end) => {
415 last_min_end <= lazy.position,
416 "make sure that the calls to `lazy*` \
417 are in the same order as the metadata fields",
419 lazy.position.get() - last_min_end.get()
422 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
423 self.emit_usize(distance)
426 fn lazy<T: ?Sized + LazyMeta>(
428 value: impl EncodeContentsForLazy<'a, 'tcx, T>,
430 let pos = NonZeroUsize::new(self.position()).unwrap();
432 assert_eq!(self.lazy_state, LazyState::NoNode);
433 self.lazy_state = LazyState::NodeStart(pos);
434 let meta = value.encode_contents_for_lazy(self);
435 self.lazy_state = LazyState::NoNode;
437 assert!(pos.get() + <T>::min_size(meta) <= self.position());
439 Lazy::from_position_and_meta(pos, meta)
442 fn encode_info_for_items(&mut self) {
443 self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
445 // Proc-macro crates only export proc-macro items, which are looked
446 // up using `proc_macro_data`
447 if self.is_proc_macro {
451 self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor());
454 fn encode_def_path_table(&mut self) {
455 let table = self.tcx.resolutions(()).definitions.def_path_table();
456 if self.is_proc_macro {
457 for def_index in std::iter::once(CRATE_DEF_INDEX)
458 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
460 let def_key = self.lazy(table.def_key(def_index));
461 let def_path_hash = self.lazy(table.def_path_hash(def_index));
462 self.tables.def_keys.set(def_index, def_key);
463 self.tables.def_path_hashes.set(def_index, def_path_hash);
466 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
467 let def_key = self.lazy(def_key);
468 let def_path_hash = self.lazy(def_path_hash);
469 self.tables.def_keys.set(def_index, def_key);
470 self.tables.def_path_hashes.set(def_index, def_path_hash);
475 fn encode_def_path_hash_map(&mut self) -> Lazy<DefPathHashMapRef<'tcx>> {
476 self.lazy(DefPathHashMapRef::BorrowedFromTcx(
477 self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(),
481 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
482 let source_map = self.tcx.sess.source_map();
483 let all_source_files = source_map.files();
485 // By replacing the `Option` with `None`, we ensure that we can't
486 // accidentally serialize any more `Span`s after the source map encoding
488 let required_source_files = self.required_source_files.take().unwrap();
490 let adapted = all_source_files
493 .filter(|(idx, source_file)| {
494 // Only serialize `SourceFile`s that were used
495 // during the encoding of a `Span`
496 required_source_files.contains(*idx) &&
497 // Don't serialize imported `SourceFile`s, unless
498 // we're in a proc-macro crate.
499 (!source_file.is_imported() || self.is_proc_macro)
501 .map(|(_, source_file)| {
502 let mut adapted = match source_file.name {
503 FileName::Real(ref realname) => {
504 let mut adapted = (**source_file).clone();
505 adapted.name = FileName::Real(match realname {
506 RealFileName::LocalPath(path_to_file) => {
507 // Prepend path of working directory onto potentially
508 // relative paths, because they could become relative
509 // to a wrong directory.
510 // We include `working_dir` as part of the crate hash,
511 // so it's okay for us to use it as part of the encoded
513 let working_dir = &self.tcx.sess.opts.working_dir;
515 RealFileName::LocalPath(absolute) => {
516 // Although neither working_dir or the file name were subject
517 // to path remapping, the concatenation between the two may
518 // be. Hence we need to do a remapping here.
519 let joined = Path::new(absolute).join(path_to_file);
520 let (joined, remapped) =
521 source_map.path_mapping().map_prefix(joined);
523 RealFileName::Remapped {
525 virtual_name: joined,
528 RealFileName::LocalPath(joined)
531 RealFileName::Remapped { local_path: _, virtual_name } => {
532 // If working_dir has been remapped, then we emit
533 // Remapped variant as the expanded path won't be valid
534 RealFileName::Remapped {
536 virtual_name: Path::new(virtual_name)
542 RealFileName::Remapped { local_path: _, virtual_name } => {
543 RealFileName::Remapped {
544 // We do not want any local path to be exported into metadata
546 virtual_name: virtual_name.clone(),
550 adapted.name_hash = {
551 let mut hasher: StableHasher = StableHasher::new();
552 adapted.name.hash(&mut hasher);
553 hasher.finish::<u128>()
558 // expanded code, not from a file
559 _ => source_file.clone(),
562 // We're serializing this `SourceFile` into our crate metadata,
563 // so mark it as coming from this crate.
564 // This also ensures that we don't try to deserialize the
565 // `CrateNum` for a proc-macro dependency - since proc macro
566 // dependencies aren't loaded when we deserialize a proc-macro,
567 // trying to remap the `CrateNum` would fail.
568 if self.is_proc_macro {
569 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
573 .collect::<Vec<_>>();
575 self.lazy(adapted.iter().map(|rc| &**rc))
578 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
579 let mut i = self.position();
581 // Encode the crate deps
582 let crate_deps = self.encode_crate_deps();
583 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
584 let dep_bytes = self.position() - i;
586 // Encode the lib features.
588 let lib_features = self.encode_lib_features();
589 let lib_feature_bytes = self.position() - i;
591 // Encode the language items.
593 let lang_items = self.encode_lang_items();
594 let lang_items_missing = self.encode_lang_items_missing();
595 let lang_item_bytes = self.position() - i;
597 // Encode the diagnostic items.
599 let diagnostic_items = self.encode_diagnostic_items();
600 let diagnostic_item_bytes = self.position() - i;
602 // Encode the native libraries used
604 let native_libraries = self.encode_native_libraries();
605 let native_lib_bytes = self.position() - i;
607 let foreign_modules = self.encode_foreign_modules();
609 // Encode DefPathTable
611 self.encode_def_path_table();
612 let def_path_table_bytes = self.position() - i;
614 // Encode the def IDs of impls, for coherence checking.
616 let impls = self.encode_impls();
617 let impl_bytes = self.position() - i;
624 let mir_bytes = self.position() - i;
628 self.encode_def_ids();
629 self.encode_info_for_items();
630 let item_bytes = self.position() - i;
632 // Encode the allocation index
633 let interpret_alloc_index = {
634 let mut interpret_alloc_index = Vec::new();
636 trace!("beginning to encode alloc ids");
638 let new_n = self.interpret_allocs.len();
639 // if we have found new ids, serialize those, too
644 trace!("encoding {} further alloc ids", new_n - n);
645 for idx in n..new_n {
646 let id = self.interpret_allocs[idx];
647 let pos = self.position() as u32;
648 interpret_alloc_index.push(pos);
649 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
653 self.lazy(interpret_alloc_index)
656 // Encode the proc macro data. This affects 'tables',
657 // so we need to do this before we encode the tables
659 let proc_macro_data = self.encode_proc_macros();
660 let proc_macro_data_bytes = self.position() - i;
663 let tables = self.tables.encode(&mut self.opaque);
664 let tables_bytes = self.position() - i;
666 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
667 // this as late as possible to give the prefetching as much time as possible to complete.
669 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
670 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
671 let exported_symbols_bytes = self.position() - i;
673 // Encode the hygiene data,
674 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
675 // of encoding other items (e.g. `optimized_mir`) may cause us to load
676 // data from the incremental cache. If this causes us to deserialize a `Span`,
677 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
678 // Therefore, we need to encode the hygiene data last to ensure that we encode
679 // any `SyntaxContext`s that might be used.
681 let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene();
682 let hygiene_bytes = self.position() - i;
685 let def_path_hash_map = self.encode_def_path_hash_map();
686 let def_path_hash_map_bytes = self.position() - i;
688 // Encode source_map. This needs to be done last,
689 // since encoding `Span`s tells us which `SourceFiles` we actually
692 let source_map = self.encode_source_map();
693 let source_map_bytes = self.position() - i;
695 let attrs = tcx.hir().krate_attrs();
696 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
698 let root = self.lazy(CrateRoot {
699 name: tcx.crate_name(LOCAL_CRATE),
700 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
701 triple: tcx.sess.opts.target_triple.clone(),
702 hash: tcx.crate_hash(LOCAL_CRATE),
703 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
704 panic_strategy: tcx.sess.panic_strategy(),
705 panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop,
706 edition: tcx.sess.edition(),
707 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
708 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
709 has_default_lib_allocator,
711 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
712 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
713 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
714 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
715 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
716 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
717 symbol_mangling_version: tcx.sess.opts.debugging_opts.get_symbol_mangling_version(),
720 dylib_dependency_formats,
730 interpret_alloc_index,
738 let total_bytes = self.position();
740 if tcx.sess.meta_stats() {
741 let mut zero_bytes = 0;
742 for e in self.opaque.data.iter() {
748 eprintln!("metadata stats:");
749 eprintln!(" dep bytes: {}", dep_bytes);
750 eprintln!(" lib feature bytes: {}", lib_feature_bytes);
751 eprintln!(" lang item bytes: {}", lang_item_bytes);
752 eprintln!(" diagnostic item bytes: {}", diagnostic_item_bytes);
753 eprintln!(" native bytes: {}", native_lib_bytes);
754 eprintln!(" source_map bytes: {}", source_map_bytes);
755 eprintln!(" impl bytes: {}", impl_bytes);
756 eprintln!(" exp. symbols bytes: {}", exported_symbols_bytes);
757 eprintln!(" def-path table bytes: {}", def_path_table_bytes);
758 eprintln!(" def-path hashes bytes: {}", def_path_hash_map_bytes);
759 eprintln!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
760 eprintln!(" mir bytes: {}", mir_bytes);
761 eprintln!(" item bytes: {}", item_bytes);
762 eprintln!(" table bytes: {}", tables_bytes);
763 eprintln!(" hygiene bytes: {}", hygiene_bytes);
764 eprintln!(" zero bytes: {}", zero_bytes);
765 eprintln!(" total bytes: {}", total_bytes);
772 fn should_encode_visibility(def_kind: DefKind) -> bool {
782 | DefKind::TraitAlias
789 | DefKind::AssocConst
792 | DefKind::ForeignMod
795 | DefKind::Field => true,
797 | DefKind::ConstParam
798 | DefKind::LifetimeParam
803 | DefKind::ExternCrate => false,
807 fn should_encode_stability(def_kind: DefKind) -> bool {
816 | DefKind::AssocConst
818 | DefKind::ConstParam
822 | DefKind::ForeignMod
829 | DefKind::TraitAlias
831 | DefKind::ForeignTy => true,
833 | DefKind::LifetimeParam
838 | DefKind::ExternCrate => false,
842 /// Whether we should encode MIR.
844 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
845 /// We want to avoid this work when not required. Therefore:
846 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
847 /// - we skip `optimized_mir` for check runs.
849 /// Return a pair, resp. for CTFE and for LLVM.
850 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
851 match tcx.def_kind(def_id) {
853 DefKind::Ctor(_, _) => {
854 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
855 || tcx.sess.opts.debugging_opts.always_encode_mir;
859 DefKind::AnonConst | DefKind::AssocConst | DefKind::Static | DefKind::Const => {
862 // Full-fledged functions
863 DefKind::AssocFn | DefKind::Fn => {
864 let generics = tcx.generics_of(def_id);
865 let needs_inline = (generics.requires_monomorphization(tcx)
866 || tcx.codegen_fn_attrs(def_id).requests_inline())
867 && tcx.sess.opts.output_types.should_codegen();
868 // Only check the presence of the `const` modifier.
869 let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id());
870 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
871 (is_const_fn, needs_inline || always_encode_mir)
873 // Closures can't be const fn.
874 DefKind::Closure => {
875 let generics = tcx.generics_of(def_id);
876 let needs_inline = (generics.requires_monomorphization(tcx)
877 || tcx.codegen_fn_attrs(def_id).requests_inline())
878 && tcx.sess.opts.output_types.should_codegen();
879 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
880 (false, needs_inline || always_encode_mir)
882 // Generators require optimized MIR to compute layout.
883 DefKind::Generator => (false, true),
884 // The others don't have MIR.
889 fn should_encode_variances(def_kind: DefKind) -> bool {
897 | DefKind::AssocFn => true,
901 | DefKind::AssocConst
903 | DefKind::ConstParam
906 | DefKind::ForeignMod
911 | DefKind::TraitAlias
915 | DefKind::LifetimeParam
920 | DefKind::ExternCrate => false,
924 fn should_encode_generics(def_kind: DefKind) -> bool {
933 | DefKind::TraitAlias
940 | DefKind::AssocConst
947 | DefKind::Generator => true,
949 | DefKind::ForeignMod
950 | DefKind::ConstParam
953 | DefKind::LifetimeParam
955 | DefKind::ExternCrate => false,
959 impl EncodeContext<'a, 'tcx> {
960 fn encode_def_ids(&mut self) {
961 if self.is_proc_macro {
966 for local_id in hir.iter_local_def_id() {
967 let def_id = local_id.to_def_id();
968 let def_kind = tcx.opt_def_kind(local_id);
969 let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue };
970 record!(self.tables.def_kind[def_id] <- match def_kind {
971 // Replace Ctor by the enclosing object to avoid leaking details in children crates.
972 DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct,
973 DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant,
974 def_kind => def_kind,
976 record!(self.tables.span[def_id] <- tcx.def_span(def_id));
977 record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id));
978 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
979 if should_encode_visibility(def_kind) {
980 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
982 if should_encode_stability(def_kind) {
983 self.encode_stability(def_id);
984 self.encode_const_stability(def_id);
985 self.encode_deprecation(def_id);
987 if should_encode_variances(def_kind) {
988 let v = self.tcx.variances_of(def_id);
989 record!(self.tables.variances[def_id] <- v);
991 if should_encode_generics(def_kind) {
992 let g = tcx.generics_of(def_id);
993 record!(self.tables.generics[def_id] <- g);
994 record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id));
995 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
996 if !inferred_outlives.is_empty() {
997 record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
1000 if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1001 record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
1004 let inherent_impls = tcx.crate_inherent_impls(());
1005 for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
1006 if implementations.is_empty() {
1009 record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1010 assert!(def_id.is_local());
1016 fn encode_item_type(&mut self, def_id: DefId) {
1017 debug!("EncodeContext::encode_item_type({:?})", def_id);
1018 record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
1021 fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
1023 let variant = &def.variants[index];
1024 let def_id = variant.def_id;
1025 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1027 let data = VariantData {
1028 ctor_kind: variant.ctor_kind,
1029 discr: variant.discr,
1030 ctor: variant.ctor_def_id.map(|did| did.index),
1031 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1034 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1035 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1036 assert!(f.did.is_local());
1039 self.encode_ident_span(def_id, variant.ident);
1040 self.encode_item_type(def_id);
1041 if variant.ctor_kind == CtorKind::Fn {
1042 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1043 if let Some(ctor_def_id) = variant.ctor_def_id {
1044 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1049 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
1051 let variant = &def.variants[index];
1052 let def_id = variant.ctor_def_id.unwrap();
1053 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1055 // FIXME(eddyb) encode only the `CtorKind` for constructors.
1056 let data = VariantData {
1057 ctor_kind: variant.ctor_kind,
1058 discr: variant.discr,
1059 ctor: Some(def_id.index),
1060 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1063 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1064 self.encode_item_type(def_id);
1065 if variant.ctor_kind == CtorKind::Fn {
1066 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1070 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1072 let def_id = local_def_id.to_def_id();
1073 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1075 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1076 // only ever get called for the crate root. We still want to encode
1077 // the crate root for consistency with other crates (some of the resolver
1078 // code uses it). However, we skip encoding anything relating to child
1079 // items - we encode information about proc-macros later on.
1080 let reexports = if !self.is_proc_macro {
1081 match tcx.module_exports(local_def_id) {
1082 Some(exports) => self.lazy(exports),
1089 let data = ModData { reexports, expansion: tcx.expn_that_defined(local_def_id) };
1091 record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
1092 if self.is_proc_macro {
1093 record!(self.tables.children[def_id] <- &[]);
1095 record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
1096 item_id.def_id.local_def_index
1103 adt_def: &ty::AdtDef,
1104 variant_index: VariantIdx,
1107 let variant = &adt_def.variants[variant_index];
1108 let field = &variant.fields[field_index];
1110 let def_id = field.did;
1111 debug!("EncodeContext::encode_field({:?})", def_id);
1113 record!(self.tables.kind[def_id] <- EntryKind::Field);
1114 self.encode_ident_span(def_id, field.ident);
1115 self.encode_item_type(def_id);
1118 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
1119 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1121 let variant = adt_def.non_enum_variant();
1123 let data = VariantData {
1124 ctor_kind: variant.ctor_kind,
1125 discr: variant.discr,
1126 ctor: Some(def_id.index),
1127 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1130 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
1131 self.encode_item_type(def_id);
1132 if variant.ctor_kind == CtorKind::Fn {
1133 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1137 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1138 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1139 let bounds = self.tcx.explicit_item_bounds(def_id);
1140 if !bounds.is_empty() {
1141 record!(self.tables.explicit_item_bounds[def_id] <- bounds);
1145 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1146 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1149 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1150 let ast_item = tcx.hir().expect_trait_item(hir_id);
1151 let trait_item = tcx.associated_item(def_id);
1153 let container = match trait_item.defaultness {
1154 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
1155 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
1156 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
1159 match trait_item.kind {
1160 ty::AssocKind::Const => {
1161 let rendered = rustc_hir_pretty::to_string(
1162 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
1163 |s| s.print_trait_item(ast_item),
1165 let rendered_const = self.lazy(RenderedConst(rendered));
1167 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(
1173 ty::AssocKind::Fn => {
1174 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
1175 let param_names = match *m {
1176 hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names),
1177 hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body),
1180 asyncness: m_sig.header.asyncness,
1181 constness: hir::Constness::NotConst,
1187 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1190 has_self: trait_item.fn_has_self_parameter,
1193 ty::AssocKind::Type => {
1194 self.encode_explicit_item_bounds(def_id);
1195 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1198 self.encode_ident_span(def_id, ast_item.ident);
1199 match trait_item.kind {
1200 ty::AssocKind::Const | ty::AssocKind::Fn => {
1201 self.encode_item_type(def_id);
1203 ty::AssocKind::Type => {
1204 if trait_item.defaultness.has_value() {
1205 self.encode_item_type(def_id);
1209 if trait_item.kind == ty::AssocKind::Fn {
1210 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1214 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1215 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1218 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1219 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1220 let impl_item = self.tcx.associated_item(def_id);
1222 let container = match impl_item.defaultness {
1223 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1224 hir::Defaultness::Final => AssocContainer::ImplFinal,
1225 hir::Defaultness::Default { has_value: false } => {
1226 span_bug!(ast_item.span, "impl items always have values (currently)")
1230 match impl_item.kind {
1231 ty::AssocKind::Const => {
1232 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1233 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1235 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(
1238 self.encode_rendered_const_for_body(body_id))
1244 ty::AssocKind::Fn => {
1245 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1247 asyncness: sig.header.asyncness,
1248 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1249 constness: if self.tcx.is_const_fn_raw(def_id) {
1250 hir::Constness::Const
1252 hir::Constness::NotConst
1254 param_names: self.encode_fn_param_names_for_body(body),
1259 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1262 has_self: impl_item.fn_has_self_parameter,
1265 ty::AssocKind::Type => {
1266 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1269 self.encode_ident_span(def_id, impl_item.ident);
1270 self.encode_item_type(def_id);
1271 if impl_item.kind == ty::AssocKind::Fn {
1272 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1276 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1277 self.lazy(self.tcx.hir().body_param_names(body_id))
1280 fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1281 self.lazy(param_names.iter())
1284 fn encode_mir(&mut self) {
1285 if self.is_proc_macro {
1289 let mut keys_and_jobs = self
1293 .filter_map(|&def_id| {
1294 let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id);
1295 if encode_const || encode_opt {
1296 Some((def_id, encode_const, encode_opt))
1301 .collect::<Vec<_>>();
1302 // Sort everything to ensure a stable order for diagnotics.
1303 keys_and_jobs.sort_by_key(|&(def_id, _, _)| def_id);
1304 for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() {
1305 debug_assert!(encode_const || encode_opt);
1307 debug!("EntryBuilder::encode_mir({:?})", def_id);
1309 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1312 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id));
1314 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1315 let abstract_const = self.tcx.thir_abstract_const(def_id);
1316 if let Ok(Some(abstract_const)) = abstract_const {
1317 record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const);
1320 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1323 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1324 let unused = self.tcx.unused_generic_params(instance);
1325 if !unused.is_empty() {
1326 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1331 fn encode_stability(&mut self, def_id: DefId) {
1332 debug!("EncodeContext::encode_stability({:?})", def_id);
1334 // The query lookup can take a measurable amount of time in crates with many items. Check if
1335 // the stability attributes are even enabled before using their queries.
1336 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1337 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1338 record!(self.tables.stability[def_id] <- stab)
1343 fn encode_const_stability(&mut self, def_id: DefId) {
1344 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1346 // The query lookup can take a measurable amount of time in crates with many items. Check if
1347 // the stability attributes are even enabled before using their queries.
1348 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1349 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1350 record!(self.tables.const_stability[def_id] <- stab)
1355 fn encode_deprecation(&mut self, def_id: DefId) {
1356 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1357 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1358 record!(self.tables.deprecation[def_id] <- depr);
1362 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1363 let hir = self.tcx.hir();
1364 let body = hir.body(body_id);
1365 let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1366 s.print_expr(&body.value)
1368 let rendered_const = &RenderedConst(rendered);
1369 self.lazy(rendered_const)
1372 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1375 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1377 self.encode_ident_span(def_id, item.ident);
1379 let entry_kind = match item.kind {
1380 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1381 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1382 hir::ItemKind::Const(_, body_id) => {
1383 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1384 EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id))
1386 hir::ItemKind::Fn(ref sig, .., body) => {
1388 asyncness: sig.header.asyncness,
1389 constness: sig.header.constness,
1390 param_names: self.encode_fn_param_names_for_body(body),
1393 EntryKind::Fn(self.lazy(data))
1395 hir::ItemKind::Macro(ref macro_def) => {
1396 EntryKind::MacroDef(self.lazy(macro_def.clone()))
1398 hir::ItemKind::Mod(ref m) => {
1399 return self.encode_info_for_mod(item.def_id, m);
1401 hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1402 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1403 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1404 hir::ItemKind::OpaqueTy(..) => {
1405 self.encode_explicit_item_bounds(def_id);
1408 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1409 hir::ItemKind::Struct(ref struct_def, _) => {
1410 let adt_def = self.tcx.adt_def(def_id);
1411 let variant = adt_def.non_enum_variant();
1413 // Encode def_ids for each field and method
1414 // for methods, write all the stuff get_trait_method
1416 let ctor = struct_def
1418 .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1421 self.lazy(VariantData {
1422 ctor_kind: variant.ctor_kind,
1423 discr: variant.discr,
1425 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1430 hir::ItemKind::Union(..) => {
1431 let adt_def = self.tcx.adt_def(def_id);
1432 let variant = adt_def.non_enum_variant();
1435 self.lazy(VariantData {
1436 ctor_kind: variant.ctor_kind,
1437 discr: variant.discr,
1439 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1444 hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1445 let trait_ref = self.tcx.impl_trait_ref(def_id);
1446 let polarity = self.tcx.impl_polarity(def_id);
1447 let parent = if let Some(trait_ref) = trait_ref {
1448 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1449 trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| {
1450 an.nth(1).and_then(|node| match node {
1451 specialization_graph::Node::Impl(parent) => Some(parent),
1459 // if this is an impl of `CoerceUnsized`, create its
1460 // "unsized info", else just store None
1461 let coerce_unsized_info = trait_ref.and_then(|t| {
1462 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1463 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1469 let data = ImplData {
1473 parent_impl: parent,
1474 coerce_unsized_info,
1477 EntryKind::Impl(self.lazy(data))
1479 hir::ItemKind::Trait(..) => {
1480 let trait_def = self.tcx.trait_def(def_id);
1481 let data = TraitData {
1482 unsafety: trait_def.unsafety,
1483 paren_sugar: trait_def.paren_sugar,
1484 has_auto_impl: self.tcx.trait_is_auto(def_id),
1485 is_marker: trait_def.is_marker,
1486 skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch,
1487 specialization_kind: trait_def.specialization_kind,
1490 EntryKind::Trait(self.lazy(data))
1492 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1493 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1494 bug!("cannot encode info for item {:?}", item)
1497 record!(self.tables.kind[def_id] <- entry_kind);
1498 // FIXME(eddyb) there should be a nicer way to do this.
1500 hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <-
1503 .map(|foreign_item| foreign_item.id.def_id.local_def_index)
1505 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1506 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1507 assert!(v.def_id.is_local());
1511 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1512 record!(self.tables.children[def_id] <-
1513 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1514 assert!(f.did.is_local());
1519 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1520 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1521 record!(self.tables.children[def_id] <-
1522 associated_item_def_ids.iter().map(|&def_id| {
1523 assert!(def_id.is_local());
1531 hir::ItemKind::Static(..)
1532 | hir::ItemKind::Const(..)
1533 | hir::ItemKind::Fn(..)
1534 | hir::ItemKind::TyAlias(..)
1535 | hir::ItemKind::OpaqueTy(..)
1536 | hir::ItemKind::Enum(..)
1537 | hir::ItemKind::Struct(..)
1538 | hir::ItemKind::Union(..)
1539 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1542 if let hir::ItemKind::Fn(..) = item.kind {
1543 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1545 if let hir::ItemKind::Impl { .. } = item.kind {
1546 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1547 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1552 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1553 record!(self.tables.kind[def_id] <- kind);
1555 self.encode_item_type(def_id);
1559 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1560 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1562 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1563 // including on the signature, which is inferred in `typeck.
1564 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1565 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1568 ty::Generator(..) => {
1569 let data = self.tcx.generator_kind(def_id).unwrap();
1570 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data));
1573 ty::Closure(..) => {
1574 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1577 _ => bug!("closure that is neither generator nor closure"),
1579 self.encode_item_type(def_id.to_def_id());
1580 if let ty::Closure(def_id, substs) = *ty.kind() {
1581 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1585 fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1586 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1587 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1588 let body_id = self.tcx.hir().body_owned_by(id);
1589 let const_data = self.encode_rendered_const_for_body(body_id);
1590 let qualifs = self.tcx.mir_const_qualif(def_id);
1592 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1593 self.encode_item_type(def_id.to_def_id());
1596 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1597 empty_proc_macro!(self);
1598 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1599 self.lazy(used_libraries.iter())
1602 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1603 empty_proc_macro!(self);
1604 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1605 self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1608 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1609 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1610 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1611 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1613 let _: Result<(), !> = self.hygiene_ctxt.encode(
1614 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1615 |(this, syntax_contexts, _, _), index, ctxt_data| {
1616 syntax_contexts.set(index, this.lazy(ctxt_data));
1619 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1620 if let Some(index) = index.as_local() {
1621 expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1622 expn_hash_table.set(index.as_raw(), this.lazy(hash));
1629 syntax_contexts.encode(&mut self.opaque),
1630 expn_data_table.encode(&mut self.opaque),
1631 expn_hash_table.encode(&mut self.opaque),
1635 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1636 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1639 let hir = tcx.hir();
1641 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1642 let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1644 self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1645 let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1646 for (i, span) in spans.into_iter().enumerate() {
1647 let span = self.lazy(span);
1648 self.tables.proc_macro_quoted_spans.set(i, span);
1651 record!(self.tables.def_kind[LOCAL_CRATE.as_def_id()] <- DefKind::Mod);
1652 record!(self.tables.span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1653 record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id()));
1654 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1655 if let Some(stability) = stability {
1656 record!(self.tables.stability[LOCAL_CRATE.as_def_id()] <- stability);
1658 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1660 // Normally, this information is encoded when we walk the items
1661 // defined in this crate. However, we skip doing that for proc-macro crates,
1662 // so we manually encode just the information that we need
1663 for &proc_macro in &tcx.resolutions(()).proc_macros {
1664 let id = proc_macro;
1665 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1666 let mut name = hir.name(proc_macro);
1667 let span = hir.span(proc_macro);
1668 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1669 // so downstream crates need access to them.
1670 let attrs = hir.attrs(proc_macro);
1671 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1673 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1675 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1676 // This unwrap chain should have been checked by the proc-macro harness.
1677 name = attr.meta_item_list().unwrap()[0]
1685 bug!("Unknown proc-macro type for item {:?}", id);
1688 let mut def_key = self.tcx.hir().def_key(id);
1689 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1691 let def_id = id.to_def_id();
1692 record!(self.tables.def_kind[def_id] <- DefKind::Macro(macro_kind));
1693 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1694 record!(self.tables.attributes[def_id] <- attrs);
1695 record!(self.tables.def_keys[def_id] <- def_key);
1696 record!(self.tables.ident_span[def_id] <- span);
1697 record!(self.tables.span[def_id] <- span);
1698 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1699 if let Some(stability) = stability {
1700 record!(self.tables.stability[def_id] <- stability);
1704 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1710 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1711 empty_proc_macro!(self);
1718 let dep = CrateDep {
1719 name: self.tcx.crate_name(cnum),
1720 hash: self.tcx.crate_hash(cnum),
1721 host_hash: self.tcx.crate_host_hash(cnum),
1722 kind: self.tcx.dep_kind(cnum),
1723 extra_filename: self.tcx.extra_filename(cnum),
1727 .collect::<Vec<_>>();
1730 // Sanity-check the crate numbers
1731 let mut expected_cnum = 1;
1732 for &(n, _) in &deps {
1733 assert_eq!(n, CrateNum::new(expected_cnum));
1738 // We're just going to write a list of crate 'name-hash-version's, with
1739 // the assumption that they are numbered 1 to n.
1740 // FIXME (#2166): This is not nearly enough to support correct versioning
1741 // but is enough to get transitive crate dependencies working.
1742 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1745 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1746 empty_proc_macro!(self);
1748 let lib_features = tcx.lib_features();
1749 self.lazy(lib_features.to_vec())
1752 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1753 empty_proc_macro!(self);
1755 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1756 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1759 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1760 empty_proc_macro!(self);
1762 let lang_items = tcx.lang_items();
1763 let lang_items = lang_items.items().iter();
1764 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1765 if let Some(def_id) = opt_def_id {
1766 if def_id.is_local() {
1767 return Some((def_id.index, i));
1774 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1775 empty_proc_macro!(self);
1777 self.lazy(&tcx.lang_items().missing)
1780 /// Encodes an index, mapping each trait to its (local) implementations.
1781 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1782 empty_proc_macro!(self);
1783 debug!("EncodeContext::encode_impls()");
1785 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1786 tcx.hir().visit_all_item_likes(&mut visitor);
1788 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1790 // Bring everything into deterministic order for hashing
1791 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1793 let all_impls: Vec<_> = all_impls
1795 .map(|(trait_def_id, mut impls)| {
1796 // Bring everything into deterministic order for hashing
1797 impls.sort_by_cached_key(|&(index, _)| {
1798 tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1802 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1803 impls: self.lazy(&impls),
1808 self.lazy(&all_impls)
1811 // Encodes all symbols exported from this crate into the metadata.
1813 // This pass is seeded off the reachability list calculated in the
1814 // middle::reachable module but filters out items that either don't have a
1815 // symbol associated with them (they weren't translated) or if they're an FFI
1816 // definition (as that's not defined in this crate).
1817 fn encode_exported_symbols(
1819 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1820 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1821 empty_proc_macro!(self);
1822 // The metadata symbol name is special. It should not show up in
1823 // downstream crates.
1824 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1829 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1830 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1837 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1838 empty_proc_macro!(self);
1839 let formats = self.tcx.dependency_formats(());
1840 for (ty, arr) in formats.iter() {
1841 if *ty != CrateType::Dylib {
1844 return self.lazy(arr.iter().map(|slot| match *slot {
1845 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1847 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1848 Linkage::Static => Some(LinkagePreference::RequireStatic),
1854 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1857 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1860 hir::ForeignItemKind::Fn(_, ref names, _) => {
1862 asyncness: hir::IsAsync::NotAsync,
1863 constness: if self.tcx.is_const_fn_raw(def_id) {
1864 hir::Constness::Const
1866 hir::Constness::NotConst
1868 param_names: self.encode_fn_param_names(names),
1870 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn(self.lazy(data)));
1872 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => {
1873 record!(self.tables.kind[def_id] <- EntryKind::ForeignMutStatic);
1875 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => {
1876 record!(self.tables.kind[def_id] <- EntryKind::ForeignImmStatic);
1878 hir::ForeignItemKind::Type => {
1879 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
1882 self.encode_ident_span(def_id, nitem.ident);
1883 self.encode_item_type(def_id);
1884 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1885 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1890 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1891 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1892 type Map = Map<'tcx>;
1894 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1895 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1897 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1898 intravisit::walk_expr(self, ex);
1899 self.encode_info_for_expr(ex);
1901 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1902 intravisit::walk_anon_const(self, c);
1903 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1904 self.encode_info_for_anon_const(def_id);
1906 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1907 intravisit::walk_item(self, item);
1909 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1910 _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
1912 self.encode_addl_info_for_item(item);
1914 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1915 intravisit::walk_foreign_item(self, ni);
1916 self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
1918 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1919 intravisit::walk_generics(self, generics);
1920 self.encode_info_for_generics(generics);
1924 impl EncodeContext<'a, 'tcx> {
1925 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1926 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1927 for (field_index, _field) in variant.fields.iter().enumerate() {
1928 self.encode_field(adt_def, variant_index, field_index);
1933 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1934 for param in generics.params {
1935 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1937 GenericParamKind::Lifetime { .. } => continue,
1938 GenericParamKind::Type { default, .. } => {
1939 self.encode_info_for_generic_param(
1941 EntryKind::TypeParam,
1945 GenericParamKind::Const { ref default, .. } => {
1946 let def_id = def_id.to_def_id();
1947 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1948 if default.is_some() {
1949 record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id))
1956 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1957 if let hir::ExprKind::Closure(..) = expr.kind {
1958 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1959 self.encode_info_for_closure(def_id);
1963 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1964 record!(self.tables.ident_span[def_id] <- ident.span);
1967 /// In some cases, along with the item itself, we also
1968 /// encode some sub-items. Usually we want some info from the item
1969 /// so it's easier to do that here then to wait until we would encounter
1970 /// normally in the visitor walk.
1971 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1973 hir::ItemKind::Static(..)
1974 | hir::ItemKind::Const(..)
1975 | hir::ItemKind::Fn(..)
1976 | hir::ItemKind::Macro(..)
1977 | hir::ItemKind::Mod(..)
1978 | hir::ItemKind::ForeignMod { .. }
1979 | hir::ItemKind::GlobalAsm(..)
1980 | hir::ItemKind::ExternCrate(..)
1981 | hir::ItemKind::Use(..)
1982 | hir::ItemKind::TyAlias(..)
1983 | hir::ItemKind::OpaqueTy(..)
1984 | hir::ItemKind::TraitAlias(..) => {
1985 // no sub-item recording needed in these cases
1987 hir::ItemKind::Enum(..) => {
1988 let def = self.tcx.adt_def(item.def_id.to_def_id());
1989 self.encode_fields(def);
1991 for (i, variant) in def.variants.iter_enumerated() {
1992 self.encode_enum_variant_info(def, i);
1994 if let Some(_ctor_def_id) = variant.ctor_def_id {
1995 self.encode_enum_variant_ctor(def, i);
1999 hir::ItemKind::Struct(ref struct_def, _) => {
2000 let def = self.tcx.adt_def(item.def_id.to_def_id());
2001 self.encode_fields(def);
2003 // If the struct has a constructor, encode it.
2004 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
2005 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
2006 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
2009 hir::ItemKind::Union(..) => {
2010 let def = self.tcx.adt_def(item.def_id.to_def_id());
2011 self.encode_fields(def);
2013 hir::ItemKind::Impl { .. } => {
2014 for &trait_item_def_id in
2015 self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2017 self.encode_info_for_impl_item(trait_item_def_id);
2020 hir::ItemKind::Trait(..) => {
2021 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2023 self.encode_info_for_trait_item(item_def_id);
2030 struct ImplVisitor<'tcx> {
2032 impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
2035 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
2036 fn visit_item(&mut self, item: &hir::Item<'_>) {
2037 if let hir::ItemKind::Impl { .. } = item.kind {
2038 if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) {
2039 let simplified_self_ty =
2040 ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
2043 .entry(trait_ref.def_id)
2045 .push((item.def_id.local_def_index, simplified_self_ty));
2050 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
2052 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
2053 // handled in `visit_item` above
2056 fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
2059 /// Used to prefetch queries which will be needed later by metadata encoding.
2060 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2061 fn prefetch_mir(tcx: TyCtxt<'_>) {
2062 if !tcx.sess.opts.output_types.should_codegen() {
2063 // We won't emit MIR, so don't prefetch it.
2067 par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2068 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2071 tcx.ensure().mir_for_ctfe(def_id);
2074 tcx.ensure().optimized_mir(def_id);
2076 if encode_opt || encode_const {
2077 tcx.ensure().promoted_mir(def_id);
2082 // NOTE(eddyb) The following comment was preserved for posterity, even
2083 // though it's no longer relevant as EBML (which uses nested & tagged
2084 // "documents") was replaced with a scheme that can't go out of bounds.
2086 // And here we run into yet another obscure archive bug: in which metadata
2087 // loaded from archives may have trailing garbage bytes. Awhile back one of
2088 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2089 // and opt) by having ebml generate an out-of-bounds panic when looking at
2092 // Upon investigation it turned out that the metadata file inside of an rlib
2093 // (and ar archive) was being corrupted. Some compilations would generate a
2094 // metadata file which would end in a few extra bytes, while other
2095 // compilations would not have these extra bytes appended to the end. These
2096 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2097 // being interpreted causing the out-of-bounds.
2099 // The root cause of why these extra bytes were appearing was never
2100 // discovered, and in the meantime the solution we're employing is to insert
2101 // the length of the metadata to the start of the metadata. Later on this
2102 // will allow us to slice the metadata to the precise length that we just
2103 // generated regardless of trailing bytes that end up in it.
2105 #[derive(Encodable, Decodable)]
2106 pub struct EncodedMetadata {
2110 impl EncodedMetadata {
2112 pub fn new() -> EncodedMetadata {
2113 EncodedMetadata { raw_data: Vec::new() }
2117 pub fn raw_data(&self) -> &[u8] {
2122 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2123 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2125 // Since encoding metadata is not in a query, and nothing is cached,
2126 // there's no need to do dep-graph tracking for any of it.
2127 tcx.dep_graph.assert_ignored();
2130 || encode_metadata_impl(tcx),
2132 if tcx.sess.threads() == 1 {
2135 // Prefetch some queries used by metadata encoding.
2136 // This is not necessary for correctness, but is only done for performance reasons.
2137 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2138 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2144 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2145 let mut encoder = opaque::Encoder::new(vec![]);
2146 encoder.emit_raw_bytes(METADATA_HEADER).unwrap();
2148 // Will be filled with the root position after encoding everything.
2149 encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap();
2151 let source_map_files = tcx.sess.source_map().files();
2152 let source_file_cache = (source_map_files[0].clone(), 0);
2153 let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2154 drop(source_map_files);
2156 let hygiene_ctxt = HygieneEncodeContext::default();
2158 let mut ecx = EncodeContext {
2161 feat: tcx.features(),
2162 tables: Default::default(),
2163 lazy_state: LazyState::NoNode,
2164 type_shorthands: Default::default(),
2165 predicate_shorthands: Default::default(),
2167 interpret_allocs: Default::default(),
2168 required_source_files,
2169 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2170 hygiene_ctxt: &hygiene_ctxt,
2173 // Encode the rustc version string in a predictable location.
2174 rustc_version().encode(&mut ecx).unwrap();
2176 // Encode all the entries and extra information in the crate,
2177 // culminating in the `CrateRoot` which points to all of it.
2178 let root = ecx.encode_crate_root();
2180 let mut result = ecx.opaque.into_inner();
2182 // Encode the root position.
2183 let header = METADATA_HEADER.len();
2184 let pos = root.position.get();
2185 result[header + 0] = (pos >> 24) as u8;
2186 result[header + 1] = (pos >> 16) as u8;
2187 result[header + 2] = (pos >> 8) as u8;
2188 result[header + 3] = (pos >> 0) as u8;
2190 EncodedMetadata { raw_data: result }