1 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
4 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
5 use rustc_data_structures::stable_hasher::StableHasher;
6 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
8 use rustc_hir::def::{CtorOf, DefKind};
9 use rustc_hir::def_id::{
10 CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
12 use rustc_hir::definitions::DefPathData;
13 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
15 use rustc_hir::lang_items;
16 use rustc_hir::{AnonConst, GenericParamKind};
17 use rustc_index::bit_set::GrowableBitSet;
18 use rustc_index::vec::Idx;
19 use rustc_middle::hir::map::Map;
20 use rustc_middle::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLib};
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_span::symbol::{sym, Ident, Symbol};
33 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
35 hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind},
38 use rustc_target::abi::VariantIdx;
40 use std::num::NonZeroUsize;
42 use tracing::{debug, trace};
44 pub(super) struct EncodeContext<'a, 'tcx> {
45 opaque: opaque::Encoder,
47 feat: &'tcx rustc_feature::Features,
49 tables: TableBuilders<'tcx>,
51 lazy_state: LazyState,
52 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
53 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
55 interpret_allocs: FxIndexSet<interpret::AllocId>,
57 // This is used to speed up Span encoding.
58 // The `usize` is an index into the `MonotonicVec`
59 // that stores the `SourceFile`
60 source_file_cache: (Lrc<SourceFile>, usize),
61 // The indices (into the `SourceMap`'s `MonotonicVec`)
62 // of all of the `SourceFiles` that we need to serialize.
63 // When we serialize a `Span`, we insert the index of its
64 // `SourceFile` into the `GrowableBitSet`.
66 // This needs to be a `GrowableBitSet` and not a
67 // regular `BitSet` because we may actually import new `SourceFiles`
68 // during metadata encoding, due to executing a query
69 // with a result containing a foreign `Span`.
70 required_source_files: Option<GrowableBitSet<usize>>,
72 hygiene_ctxt: &'a HygieneEncodeContext,
75 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
76 /// This is useful for skipping the encoding of things that aren't needed
77 /// for proc-macro crates.
78 macro_rules! empty_proc_macro {
80 if $self.is_proc_macro {
86 macro_rules! encoder_methods {
87 ($($name:ident($ty:ty);)*) => {
88 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
89 self.opaque.$name(value)
94 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
95 type Error = <opaque::Encoder as Encoder>::Error;
98 fn emit_unit(&mut self) -> Result<(), Self::Error> {
122 emit_raw_bytes(&[u8]);
126 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
129 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
130 e.emit_lazy_distance(*self)
134 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
137 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
138 e.emit_usize(self.meta)?;
142 e.emit_lazy_distance(*self)
146 impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
147 for Lazy<Table<I, T>>
149 Option<T>: FixedSizeEncoding,
151 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
152 e.emit_usize(self.meta)?;
153 e.emit_lazy_distance(*self)
157 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
158 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
159 if *self != LOCAL_CRATE && s.is_proc_macro {
160 panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
162 s.emit_u32(self.as_u32())
166 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
167 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
168 s.emit_u32(self.as_u32())
172 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
173 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
174 s.emit_u32(self.as_u32())
178 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
179 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
180 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
184 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
185 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
186 if self.krate == LOCAL_CRATE {
187 // We will only write details for local expansions. Non-local expansions will fetch
188 // data from the corresponding crate's metadata.
189 // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
190 // metadata from proc-macro crates.
191 s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
193 self.krate.encode(s)?;
194 self.local_id.encode(s)
198 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
199 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
200 let span = self.data();
202 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
203 // since we don't load proc-macro dependencies during serialization.
204 // This means that any hygiene information from macros used *within*
205 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
206 // definition) will be lost.
208 // This can show up in two ways:
210 // 1. Any hygiene information associated with identifier of
211 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
212 // Since proc-macros can only be invoked from a different crate,
213 // real code should never need to care about this.
215 // 2. Using `Span::def_site` or `Span::mixed_site` will not
216 // include any hygiene information associated with the definition
217 // site. This means that a proc-macro cannot emit a `$crate`
218 // identifier which resolves to one of its dependencies,
219 // which also should never come up in practice.
221 // Additionally, this affects `Span::parent`, and any other
222 // span inspection APIs that would otherwise allow traversing
223 // the `SyntaxContexts` associated with a span.
225 // None of these user-visible effects should result in any
226 // cross-crate inconsistencies (getting one behavior in the same
227 // crate, and a different behavior in another crate) due to the
228 // limited surface that proc-macros can expose.
230 // IMPORTANT: If this is ever changed, be sure to update
231 // `rustc_span::hygiene::raw_encode_expn_id` to handle
232 // encoding `ExpnData` for proc-macro crates.
234 SyntaxContext::root().encode(s)?;
236 span.ctxt.encode(s)?;
240 return TAG_PARTIAL_SPAN.encode(s);
243 // The Span infrastructure should make sure that this invariant holds:
244 debug_assert!(span.lo <= span.hi);
246 if !s.source_file_cache.0.contains(span.lo) {
247 let source_map = s.tcx.sess.source_map();
248 let source_file_index = source_map.lookup_source_file_idx(span.lo);
249 s.source_file_cache =
250 (source_map.files()[source_file_index].clone(), source_file_index);
253 if !s.source_file_cache.0.contains(span.hi) {
254 // Unfortunately, macro expansion still sometimes generates Spans
255 // that malformed in this way.
256 return TAG_PARTIAL_SPAN.encode(s);
259 let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
260 // Record the fact that we need to encode the data for this `SourceFile`
261 source_files.insert(s.source_file_cache.1);
263 // There are two possible cases here:
264 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
265 // crate we are writing metadata for. When the metadata for *this* crate gets
266 // deserialized, the deserializer will need to know which crate it originally came
267 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
268 // be deserialized after the rest of the span data, which tells the deserializer
269 // which crate contains the source map information.
270 // 2. This span comes from our own crate. No special hamdling is needed - we just
271 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
272 // our own source map information.
274 // If we're a proc-macro crate, we always treat this as a local `Span`.
275 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
276 // if we're a proc-macro crate.
277 // This allows us to avoid loading the dependencies of proc-macro crates: all of
278 // the information we need to decode `Span`s is stored in the proc-macro crate.
279 let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
280 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
281 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
282 // are relative to the source map information for the 'foreign' crate whose CrateNum
283 // we write into the metadata. This allows `imported_source_files` to binary
284 // search through the 'foreign' crate's source map information, using the
285 // deserialized 'lo' and 'hi' values directly.
287 // All of this logic ensures that the final result of deserialization is a 'normal'
288 // Span that can be used without any additional trouble.
289 let external_start_pos = {
290 // Introduce a new scope so that we drop the 'lock()' temporary
291 match &*s.source_file_cache.0.external_src.lock() {
292 ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
293 src => panic!("Unexpected external source {:?}", src),
296 let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
297 let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
299 (TAG_VALID_SPAN_FOREIGN, lo, hi)
301 (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
307 // Encode length which is usually less than span.hi and profits more
308 // from the variable-length integer encoding that we use.
312 if tag == TAG_VALID_SPAN_FOREIGN {
313 // This needs to be two lines to avoid holding the `s.source_file_cache`
314 // while calling `cnum.encode(s)`
315 let cnum = s.source_file_cache.0.cnum;
323 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
324 const CLEAR_CROSS_CRATE: bool = true;
326 fn position(&self) -> usize {
327 self.opaque.position()
330 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
331 &mut self.type_shorthands
334 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
335 &mut self.predicate_shorthands
340 alloc_id: &rustc_middle::mir::interpret::AllocId,
341 ) -> Result<(), Self::Error> {
342 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
348 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [thir::abstract_const::Node<'tcx>] {
349 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
354 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
355 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
360 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
361 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
362 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
365 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
366 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
367 self.encode(ecx).unwrap()
371 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
372 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
373 self.encode(ecx).unwrap()
377 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
380 I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
382 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
383 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
387 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
388 // normally need extra variables to avoid errors about multiple mutable borrows.
389 macro_rules! record {
390 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
393 let lazy = $self.lazy(value);
394 $self.$tables.$table.set($def_id.index, lazy);
399 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
400 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
403 ) -> Result<(), <Self as Encoder>::Error> {
404 let min_end = lazy.position.get() + T::min_size(lazy.meta);
405 let distance = match self.lazy_state {
406 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
407 LazyState::NodeStart(start) => {
408 let start = start.get();
409 assert!(min_end <= start);
412 LazyState::Previous(last_min_end) => {
414 last_min_end <= lazy.position,
415 "make sure that the calls to `lazy*` \
416 are in the same order as the metadata fields",
418 lazy.position.get() - last_min_end.get()
421 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
422 self.emit_usize(distance)
425 fn lazy<T: ?Sized + LazyMeta>(
427 value: impl EncodeContentsForLazy<'a, 'tcx, T>,
429 let pos = NonZeroUsize::new(self.position()).unwrap();
431 assert_eq!(self.lazy_state, LazyState::NoNode);
432 self.lazy_state = LazyState::NodeStart(pos);
433 let meta = value.encode_contents_for_lazy(self);
434 self.lazy_state = LazyState::NoNode;
436 assert!(pos.get() + <T>::min_size(meta) <= self.position());
438 Lazy::from_position_and_meta(pos, meta)
441 fn encode_info_for_items(&mut self) {
442 let krate = self.tcx.hir().krate();
443 self.encode_info_for_mod(CRATE_DEF_ID, krate.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 krate.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_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
476 let source_map = self.tcx.sess.source_map();
477 let all_source_files = source_map.files();
479 // By replacing the `Option` with `None`, we ensure that we can't
480 // accidentally serialize any more `Span`s after the source map encoding
482 let required_source_files = self.required_source_files.take().unwrap();
484 let adapted = all_source_files
487 .filter(|(idx, source_file)| {
488 // Only serialize `SourceFile`s that were used
489 // during the encoding of a `Span`
490 required_source_files.contains(*idx) &&
491 // Don't serialize imported `SourceFile`s, unless
492 // we're in a proc-macro crate.
493 (!source_file.is_imported() || self.is_proc_macro)
495 .map(|(_, source_file)| {
496 let mut adapted = match source_file.name {
497 FileName::Real(ref realname) => {
498 let mut adapted = (**source_file).clone();
499 adapted.name = FileName::Real(match realname {
500 RealFileName::LocalPath(path_to_file) => {
501 // Prepend path of working directory onto potentially
502 // relative paths, because they could become relative
503 // to a wrong directory.
504 // We include `working_dir` as part of the crate hash,
505 // so it's okay for us to use it as part of the encoded
507 let working_dir = &self.tcx.sess.opts.working_dir;
509 RealFileName::LocalPath(absolute) => {
510 // Although neither working_dir or the file name were subject
511 // to path remapping, the concatenation between the two may
512 // be. Hence we need to do a remapping here.
513 let joined = Path::new(absolute).join(path_to_file);
514 let (joined, remapped) =
515 source_map.path_mapping().map_prefix(joined);
517 RealFileName::Remapped {
519 virtual_name: joined,
522 RealFileName::LocalPath(joined)
525 RealFileName::Remapped { local_path: _, virtual_name } => {
526 // If working_dir has been remapped, then we emit
527 // Remapped variant as the expanded path won't be valid
528 RealFileName::Remapped {
530 virtual_name: Path::new(virtual_name)
536 RealFileName::Remapped { local_path: _, virtual_name } => {
537 RealFileName::Remapped {
538 // We do not want any local path to be exported into metadata
540 virtual_name: virtual_name.clone(),
544 adapted.name_hash = {
545 let mut hasher: StableHasher = StableHasher::new();
546 adapted.name.hash(&mut hasher);
547 hasher.finish::<u128>()
552 // expanded code, not from a file
553 _ => source_file.clone(),
556 // We're serializing this `SourceFile` into our crate metadata,
557 // so mark it as coming from this crate.
558 // This also ensures that we don't try to deserialize the
559 // `CrateNum` for a proc-macro dependency - since proc macro
560 // dependencies aren't loaded when we deserialize a proc-macro,
561 // trying to remap the `CrateNum` would fail.
562 if self.is_proc_macro {
563 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
567 .collect::<Vec<_>>();
569 self.lazy(adapted.iter().map(|rc| &**rc))
572 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
573 let mut i = self.position();
575 // Encode the crate deps
576 let crate_deps = self.encode_crate_deps();
577 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
578 let dep_bytes = self.position() - i;
580 // Encode the lib features.
582 let lib_features = self.encode_lib_features();
583 let lib_feature_bytes = self.position() - i;
585 // Encode the language items.
587 let lang_items = self.encode_lang_items();
588 let lang_items_missing = self.encode_lang_items_missing();
589 let lang_item_bytes = self.position() - i;
591 // Encode the diagnostic items.
593 let diagnostic_items = self.encode_diagnostic_items();
594 let diagnostic_item_bytes = self.position() - i;
596 // Encode the native libraries used
598 let native_libraries = self.encode_native_libraries();
599 let native_lib_bytes = self.position() - i;
601 let foreign_modules = self.encode_foreign_modules();
603 // Encode DefPathTable
605 self.encode_def_path_table();
606 let def_path_table_bytes = self.position() - i;
608 // Encode the def IDs of impls, for coherence checking.
610 let impls = self.encode_impls();
611 let impl_bytes = self.position() - i;
618 let mir_bytes = self.position() - i;
622 self.encode_def_ids();
623 self.encode_info_for_items();
624 let item_bytes = self.position() - i;
626 // Encode the allocation index
627 let interpret_alloc_index = {
628 let mut interpret_alloc_index = Vec::new();
630 trace!("beginning to encode alloc ids");
632 let new_n = self.interpret_allocs.len();
633 // if we have found new ids, serialize those, too
638 trace!("encoding {} further alloc ids", new_n - n);
639 for idx in n..new_n {
640 let id = self.interpret_allocs[idx];
641 let pos = self.position() as u32;
642 interpret_alloc_index.push(pos);
643 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
647 self.lazy(interpret_alloc_index)
650 // Encode the proc macro data. This affects 'tables',
651 // so we need to do this before we encode the tables
653 let proc_macro_data = self.encode_proc_macros();
654 let proc_macro_data_bytes = self.position() - i;
657 let tables = self.tables.encode(&mut self.opaque);
658 let tables_bytes = self.position() - i;
660 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
661 // this as late as possible to give the prefetching as much time as possible to complete.
663 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
664 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
665 let exported_symbols_bytes = self.position() - i;
667 // Encode the hygiene data,
668 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
669 // of encoding other items (e.g. `optimized_mir`) may cause us to load
670 // data from the incremental cache. If this causes us to deserialize a `Span`,
671 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
672 // Therefore, we need to encode the hygiene data last to ensure that we encode
673 // any `SyntaxContext`s that might be used.
675 let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene();
676 let hygiene_bytes = self.position() - i;
678 // Encode source_map. This needs to be done last,
679 // since encoding `Span`s tells us which `SourceFiles` we actually
682 let source_map = self.encode_source_map();
683 let source_map_bytes = self.position() - i;
685 let attrs = tcx.hir().krate_attrs();
686 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
688 let root = self.lazy(CrateRoot {
689 name: tcx.crate_name(LOCAL_CRATE),
690 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
691 triple: tcx.sess.opts.target_triple.clone(),
692 hash: tcx.crate_hash(LOCAL_CRATE),
693 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
694 panic_strategy: tcx.sess.panic_strategy(),
695 edition: tcx.sess.edition(),
696 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
697 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
698 has_default_lib_allocator,
700 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
701 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
702 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
703 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
704 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
705 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
706 symbol_mangling_version: tcx.sess.opts.debugging_opts.get_symbol_mangling_version(),
709 dylib_dependency_formats,
719 interpret_alloc_index,
726 let total_bytes = self.position();
728 if tcx.sess.meta_stats() {
729 let mut zero_bytes = 0;
730 for e in self.opaque.data.iter() {
736 eprintln!("metadata stats:");
737 eprintln!(" dep bytes: {}", dep_bytes);
738 eprintln!(" lib feature bytes: {}", lib_feature_bytes);
739 eprintln!(" lang item bytes: {}", lang_item_bytes);
740 eprintln!(" diagnostic item bytes: {}", diagnostic_item_bytes);
741 eprintln!(" native bytes: {}", native_lib_bytes);
742 eprintln!(" source_map bytes: {}", source_map_bytes);
743 eprintln!(" impl bytes: {}", impl_bytes);
744 eprintln!(" exp. symbols bytes: {}", exported_symbols_bytes);
745 eprintln!(" def-path table bytes: {}", def_path_table_bytes);
746 eprintln!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
747 eprintln!(" mir bytes: {}", mir_bytes);
748 eprintln!(" item bytes: {}", item_bytes);
749 eprintln!(" table bytes: {}", tables_bytes);
750 eprintln!(" hygiene bytes: {}", hygiene_bytes);
751 eprintln!(" zero bytes: {}", zero_bytes);
752 eprintln!(" total bytes: {}", total_bytes);
759 fn should_encode_visibility(def_kind: DefKind) -> bool {
769 | DefKind::TraitAlias
776 | DefKind::AssocConst
779 | DefKind::ForeignMod
782 | DefKind::Field => true,
784 | DefKind::ConstParam
785 | DefKind::LifetimeParam
790 | DefKind::ExternCrate => false,
794 fn should_encode_stability(def_kind: DefKind) -> bool {
803 | DefKind::AssocConst
805 | DefKind::ConstParam
809 | DefKind::ForeignMod
816 | DefKind::TraitAlias
818 | DefKind::ForeignTy => true,
820 | DefKind::LifetimeParam
825 | DefKind::ExternCrate => false,
829 /// Whether we should encode MIR.
831 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
832 /// We want to avoid this work when not required. Therefore:
833 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
834 /// - we skip `optimized_mir` for check runs.
836 /// Return a pair, resp. for CTFE and for LLVM.
837 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
838 match tcx.def_kind(def_id) {
840 DefKind::Ctor(_, _) => {
841 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
842 || tcx.sess.opts.debugging_opts.always_encode_mir;
846 DefKind::AnonConst | DefKind::AssocConst | DefKind::Static | DefKind::Const => {
849 // Full-fledged functions
850 DefKind::AssocFn | DefKind::Fn => {
851 let generics = tcx.generics_of(def_id);
852 let needs_inline = (generics.requires_monomorphization(tcx)
853 || tcx.codegen_fn_attrs(def_id).requests_inline())
854 && tcx.sess.opts.output_types.should_codegen();
855 // Only check the presence of the `const` modifier.
856 let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id());
857 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
858 (is_const_fn, needs_inline || always_encode_mir)
860 // Closures can't be const fn.
861 DefKind::Closure => {
862 let generics = tcx.generics_of(def_id);
863 let needs_inline = (generics.requires_monomorphization(tcx)
864 || tcx.codegen_fn_attrs(def_id).requests_inline())
865 && tcx.sess.opts.output_types.should_codegen();
866 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
867 (false, needs_inline || always_encode_mir)
869 // Generators require optimized MIR to compute layout.
870 DefKind::Generator => (false, true),
871 // The others don't have MIR.
876 fn should_encode_variances(def_kind: DefKind) -> bool {
884 | DefKind::AssocFn => true,
888 | DefKind::AssocConst
890 | DefKind::ConstParam
893 | DefKind::ForeignMod
898 | DefKind::TraitAlias
902 | DefKind::LifetimeParam
907 | DefKind::ExternCrate => false,
911 fn should_encode_generics(def_kind: DefKind) -> bool {
920 | DefKind::TraitAlias
927 | DefKind::AssocConst
934 | DefKind::Generator => true,
936 | DefKind::ForeignMod
937 | DefKind::ConstParam
940 | DefKind::LifetimeParam
942 | DefKind::ExternCrate => false,
946 impl EncodeContext<'a, 'tcx> {
947 fn encode_def_ids(&mut self) {
948 if self.is_proc_macro {
953 for local_id in hir.iter_local_def_id() {
954 let def_id = local_id.to_def_id();
955 let def_kind = tcx.opt_def_kind(local_id);
956 let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue };
957 record!(self.tables.def_kind[def_id] <- match def_kind {
958 // Replace Ctor by the enclosing object to avoid leaking details in children crates.
959 DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct,
960 DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant,
961 def_kind => def_kind,
963 record!(self.tables.span[def_id] <- tcx.def_span(def_id));
964 record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id));
965 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
966 if should_encode_visibility(def_kind) {
967 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
969 if should_encode_stability(def_kind) {
970 self.encode_stability(def_id);
971 self.encode_const_stability(def_id);
972 self.encode_deprecation(def_id);
974 if should_encode_variances(def_kind) {
975 let v = self.tcx.variances_of(def_id);
976 record!(self.tables.variances[def_id] <- v);
978 if should_encode_generics(def_kind) {
979 let g = tcx.generics_of(def_id);
980 record!(self.tables.generics[def_id] <- g);
981 record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id));
982 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
983 if !inferred_outlives.is_empty() {
984 record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
987 if let DefKind::Trait | DefKind::TraitAlias = def_kind {
988 record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
991 let inherent_impls = tcx.crate_inherent_impls(());
992 for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
993 if implementations.is_empty() {
996 record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
997 assert!(def_id.is_local());
1003 fn encode_item_type(&mut self, def_id: DefId) {
1004 debug!("EncodeContext::encode_item_type({:?})", def_id);
1005 record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
1008 fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
1010 let variant = &def.variants[index];
1011 let def_id = variant.def_id;
1012 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1014 let data = VariantData {
1015 ctor_kind: variant.ctor_kind,
1016 discr: variant.discr,
1017 ctor: variant.ctor_def_id.map(|did| did.index),
1018 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1021 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1022 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1023 assert!(f.did.is_local());
1026 self.encode_ident_span(def_id, variant.ident);
1027 self.encode_item_type(def_id);
1028 if variant.ctor_kind == CtorKind::Fn {
1029 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1030 if let Some(ctor_def_id) = variant.ctor_def_id {
1031 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1036 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
1038 let variant = &def.variants[index];
1039 let def_id = variant.ctor_def_id.unwrap();
1040 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1042 // FIXME(eddyb) encode only the `CtorKind` for constructors.
1043 let data = VariantData {
1044 ctor_kind: variant.ctor_kind,
1045 discr: variant.discr,
1046 ctor: Some(def_id.index),
1047 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1050 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1051 self.encode_item_type(def_id);
1052 if variant.ctor_kind == CtorKind::Fn {
1053 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1057 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1059 let def_id = local_def_id.to_def_id();
1060 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1062 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1063 // only ever get called for the crate root. We still want to encode
1064 // the crate root for consistency with other crates (some of the resolver
1065 // code uses it). However, we skip encoding anything relating to child
1066 // items - we encode information about proc-macros later on.
1067 let reexports = if !self.is_proc_macro {
1068 match tcx.module_exports(local_def_id) {
1069 Some(exports) => self.lazy(exports),
1076 let data = ModData { reexports, expansion: tcx.expn_that_defined(local_def_id) };
1078 record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
1079 if self.is_proc_macro {
1080 record!(self.tables.children[def_id] <- &[]);
1082 record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
1083 item_id.def_id.local_def_index
1090 adt_def: &ty::AdtDef,
1091 variant_index: VariantIdx,
1094 let variant = &adt_def.variants[variant_index];
1095 let field = &variant.fields[field_index];
1097 let def_id = field.did;
1098 debug!("EncodeContext::encode_field({:?})", def_id);
1100 record!(self.tables.kind[def_id] <- EntryKind::Field);
1101 self.encode_ident_span(def_id, field.ident);
1102 self.encode_item_type(def_id);
1105 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
1106 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1108 let variant = adt_def.non_enum_variant();
1110 let data = VariantData {
1111 ctor_kind: variant.ctor_kind,
1112 discr: variant.discr,
1113 ctor: Some(def_id.index),
1114 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1117 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
1118 self.encode_item_type(def_id);
1119 if variant.ctor_kind == CtorKind::Fn {
1120 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1124 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1125 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1126 let bounds = self.tcx.explicit_item_bounds(def_id);
1127 if !bounds.is_empty() {
1128 record!(self.tables.explicit_item_bounds[def_id] <- bounds);
1132 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1133 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1136 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1137 let ast_item = tcx.hir().expect_trait_item(hir_id);
1138 let trait_item = tcx.associated_item(def_id);
1140 let container = match trait_item.defaultness {
1141 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
1142 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
1143 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
1146 match trait_item.kind {
1147 ty::AssocKind::Const => {
1148 let rendered = rustc_hir_pretty::to_string(
1149 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
1150 |s| s.print_trait_item(ast_item),
1152 let rendered_const = self.lazy(RenderedConst(rendered));
1154 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(
1160 ty::AssocKind::Fn => {
1161 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
1162 let param_names = match *m {
1163 hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names),
1164 hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body),
1167 asyncness: m_sig.header.asyncness,
1168 constness: hir::Constness::NotConst,
1174 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1177 has_self: trait_item.fn_has_self_parameter,
1180 ty::AssocKind::Type => {
1181 self.encode_explicit_item_bounds(def_id);
1182 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1185 self.encode_ident_span(def_id, ast_item.ident);
1186 match trait_item.kind {
1187 ty::AssocKind::Const | ty::AssocKind::Fn => {
1188 self.encode_item_type(def_id);
1190 ty::AssocKind::Type => {
1191 if trait_item.defaultness.has_value() {
1192 self.encode_item_type(def_id);
1196 if trait_item.kind == ty::AssocKind::Fn {
1197 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1201 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1202 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1205 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1206 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1207 let impl_item = self.tcx.associated_item(def_id);
1209 let container = match impl_item.defaultness {
1210 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1211 hir::Defaultness::Final => AssocContainer::ImplFinal,
1212 hir::Defaultness::Default { has_value: false } => {
1213 span_bug!(ast_item.span, "impl items always have values (currently)")
1217 match impl_item.kind {
1218 ty::AssocKind::Const => {
1219 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1220 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1222 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(
1225 self.encode_rendered_const_for_body(body_id))
1231 ty::AssocKind::Fn => {
1232 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1234 asyncness: sig.header.asyncness,
1235 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1236 constness: if self.tcx.is_const_fn_raw(def_id) {
1237 hir::Constness::Const
1239 hir::Constness::NotConst
1241 param_names: self.encode_fn_param_names_for_body(body),
1246 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1249 has_self: impl_item.fn_has_self_parameter,
1252 ty::AssocKind::Type => {
1253 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1256 self.encode_ident_span(def_id, impl_item.ident);
1257 self.encode_item_type(def_id);
1258 if impl_item.kind == ty::AssocKind::Fn {
1259 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1263 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1264 self.lazy(self.tcx.hir().body_param_names(body_id))
1267 fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1268 self.lazy(param_names.iter())
1271 fn encode_mir(&mut self) {
1272 if self.is_proc_macro {
1276 let mut keys_and_jobs = self
1280 .filter_map(|&def_id| {
1281 let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id);
1282 if encode_const || encode_opt {
1283 Some((def_id, encode_const, encode_opt))
1288 .collect::<Vec<_>>();
1289 // Sort everything to ensure a stable order for diagnotics.
1290 keys_and_jobs.sort_by_key(|&(def_id, _, _)| def_id);
1291 for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() {
1292 debug_assert!(encode_const || encode_opt);
1294 debug!("EntryBuilder::encode_mir({:?})", def_id);
1296 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1299 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id));
1301 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1302 let abstract_const = self.tcx.thir_abstract_const(def_id);
1303 if let Ok(Some(abstract_const)) = abstract_const {
1304 record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const);
1307 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1309 let unused = self.tcx.unused_generic_params(def_id);
1310 if !unused.is_empty() {
1311 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1316 fn encode_stability(&mut self, def_id: DefId) {
1317 debug!("EncodeContext::encode_stability({:?})", def_id);
1319 // The query lookup can take a measurable amount of time in crates with many items. Check if
1320 // the stability attributes are even enabled before using their queries.
1321 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1322 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1323 record!(self.tables.stability[def_id] <- stab)
1328 fn encode_const_stability(&mut self, def_id: DefId) {
1329 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1331 // The query lookup can take a measurable amount of time in crates with many items. Check if
1332 // the stability attributes are even enabled before using their queries.
1333 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1334 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1335 record!(self.tables.const_stability[def_id] <- stab)
1340 fn encode_deprecation(&mut self, def_id: DefId) {
1341 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1342 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1343 record!(self.tables.deprecation[def_id] <- depr);
1347 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1348 let hir = self.tcx.hir();
1349 let body = hir.body(body_id);
1350 let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1351 s.print_expr(&body.value)
1353 let rendered_const = &RenderedConst(rendered);
1354 self.lazy(rendered_const)
1357 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1360 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1362 self.encode_ident_span(def_id, item.ident);
1364 let entry_kind = match item.kind {
1365 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1366 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1367 hir::ItemKind::Const(_, body_id) => {
1368 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1369 EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id))
1371 hir::ItemKind::Fn(ref sig, .., body) => {
1373 asyncness: sig.header.asyncness,
1374 constness: sig.header.constness,
1375 param_names: self.encode_fn_param_names_for_body(body),
1378 EntryKind::Fn(self.lazy(data))
1380 hir::ItemKind::Macro(ref macro_def) => {
1381 EntryKind::MacroDef(self.lazy(macro_def.clone()))
1383 hir::ItemKind::Mod(ref m) => {
1384 return self.encode_info_for_mod(item.def_id, m);
1386 hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1387 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1388 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1389 hir::ItemKind::OpaqueTy(..) => {
1390 self.encode_explicit_item_bounds(def_id);
1393 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1394 hir::ItemKind::Struct(ref struct_def, _) => {
1395 let adt_def = self.tcx.adt_def(def_id);
1396 let variant = adt_def.non_enum_variant();
1398 // Encode def_ids for each field and method
1399 // for methods, write all the stuff get_trait_method
1401 let ctor = struct_def
1403 .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1406 self.lazy(VariantData {
1407 ctor_kind: variant.ctor_kind,
1408 discr: variant.discr,
1410 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1415 hir::ItemKind::Union(..) => {
1416 let adt_def = self.tcx.adt_def(def_id);
1417 let variant = adt_def.non_enum_variant();
1420 self.lazy(VariantData {
1421 ctor_kind: variant.ctor_kind,
1422 discr: variant.discr,
1424 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1429 hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1430 let trait_ref = self.tcx.impl_trait_ref(def_id);
1431 let polarity = self.tcx.impl_polarity(def_id);
1432 let parent = if let Some(trait_ref) = trait_ref {
1433 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1434 trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| {
1435 an.nth(1).and_then(|node| match node {
1436 specialization_graph::Node::Impl(parent) => Some(parent),
1444 // if this is an impl of `CoerceUnsized`, create its
1445 // "unsized info", else just store None
1446 let coerce_unsized_info = trait_ref.and_then(|t| {
1447 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1448 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1454 let data = ImplData {
1458 parent_impl: parent,
1459 coerce_unsized_info,
1462 EntryKind::Impl(self.lazy(data))
1464 hir::ItemKind::Trait(..) => {
1465 let trait_def = self.tcx.trait_def(def_id);
1466 let data = TraitData {
1467 unsafety: trait_def.unsafety,
1468 paren_sugar: trait_def.paren_sugar,
1469 has_auto_impl: self.tcx.trait_is_auto(def_id),
1470 is_marker: trait_def.is_marker,
1471 skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch,
1472 specialization_kind: trait_def.specialization_kind,
1475 EntryKind::Trait(self.lazy(data))
1477 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1478 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1479 bug!("cannot encode info for item {:?}", item)
1482 record!(self.tables.kind[def_id] <- entry_kind);
1483 // FIXME(eddyb) there should be a nicer way to do this.
1485 hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <-
1488 .map(|foreign_item| foreign_item.id.def_id.local_def_index)
1490 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1491 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1492 assert!(v.def_id.is_local());
1496 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1497 record!(self.tables.children[def_id] <-
1498 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1499 assert!(f.did.is_local());
1504 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1505 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1506 record!(self.tables.children[def_id] <-
1507 associated_item_def_ids.iter().map(|&def_id| {
1508 assert!(def_id.is_local());
1516 hir::ItemKind::Static(..)
1517 | hir::ItemKind::Const(..)
1518 | hir::ItemKind::Fn(..)
1519 | hir::ItemKind::TyAlias(..)
1520 | hir::ItemKind::OpaqueTy(..)
1521 | hir::ItemKind::Enum(..)
1522 | hir::ItemKind::Struct(..)
1523 | hir::ItemKind::Union(..)
1524 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1527 if let hir::ItemKind::Fn(..) = item.kind {
1528 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1530 if let hir::ItemKind::Impl { .. } = item.kind {
1531 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1532 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1537 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1538 record!(self.tables.kind[def_id] <- kind);
1540 self.encode_item_type(def_id);
1544 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1545 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1547 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1548 // including on the signature, which is inferred in `typeck.
1549 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1550 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1553 ty::Generator(..) => {
1554 let data = self.tcx.generator_kind(def_id).unwrap();
1555 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data));
1558 ty::Closure(..) => {
1559 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1562 _ => bug!("closure that is neither generator nor closure"),
1564 self.encode_item_type(def_id.to_def_id());
1565 if let ty::Closure(def_id, substs) = *ty.kind() {
1566 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1570 fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1571 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1572 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1573 let body_id = self.tcx.hir().body_owned_by(id);
1574 let const_data = self.encode_rendered_const_for_body(body_id);
1575 let qualifs = self.tcx.mir_const_qualif(def_id);
1577 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1578 self.encode_item_type(def_id.to_def_id());
1581 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1582 empty_proc_macro!(self);
1583 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1584 self.lazy(used_libraries.iter())
1587 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1588 empty_proc_macro!(self);
1589 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1590 self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1593 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1594 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1595 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1596 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1598 let _: Result<(), !> = self.hygiene_ctxt.encode(
1599 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1600 |(this, syntax_contexts, _, _), index, ctxt_data| {
1601 syntax_contexts.set(index, this.lazy(ctxt_data));
1604 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1605 if let Some(index) = index.as_local() {
1606 expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1607 expn_hash_table.set(index.as_raw(), this.lazy(hash));
1614 syntax_contexts.encode(&mut self.opaque),
1615 expn_data_table.encode(&mut self.opaque),
1616 expn_hash_table.encode(&mut self.opaque),
1620 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1621 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1624 let hir = tcx.hir();
1626 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1627 let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1629 self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1630 let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1631 for (i, span) in spans.into_iter().enumerate() {
1632 let span = self.lazy(span);
1633 self.tables.proc_macro_quoted_spans.set(i, span);
1636 record!(self.tables.def_kind[LOCAL_CRATE.as_def_id()] <- DefKind::Mod);
1637 record!(self.tables.span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1638 record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id()));
1639 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1640 if let Some(stability) = stability {
1641 record!(self.tables.stability[LOCAL_CRATE.as_def_id()] <- stability);
1643 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1645 // Normally, this information is encoded when we walk the items
1646 // defined in this crate. However, we skip doing that for proc-macro crates,
1647 // so we manually encode just the information that we need
1648 for &proc_macro in &tcx.resolutions(()).proc_macros {
1649 let id = proc_macro;
1650 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1651 let mut name = hir.name(proc_macro);
1652 let span = hir.span(proc_macro);
1653 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1654 // so downstream crates need access to them.
1655 let attrs = hir.attrs(proc_macro);
1656 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1658 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1660 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1661 // This unwrap chain should have been checked by the proc-macro harness.
1662 name = attr.meta_item_list().unwrap()[0]
1670 bug!("Unknown proc-macro type for item {:?}", id);
1673 let mut def_key = self.tcx.hir().def_key(id);
1674 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1676 let def_id = id.to_def_id();
1677 record!(self.tables.def_kind[def_id] <- DefKind::Macro(macro_kind));
1678 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1679 record!(self.tables.attributes[def_id] <- attrs);
1680 record!(self.tables.def_keys[def_id] <- def_key);
1681 record!(self.tables.ident_span[def_id] <- span);
1682 record!(self.tables.span[def_id] <- span);
1683 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1684 if let Some(stability) = stability {
1685 record!(self.tables.stability[def_id] <- stability);
1689 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1695 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1696 empty_proc_macro!(self);
1697 let crates = self.tcx.crates(());
1699 let mut deps = crates
1702 let dep = CrateDep {
1703 name: self.tcx.crate_name(cnum),
1704 hash: self.tcx.crate_hash(cnum),
1705 host_hash: self.tcx.crate_host_hash(cnum),
1706 kind: self.tcx.dep_kind(cnum),
1707 extra_filename: self.tcx.extra_filename(cnum),
1711 .collect::<Vec<_>>();
1713 deps.sort_by_key(|&(cnum, _)| cnum);
1716 // Sanity-check the crate numbers
1717 let mut expected_cnum = 1;
1718 for &(n, _) in &deps {
1719 assert_eq!(n, CrateNum::new(expected_cnum));
1724 // We're just going to write a list of crate 'name-hash-version's, with
1725 // the assumption that they are numbered 1 to n.
1726 // FIXME (#2166): This is not nearly enough to support correct versioning
1727 // but is enough to get transitive crate dependencies working.
1728 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1731 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1732 empty_proc_macro!(self);
1734 let lib_features = tcx.lib_features();
1735 self.lazy(lib_features.to_vec())
1738 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1739 empty_proc_macro!(self);
1741 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1742 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1745 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1746 empty_proc_macro!(self);
1748 let lang_items = tcx.lang_items();
1749 let lang_items = lang_items.items().iter();
1750 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1751 if let Some(def_id) = opt_def_id {
1752 if def_id.is_local() {
1753 return Some((def_id.index, i));
1760 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1761 empty_proc_macro!(self);
1763 self.lazy(&tcx.lang_items().missing)
1766 /// Encodes an index, mapping each trait to its (local) implementations.
1767 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1768 empty_proc_macro!(self);
1769 debug!("EncodeContext::encode_impls()");
1771 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1772 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1774 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1776 // Bring everything into deterministic order for hashing
1777 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1779 let all_impls: Vec<_> = all_impls
1781 .map(|(trait_def_id, mut impls)| {
1782 // Bring everything into deterministic order for hashing
1783 impls.sort_by_cached_key(|&(index, _)| {
1784 tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1788 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1789 impls: self.lazy(&impls),
1794 self.lazy(&all_impls)
1797 // Encodes all symbols exported from this crate into the metadata.
1799 // This pass is seeded off the reachability list calculated in the
1800 // middle::reachable module but filters out items that either don't have a
1801 // symbol associated with them (they weren't translated) or if they're an FFI
1802 // definition (as that's not defined in this crate).
1803 fn encode_exported_symbols(
1805 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1806 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1807 empty_proc_macro!(self);
1808 // The metadata symbol name is special. It should not show up in
1809 // downstream crates.
1810 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1815 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1816 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1823 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1824 empty_proc_macro!(self);
1825 let formats = self.tcx.dependency_formats(());
1826 for (ty, arr) in formats.iter() {
1827 if *ty != CrateType::Dylib {
1830 return self.lazy(arr.iter().map(|slot| match *slot {
1831 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1833 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1834 Linkage::Static => Some(LinkagePreference::RequireStatic),
1840 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1843 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1846 hir::ForeignItemKind::Fn(_, ref names, _) => {
1848 asyncness: hir::IsAsync::NotAsync,
1849 constness: if self.tcx.is_const_fn_raw(def_id) {
1850 hir::Constness::Const
1852 hir::Constness::NotConst
1854 param_names: self.encode_fn_param_names(names),
1856 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn(self.lazy(data)));
1858 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => {
1859 record!(self.tables.kind[def_id] <- EntryKind::ForeignMutStatic);
1861 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => {
1862 record!(self.tables.kind[def_id] <- EntryKind::ForeignImmStatic);
1864 hir::ForeignItemKind::Type => {
1865 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
1868 self.encode_ident_span(def_id, nitem.ident);
1869 self.encode_item_type(def_id);
1870 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1871 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1876 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1877 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1878 type Map = Map<'tcx>;
1880 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1881 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1883 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1884 intravisit::walk_expr(self, ex);
1885 self.encode_info_for_expr(ex);
1887 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1888 intravisit::walk_anon_const(self, c);
1889 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1890 self.encode_info_for_anon_const(def_id);
1892 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1893 intravisit::walk_item(self, item);
1895 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1896 _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
1898 self.encode_addl_info_for_item(item);
1900 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1901 intravisit::walk_foreign_item(self, ni);
1902 self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
1904 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1905 intravisit::walk_generics(self, generics);
1906 self.encode_info_for_generics(generics);
1910 impl EncodeContext<'a, 'tcx> {
1911 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1912 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1913 for (field_index, _field) in variant.fields.iter().enumerate() {
1914 self.encode_field(adt_def, variant_index, field_index);
1919 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1920 for param in generics.params {
1921 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1923 GenericParamKind::Lifetime { .. } => continue,
1924 GenericParamKind::Type { default, .. } => {
1925 self.encode_info_for_generic_param(
1927 EntryKind::TypeParam,
1931 GenericParamKind::Const { ref default, .. } => {
1932 let def_id = def_id.to_def_id();
1933 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1934 if default.is_some() {
1935 record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id))
1942 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1943 if let hir::ExprKind::Closure(..) = expr.kind {
1944 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1945 self.encode_info_for_closure(def_id);
1949 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1950 record!(self.tables.ident_span[def_id] <- ident.span);
1953 /// In some cases, along with the item itself, we also
1954 /// encode some sub-items. Usually we want some info from the item
1955 /// so it's easier to do that here then to wait until we would encounter
1956 /// normally in the visitor walk.
1957 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1959 hir::ItemKind::Static(..)
1960 | hir::ItemKind::Const(..)
1961 | hir::ItemKind::Fn(..)
1962 | hir::ItemKind::Macro(..)
1963 | hir::ItemKind::Mod(..)
1964 | hir::ItemKind::ForeignMod { .. }
1965 | hir::ItemKind::GlobalAsm(..)
1966 | hir::ItemKind::ExternCrate(..)
1967 | hir::ItemKind::Use(..)
1968 | hir::ItemKind::TyAlias(..)
1969 | hir::ItemKind::OpaqueTy(..)
1970 | hir::ItemKind::TraitAlias(..) => {
1971 // no sub-item recording needed in these cases
1973 hir::ItemKind::Enum(..) => {
1974 let def = self.tcx.adt_def(item.def_id.to_def_id());
1975 self.encode_fields(def);
1977 for (i, variant) in def.variants.iter_enumerated() {
1978 self.encode_enum_variant_info(def, i);
1980 if let Some(_ctor_def_id) = variant.ctor_def_id {
1981 self.encode_enum_variant_ctor(def, i);
1985 hir::ItemKind::Struct(ref struct_def, _) => {
1986 let def = self.tcx.adt_def(item.def_id.to_def_id());
1987 self.encode_fields(def);
1989 // If the struct has a constructor, encode it.
1990 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1991 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1992 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1995 hir::ItemKind::Union(..) => {
1996 let def = self.tcx.adt_def(item.def_id.to_def_id());
1997 self.encode_fields(def);
1999 hir::ItemKind::Impl { .. } => {
2000 for &trait_item_def_id in
2001 self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2003 self.encode_info_for_impl_item(trait_item_def_id);
2006 hir::ItemKind::Trait(..) => {
2007 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2009 self.encode_info_for_trait_item(item_def_id);
2016 struct ImplVisitor<'tcx> {
2018 impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
2021 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
2022 fn visit_item(&mut self, item: &hir::Item<'_>) {
2023 if let hir::ItemKind::Impl { .. } = item.kind {
2024 if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) {
2025 let simplified_self_ty =
2026 ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
2029 .entry(trait_ref.def_id)
2031 .push((item.def_id.local_def_index, simplified_self_ty));
2036 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
2038 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
2039 // handled in `visit_item` above
2042 fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
2045 /// Used to prefetch queries which will be needed later by metadata encoding.
2046 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2047 fn prefetch_mir(tcx: TyCtxt<'_>) {
2048 if !tcx.sess.opts.output_types.should_codegen() {
2049 // We won't emit MIR, so don't prefetch it.
2053 par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2054 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2057 tcx.ensure().mir_for_ctfe(def_id);
2060 tcx.ensure().optimized_mir(def_id);
2062 if encode_opt || encode_const {
2063 tcx.ensure().promoted_mir(def_id);
2068 // NOTE(eddyb) The following comment was preserved for posterity, even
2069 // though it's no longer relevant as EBML (which uses nested & tagged
2070 // "documents") was replaced with a scheme that can't go out of bounds.
2072 // And here we run into yet another obscure archive bug: in which metadata
2073 // loaded from archives may have trailing garbage bytes. Awhile back one of
2074 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2075 // and opt) by having ebml generate an out-of-bounds panic when looking at
2078 // Upon investigation it turned out that the metadata file inside of an rlib
2079 // (and ar archive) was being corrupted. Some compilations would generate a
2080 // metadata file which would end in a few extra bytes, while other
2081 // compilations would not have these extra bytes appended to the end. These
2082 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2083 // being interpreted causing the out-of-bounds.
2085 // The root cause of why these extra bytes were appearing was never
2086 // discovered, and in the meantime the solution we're employing is to insert
2087 // the length of the metadata to the start of the metadata. Later on this
2088 // will allow us to slice the metadata to the precise length that we just
2089 // generated regardless of trailing bytes that end up in it.
2091 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2092 // Since encoding metadata is not in a query, and nothing is cached,
2093 // there's no need to do dep-graph tracking for any of it.
2094 tcx.dep_graph.assert_ignored();
2097 || encode_metadata_impl(tcx),
2099 if tcx.sess.threads() == 1 {
2102 // Prefetch some queries used by metadata encoding.
2103 // This is not necessary for correctness, but is only done for performance reasons.
2104 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2105 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2111 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2112 let mut encoder = opaque::Encoder::new(vec![]);
2113 encoder.emit_raw_bytes(METADATA_HEADER).unwrap();
2115 // Will be filled with the root position after encoding everything.
2116 encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap();
2118 let source_map_files = tcx.sess.source_map().files();
2119 let source_file_cache = (source_map_files[0].clone(), 0);
2120 let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2121 drop(source_map_files);
2123 let hygiene_ctxt = HygieneEncodeContext::default();
2125 let mut ecx = EncodeContext {
2128 feat: tcx.features(),
2129 tables: Default::default(),
2130 lazy_state: LazyState::NoNode,
2131 type_shorthands: Default::default(),
2132 predicate_shorthands: Default::default(),
2134 interpret_allocs: Default::default(),
2135 required_source_files,
2136 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2137 hygiene_ctxt: &hygiene_ctxt,
2140 // Encode the rustc version string in a predictable location.
2141 rustc_version().encode(&mut ecx).unwrap();
2143 // Encode all the entries and extra information in the crate,
2144 // culminating in the `CrateRoot` which points to all of it.
2145 let root = ecx.encode_crate_root();
2147 let mut result = ecx.opaque.into_inner();
2149 // Encode the root position.
2150 let header = METADATA_HEADER.len();
2151 let pos = root.position.get();
2152 result[header + 0] = (pos >> 24) as u8;
2153 result[header + 1] = (pos >> 16) as u8;
2154 result[header + 2] = (pos >> 8) as u8;
2155 result[header + 3] = (pos >> 0) as u8;
2157 EncodedMetadata { raw_data: result }