2 use crate::rmeta::table::{FixedSizeEncoding, PerDefTable};
4 use rustc::middle::cstore::{LinkagePreference, NativeLibrary,
5 EncodedMetadata, ForeignModule};
6 use rustc::hir::def::CtorKind;
7 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
8 use rustc::hir::{GenericParamKind, AnonConst};
9 use rustc::hir::map::definitions::DefPathTable;
10 use rustc_data_structures::fingerprint::Fingerprint;
11 use rustc_index::vec::IndexVec;
12 use rustc::middle::dependency_format::Linkage;
13 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel,
14 metadata_symbol_name};
15 use rustc::middle::lang_items;
16 use rustc::mir::{self, interpret};
17 use rustc::traits::specialization_graph;
18 use rustc::ty::{self, Ty, TyCtxt, SymbolName};
19 use rustc::ty::codec::{self as ty_codec, TyEncoder};
20 use rustc::ty::layout::VariantIdx;
22 use rustc::session::config::{self, CrateType};
23 use rustc::util::nodemap::FxHashMap;
25 use rustc_data_structures::stable_hasher::StableHasher;
26 use rustc_data_structures::sync::Lrc;
27 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
30 use std::num::NonZeroUsize;
35 use syntax::expand::is_proc_macro_attr;
36 use syntax::source_map::Spanned;
37 use syntax::symbol::{kw, sym, Ident, Symbol};
38 use syntax_pos::{self, FileName, SourceFile, Span};
39 use log::{debug, trace};
41 use rustc::hir::{self, PatKind};
42 use rustc::hir::itemlikevisit::ItemLikeVisitor;
43 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
44 use rustc::hir::intravisit;
46 struct EncodeContext<'tcx> {
47 opaque: opaque::Encoder,
50 per_def: PerDefTables<'tcx>,
52 lazy_state: LazyState,
53 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
54 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
56 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
57 interpret_allocs_inverse: Vec<interpret::AllocId>,
59 // This is used to speed up Span encoding.
60 source_file_cache: Lrc<SourceFile>,
64 struct PerDefTables<'tcx> {
65 kind: PerDefTable<Lazy<EntryKind<'tcx>>>,
66 visibility: PerDefTable<Lazy<ty::Visibility>>,
67 span: PerDefTable<Lazy<Span>>,
68 attributes: PerDefTable<Lazy<[ast::Attribute]>>,
69 children: PerDefTable<Lazy<[DefIndex]>>,
70 stability: PerDefTable<Lazy<attr::Stability>>,
71 deprecation: PerDefTable<Lazy<attr::Deprecation>>,
73 ty: PerDefTable<Lazy<Ty<'tcx>>>,
74 fn_sig: PerDefTable<Lazy<ty::PolyFnSig<'tcx>>>,
75 impl_trait_ref: PerDefTable<Lazy<ty::TraitRef<'tcx>>>,
76 inherent_impls: PerDefTable<Lazy<[DefIndex]>>,
77 variances: PerDefTable<Lazy<[ty::Variance]>>,
78 generics: PerDefTable<Lazy<ty::Generics>>,
79 explicit_predicates: PerDefTable<Lazy<ty::GenericPredicates<'tcx>>>,
80 inferred_outlives: PerDefTable<Lazy<&'tcx [(ty::Predicate<'tcx>, Span)]>>,
81 super_predicates: PerDefTable<Lazy<ty::GenericPredicates<'tcx>>>,
83 mir: PerDefTable<Lazy<mir::Body<'tcx>>>,
84 promoted_mir: PerDefTable<Lazy<IndexVec<mir::Promoted, mir::Body<'tcx>>>>,
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<'tcx> Encoder for EncodeContext<'tcx> {
96 type Error = <opaque::Encoder as Encoder>::Error;
98 fn emit_unit(&mut self) -> Result<(), Self::Error> {
125 impl<'tcx, T: Encodable> SpecializedEncoder<Lazy<T>> for EncodeContext<'tcx> {
126 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
127 self.emit_lazy_distance(*lazy)
131 impl<'tcx, T: Encodable> SpecializedEncoder<Lazy<[T]>> for EncodeContext<'tcx> {
132 fn specialized_encode(&mut self, lazy: &Lazy<[T]>) -> Result<(), Self::Error> {
133 self.emit_usize(lazy.meta)?;
137 self.emit_lazy_distance(*lazy)
141 impl<'tcx, T> SpecializedEncoder<Lazy<PerDefTable<T>>> for EncodeContext<'tcx>
142 where Option<T>: FixedSizeEncoding,
144 fn specialized_encode(&mut self, lazy: &Lazy<PerDefTable<T>>) -> Result<(), Self::Error> {
145 self.emit_usize(lazy.meta)?;
146 self.emit_lazy_distance(*lazy)
150 impl<'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'tcx> {
152 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
153 self.emit_u32(cnum.as_u32())
157 impl<'tcx> SpecializedEncoder<DefId> for EncodeContext<'tcx> {
159 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
170 impl<'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'tcx> {
172 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
173 self.emit_u32(def_index.as_u32())
177 impl<'tcx> SpecializedEncoder<Span> for EncodeContext<'tcx> {
178 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
180 return TAG_INVALID_SPAN.encode(self)
183 let span = span.data();
185 // The Span infrastructure should make sure that this invariant holds:
186 debug_assert!(span.lo <= span.hi);
188 if !self.source_file_cache.contains(span.lo) {
189 let source_map = self.tcx.sess.source_map();
190 let source_file_index = source_map.lookup_source_file_idx(span.lo);
191 self.source_file_cache = source_map.files()[source_file_index].clone();
194 if !self.source_file_cache.contains(span.hi) {
195 // Unfortunately, macro expansion still sometimes generates Spans
196 // that malformed in this way.
197 return TAG_INVALID_SPAN.encode(self)
200 // HACK(eddyb) there's no way to indicate which crate a Span is coming
201 // from right now, so decoding would fail to find the SourceFile if
202 // it's not local to the crate the Span is found in.
203 if self.source_file_cache.is_imported() {
204 return TAG_INVALID_SPAN.encode(self)
207 TAG_VALID_SPAN.encode(self)?;
208 span.lo.encode(self)?;
210 // Encode length which is usually less than span.hi and profits more
211 // from the variable-length integer encoding that we use.
212 let len = span.hi - span.lo;
215 // Don't encode the expansion context.
219 impl SpecializedEncoder<Ident> for EncodeContext<'tcx> {
220 fn specialized_encode(&mut self, ident: &Ident) -> Result<(), Self::Error> {
221 // FIXME(jseyfried): intercrate hygiene
222 ident.name.encode(self)
226 impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
228 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
229 self.specialized_encode(&def_id.to_def_id())
233 impl<'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'tcx> {
234 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
235 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
239 impl<'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'tcx> {
240 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
241 use std::collections::hash_map::Entry;
242 let index = match self.interpret_allocs.entry(*alloc_id) {
243 Entry::Occupied(e) => *e.get(),
244 Entry::Vacant(e) => {
245 let idx = self.interpret_allocs_inverse.len();
246 self.interpret_allocs_inverse.push(*alloc_id);
256 impl<'tcx> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]> for EncodeContext<'tcx> {
257 fn specialized_encode(&mut self,
258 predicates: &&'tcx [(ty::Predicate<'tcx>, Span)])
259 -> Result<(), Self::Error> {
260 ty_codec::encode_spanned_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
264 impl<'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'tcx> {
265 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
266 f.encode_opaque(&mut self.opaque)
270 impl<'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'tcx> {
271 fn specialized_encode(&mut self,
272 _: &mir::ClearCrossCrate<T>)
273 -> Result<(), Self::Error> {
278 impl<'tcx> TyEncoder for EncodeContext<'tcx> {
279 fn position(&self) -> usize {
280 self.opaque.position()
284 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
285 trait EncodeContentsForLazy<T: ?Sized + LazyMeta> {
286 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> T::Meta;
289 impl<T: Encodable> EncodeContentsForLazy<T> for &T {
290 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
291 self.encode(ecx).unwrap()
295 impl<T: Encodable> EncodeContentsForLazy<T> for T {
296 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
297 self.encode(ecx).unwrap()
301 impl<I, T: Encodable> EncodeContentsForLazy<[T]> for I
302 where I: IntoIterator,
303 I::Item: EncodeContentsForLazy<T>,
305 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> usize {
306 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
310 // Shorthand for `$self.$tables.$table.set($key, $self.lazy($value))`, which would
311 // normally need extra variables to avoid errors about multiple mutable borrows.
312 macro_rules! record {
313 ($self:ident.$tables:ident.$table:ident[$key:expr] <- $value:expr) => {{
316 let lazy = $self.lazy(value);
317 $self.$tables.$table.set($key, lazy);
322 impl<'tcx> EncodeContext<'tcx> {
323 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
326 ) -> Result<(), <Self as Encoder>::Error> {
327 let min_end = lazy.position.get() + T::min_size(lazy.meta);
328 let distance = match self.lazy_state {
329 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
330 LazyState::NodeStart(start) => {
331 let start = start.get();
332 assert!(min_end <= start);
335 LazyState::Previous(last_min_end) => {
337 last_min_end <= lazy.position,
338 "make sure that the calls to `lazy*` \
339 are in the same order as the metadata fields",
341 lazy.position.get() - last_min_end.get()
344 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
345 self.emit_usize(distance)
348 fn lazy<T: ?Sized + LazyMeta>(
350 value: impl EncodeContentsForLazy<T>,
352 let pos = NonZeroUsize::new(self.position()).unwrap();
354 assert_eq!(self.lazy_state, LazyState::NoNode);
355 self.lazy_state = LazyState::NodeStart(pos);
356 let meta = value.encode_contents_for_lazy(self);
357 self.lazy_state = LazyState::NoNode;
359 assert!(pos.get() + <T>::min_size(meta) <= self.position());
361 Lazy::from_position_and_meta(pos, meta)
364 fn encode_info_for_items(&mut self) {
365 let krate = self.tcx.hir().krate();
366 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
367 self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.module, &krate.attrs, &vis);
368 krate.visit_all_item_likes(&mut self.as_deep_visitor());
369 for macro_def in &krate.exported_macros {
370 self.visit_macro_def(macro_def);
374 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
375 let definitions = self.tcx.hir().definitions();
376 self.lazy(definitions.def_path_table())
379 fn encode_source_map(&mut self) -> Lazy<[syntax_pos::SourceFile]> {
380 let source_map = self.tcx.sess.source_map();
381 let all_source_files = source_map.files();
383 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
385 let adapted = all_source_files.iter()
386 .filter(|source_file| {
387 // No need to re-export imported source_files, as any downstream
388 // crate will import them from their original source.
389 // FIXME(eddyb) the `Span` encoding should take that into account.
390 !source_file.is_imported()
393 match source_file.name {
394 // This path of this SourceFile has been modified by
395 // path-remapping, so we use it verbatim (and avoid
396 // cloning the whole map in the process).
397 _ if source_file.name_was_remapped => source_file.clone(),
399 // Otherwise expand all paths to absolute paths because
400 // any relative paths are potentially relative to a
402 FileName::Real(ref name) => {
403 let mut adapted = (**source_file).clone();
404 adapted.name = Path::new(&working_dir).join(name).into();
405 adapted.name_hash = {
406 let mut hasher: StableHasher = StableHasher::new();
407 adapted.name.hash(&mut hasher);
408 hasher.finish::<u128>()
413 // expanded code, not from a file
414 _ => source_file.clone(),
417 .collect::<Vec<_>>();
419 self.lazy(adapted.iter().map(|rc| &**rc))
422 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
423 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
425 let mut i = self.position();
427 let crate_deps = self.encode_crate_deps();
428 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
429 let dep_bytes = self.position() - i;
431 // Encode the lib features.
433 let lib_features = self.encode_lib_features();
434 let lib_feature_bytes = self.position() - i;
436 // Encode the language items.
438 let lang_items = self.encode_lang_items();
439 let lang_items_missing = self.encode_lang_items_missing();
440 let lang_item_bytes = self.position() - i;
442 // Encode the diagnostic items.
444 let diagnostic_items = self.encode_diagnostic_items();
445 let diagnostic_item_bytes = self.position() - i;
447 // Encode the native libraries used
449 let native_libraries = self.encode_native_libraries();
450 let native_lib_bytes = self.position() - i;
452 let foreign_modules = self.encode_foreign_modules();
456 let source_map = self.encode_source_map();
457 let source_map_bytes = self.position() - i;
459 // Encode DefPathTable
461 let def_path_table = self.encode_def_path_table();
462 let def_path_table_bytes = self.position() - i;
464 // Encode the def IDs of impls, for coherence checking.
466 let impls = self.encode_impls();
467 let impl_bytes = self.position() - i;
469 // Encode exported symbols info.
471 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
472 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
473 let exported_symbols_bytes = self.position() - i;
479 self.encode_info_for_items();
480 let item_bytes = self.position() - i;
482 // Encode the allocation index
483 let interpret_alloc_index = {
484 let mut interpret_alloc_index = Vec::new();
486 trace!("beginning to encode alloc ids");
488 let new_n = self.interpret_allocs_inverse.len();
489 // if we have found new ids, serialize those, too
494 trace!("encoding {} further alloc ids", new_n - n);
495 for idx in n..new_n {
496 let id = self.interpret_allocs_inverse[idx];
497 let pos = self.position() as u32;
498 interpret_alloc_index.push(pos);
499 interpret::specialized_encode_alloc_id(
507 self.lazy(interpret_alloc_index)
512 let per_def = LazyPerDefTables {
513 kind: self.per_def.kind.encode(&mut self.opaque),
514 visibility: self.per_def.visibility.encode(&mut self.opaque),
515 span: self.per_def.span.encode(&mut self.opaque),
516 attributes: self.per_def.attributes.encode(&mut self.opaque),
517 children: self.per_def.children.encode(&mut self.opaque),
518 stability: self.per_def.stability.encode(&mut self.opaque),
519 deprecation: self.per_def.deprecation.encode(&mut self.opaque),
521 ty: self.per_def.ty.encode(&mut self.opaque),
522 fn_sig: self.per_def.fn_sig.encode(&mut self.opaque),
523 impl_trait_ref: self.per_def.impl_trait_ref.encode(&mut self.opaque),
524 inherent_impls: self.per_def.inherent_impls.encode(&mut self.opaque),
525 variances: self.per_def.variances.encode(&mut self.opaque),
526 generics: self.per_def.generics.encode(&mut self.opaque),
527 explicit_predicates: self.per_def.explicit_predicates.encode(&mut self.opaque),
528 inferred_outlives: self.per_def.inferred_outlives.encode(&mut self.opaque),
529 super_predicates: self.per_def.super_predicates.encode(&mut self.opaque),
531 mir: self.per_def.mir.encode(&mut self.opaque),
532 promoted_mir: self.per_def.promoted_mir.encode(&mut self.opaque),
534 let per_def_bytes = self.position() - i;
536 // Encode the proc macro data
538 let proc_macro_data = self.encode_proc_macros();
539 let proc_macro_data_bytes = self.position() - i;
542 let attrs = tcx.hir().krate_attrs();
543 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
544 let has_global_allocator = *tcx.sess.has_global_allocator.get();
546 let root = self.lazy(CrateRoot {
547 name: tcx.crate_name(LOCAL_CRATE),
548 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
549 triple: tcx.sess.opts.target_triple.clone(),
550 hash: tcx.crate_hash(LOCAL_CRATE),
551 disambiguator: tcx.sess.local_crate_disambiguator(),
552 panic_strategy: tcx.sess.panic_strategy(),
553 edition: tcx.sess.edition(),
554 has_global_allocator: has_global_allocator,
555 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
556 has_default_lib_allocator: has_default_lib_allocator,
557 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
558 proc_macro_decls_static: if is_proc_macro {
559 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
565 proc_macro_stability: if is_proc_macro {
566 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| stab.clone())
570 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
571 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
572 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
573 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
574 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
575 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
576 sanitizer_runtime: attr::contains_name(&attrs, sym::sanitizer_runtime),
577 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
580 dylib_dependency_formats,
591 interpret_alloc_index,
595 let total_bytes = self.position();
597 if self.tcx.sess.meta_stats() {
598 let mut zero_bytes = 0;
599 for e in self.opaque.data.iter() {
605 println!("metadata stats:");
606 println!(" dep bytes: {}", dep_bytes);
607 println!(" lib feature bytes: {}", lib_feature_bytes);
608 println!(" lang item bytes: {}", lang_item_bytes);
609 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
610 println!(" native bytes: {}", native_lib_bytes);
611 println!(" source_map bytes: {}", source_map_bytes);
612 println!(" impl bytes: {}", impl_bytes);
613 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
614 println!(" def-path table bytes: {}", def_path_table_bytes);
615 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
616 println!(" item bytes: {}", item_bytes);
617 println!(" per-def table bytes: {}", per_def_bytes);
618 println!(" zero bytes: {}", zero_bytes);
619 println!(" total bytes: {}", total_bytes);
626 impl EncodeContext<'tcx> {
627 fn encode_variances_of(&mut self, def_id: DefId) {
628 debug!("EncodeContext::encode_variances_of({:?})", def_id);
629 record!(self.per_def.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
632 fn encode_item_type(&mut self, def_id: DefId) {
633 debug!("EncodeContext::encode_item_type({:?})", def_id);
634 record!(self.per_def.ty[def_id] <- self.tcx.type_of(def_id));
637 fn encode_enum_variant_info(
643 let def = tcx.adt_def(enum_did);
644 let variant = &def.variants[index];
645 let def_id = variant.def_id;
646 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
648 let data = VariantData {
649 ctor_kind: variant.ctor_kind,
650 discr: variant.discr,
651 ctor: variant.ctor_def_id.map(|did| did.index),
654 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
655 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
657 record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
658 record!(self.per_def.visibility[def_id] <-
659 ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
660 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
661 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
662 record!(self.per_def.children[def_id] <- variant.fields.iter().map(|f| {
663 assert!(f.did.is_local());
666 self.encode_stability(def_id);
667 self.encode_deprecation(def_id);
668 self.encode_item_type(def_id);
669 if variant.ctor_kind == CtorKind::Fn {
670 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
671 if let Some(ctor_def_id) = variant.ctor_def_id {
672 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
674 // FIXME(eddyb) is this ever used?
675 self.encode_variances_of(def_id);
677 self.encode_generics(def_id);
678 self.encode_explicit_predicates(def_id);
679 self.encode_inferred_outlives(def_id);
680 self.encode_optimized_mir(def_id);
681 self.encode_promoted_mir(def_id);
684 fn encode_enum_variant_ctor(
690 let def = tcx.adt_def(enum_did);
691 let variant = &def.variants[index];
692 let def_id = variant.ctor_def_id.unwrap();
693 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
695 // FIXME(eddyb) encode only the `CtorKind` for constructors.
696 let data = VariantData {
697 ctor_kind: variant.ctor_kind,
698 discr: variant.discr,
699 ctor: Some(def_id.index),
702 // Variant constructors have the same visibility as the parent enums, unless marked as
703 // non-exhaustive, in which case they are lowered to `pub(crate)`.
704 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
705 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
706 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
707 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
708 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
711 record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
712 record!(self.per_def.visibility[def_id] <- ctor_vis);
713 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
714 self.encode_stability(def_id);
715 self.encode_deprecation(def_id);
716 self.encode_item_type(def_id);
717 if variant.ctor_kind == CtorKind::Fn {
718 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
719 self.encode_variances_of(def_id);
721 self.encode_generics(def_id);
722 self.encode_explicit_predicates(def_id);
723 self.encode_inferred_outlives(def_id);
724 self.encode_optimized_mir(def_id);
725 self.encode_promoted_mir(def_id);
728 fn encode_info_for_mod(
732 attrs: &[ast::Attribute],
733 vis: &hir::Visibility,
736 let def_id = tcx.hir().local_def_id(id);
737 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
740 reexports: match tcx.module_exports(def_id) {
741 Some(exports) => self.lazy(exports),
746 record!(self.per_def.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
747 record!(self.per_def.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
748 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
749 record!(self.per_def.attributes[def_id] <- attrs);
750 record!(self.per_def.children[def_id] <- md.item_ids.iter().map(|item_id| {
751 tcx.hir().local_def_id(item_id.id).index
753 self.encode_stability(def_id);
754 self.encode_deprecation(def_id);
760 variant_index: VariantIdx,
764 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
765 let field = &variant.fields[field_index];
767 let def_id = field.did;
768 debug!("EncodeContext::encode_field({:?})", def_id);
770 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
771 let variant_data = tcx.hir().expect_variant_data(variant_id);
773 record!(self.per_def.kind[def_id] <- EntryKind::Field);
774 record!(self.per_def.visibility[def_id] <- field.vis);
775 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
776 record!(self.per_def.attributes[def_id] <- &variant_data.fields()[field_index].attrs);
777 self.encode_stability(def_id);
778 self.encode_deprecation(def_id);
779 self.encode_item_type(def_id);
780 self.encode_generics(def_id);
781 self.encode_explicit_predicates(def_id);
782 self.encode_inferred_outlives(def_id);
785 fn encode_struct_ctor(&mut self, adt_def_id: DefId, def_id: DefId) {
786 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
788 let adt_def = tcx.adt_def(adt_def_id);
789 let variant = adt_def.non_enum_variant();
791 let data = VariantData {
792 ctor_kind: variant.ctor_kind,
793 discr: variant.discr,
794 ctor: Some(def_id.index),
797 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
798 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
799 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
800 for field in &variant.fields {
801 if ctor_vis.is_at_least(field.vis, tcx) {
802 ctor_vis = field.vis;
806 // If the structure is marked as non_exhaustive then lower the visibility
807 // to within the crate.
808 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
809 ctor_vis == ty::Visibility::Public
811 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
814 record!(self.per_def.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
815 record!(self.per_def.visibility[def_id] <- ctor_vis);
816 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
817 self.encode_stability(def_id);
818 self.encode_deprecation(def_id);
819 self.encode_item_type(def_id);
820 if variant.ctor_kind == CtorKind::Fn {
821 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
822 self.encode_variances_of(def_id);
824 self.encode_generics(def_id);
825 self.encode_explicit_predicates(def_id);
826 self.encode_inferred_outlives(def_id);
827 self.encode_optimized_mir(def_id);
828 self.encode_promoted_mir(def_id);
831 fn encode_generics(&mut self, def_id: DefId) {
832 debug!("EncodeContext::encode_generics({:?})", def_id);
833 record!(self.per_def.generics[def_id] <- self.tcx.generics_of(def_id));
836 fn encode_explicit_predicates(&mut self, def_id: DefId) {
837 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
838 record!(self.per_def.explicit_predicates[def_id] <-
839 self.tcx.explicit_predicates_of(def_id));
842 fn encode_inferred_outlives(&mut self, def_id: DefId) {
843 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
844 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
845 if !inferred_outlives.is_empty() {
846 record!(self.per_def.inferred_outlives[def_id] <- inferred_outlives);
850 fn encode_super_predicates(&mut self, def_id: DefId) {
851 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
852 record!(self.per_def.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
855 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
856 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
859 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
860 let ast_item = tcx.hir().expect_trait_item(hir_id);
861 let trait_item = tcx.associated_item(def_id);
863 let container = match trait_item.defaultness {
864 hir::Defaultness::Default { has_value: true } =>
865 AssocContainer::TraitWithDefault,
866 hir::Defaultness::Default { has_value: false } =>
867 AssocContainer::TraitRequired,
868 hir::Defaultness::Final =>
869 span_bug!(ast_item.span, "traits cannot have final items"),
872 record!(self.per_def.kind[def_id] <- match trait_item.kind {
873 ty::AssocKind::Const => {
875 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
876 let rendered_const = self.lazy(RenderedConst(rendered));
878 EntryKind::AssocConst(
880 ConstQualif { mir: Default::default() },
884 ty::AssocKind::Method => {
885 let fn_data = if let hir::TraitItemKind::Method(m_sig, m) = &ast_item.kind {
886 let param_names = match *m {
887 hir::TraitMethod::Required(ref names) => {
888 self.encode_fn_param_names(names)
890 hir::TraitMethod::Provided(body) => {
891 self.encode_fn_param_names_for_body(body)
895 asyncness: m_sig.header.asyncness,
896 constness: hir::Constness::NotConst,
902 EntryKind::Method(self.lazy(MethodData {
905 has_self: trait_item.method_has_self_argument,
908 ty::AssocKind::Type => EntryKind::AssocType(container),
909 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
911 record!(self.per_def.visibility[def_id] <- trait_item.vis);
912 record!(self.per_def.span[def_id] <- ast_item.span);
913 record!(self.per_def.attributes[def_id] <- &ast_item.attrs);
914 self.encode_stability(def_id);
915 self.encode_deprecation(def_id);
916 match trait_item.kind {
917 ty::AssocKind::Const |
918 ty::AssocKind::Method => {
919 self.encode_item_type(def_id);
921 ty::AssocKind::Type => {
922 if trait_item.defaultness.has_value() {
923 self.encode_item_type(def_id);
926 ty::AssocKind::OpaqueTy => unreachable!(),
928 if trait_item.kind == ty::AssocKind::Method {
929 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
930 self.encode_variances_of(def_id);
932 self.encode_generics(def_id);
933 self.encode_explicit_predicates(def_id);
934 self.encode_inferred_outlives(def_id);
935 self.encode_optimized_mir(def_id);
936 self.encode_promoted_mir(def_id);
939 fn metadata_output_only(&self) -> bool {
940 // MIR optimisation can be skipped when we're just interested in the metadata.
941 !self.tcx.sess.opts.output_types.should_codegen()
944 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
945 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
948 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
949 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
950 let impl_item = self.tcx.associated_item(def_id);
952 let container = match impl_item.defaultness {
953 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
954 hir::Defaultness::Final => AssocContainer::ImplFinal,
955 hir::Defaultness::Default { has_value: false } =>
956 span_bug!(ast_item.span, "impl items always have values (currently)"),
959 record!(self.per_def.kind[def_id] <- match impl_item.kind {
960 ty::AssocKind::Const => {
961 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
962 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
964 EntryKind::AssocConst(container,
966 self.encode_rendered_const_for_body(body_id))
971 ty::AssocKind::Method => {
972 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.kind {
974 asyncness: sig.header.asyncness,
975 constness: sig.header.constness,
976 param_names: self.encode_fn_param_names_for_body(body),
981 EntryKind::Method(self.lazy(MethodData {
984 has_self: impl_item.method_has_self_argument,
987 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
988 ty::AssocKind::Type => EntryKind::AssocType(container)
990 record!(self.per_def.visibility[def_id] <- impl_item.vis);
991 record!(self.per_def.span[def_id] <- ast_item.span);
992 record!(self.per_def.attributes[def_id] <- &ast_item.attrs);
993 self.encode_stability(def_id);
994 self.encode_deprecation(def_id);
995 self.encode_item_type(def_id);
996 if impl_item.kind == ty::AssocKind::Method {
997 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
998 self.encode_variances_of(def_id);
1000 self.encode_generics(def_id);
1001 self.encode_explicit_predicates(def_id);
1002 self.encode_inferred_outlives(def_id);
1003 let mir = match ast_item.kind {
1004 hir::ImplItemKind::Const(..) => true,
1005 hir::ImplItemKind::Method(ref sig, _) => {
1006 let generics = self.tcx.generics_of(def_id);
1007 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
1008 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1009 !self.metadata_output_only();
1010 let is_const_fn = sig.header.constness == hir::Constness::Const;
1011 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1012 needs_inline || is_const_fn || always_encode_mir
1014 hir::ImplItemKind::OpaqueTy(..) |
1015 hir::ImplItemKind::TyAlias(..) => false,
1018 self.encode_optimized_mir(def_id);
1019 self.encode_promoted_mir(def_id);
1023 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId)
1024 -> Lazy<[ast::Name]> {
1025 self.tcx.dep_graph.with_ignore(|| {
1026 let body = self.tcx.hir().body(body_id);
1027 self.lazy(body.params.iter().map(|arg| {
1028 match arg.pat.kind {
1029 PatKind::Binding(_, _, ident, _) => ident.name,
1036 fn encode_fn_param_names(&mut self, param_names: &[ast::Ident]) -> Lazy<[ast::Name]> {
1037 self.lazy(param_names.iter().map(|ident| ident.name))
1040 fn encode_optimized_mir(&mut self, def_id: DefId) {
1041 debug!("EntryBuilder::encode_mir({:?})", def_id);
1042 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1043 record!(self.per_def.mir[def_id] <- self.tcx.optimized_mir(def_id));
1047 fn encode_promoted_mir(&mut self, def_id: DefId) {
1048 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1049 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1050 record!(self.per_def.promoted_mir[def_id] <- self.tcx.promoted_mir(def_id));
1054 // Encodes the inherent implementations of a structure, enumeration, or trait.
1055 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1056 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1057 let implementations = self.tcx.inherent_impls(def_id);
1058 if !implementations.is_empty() {
1059 record!(self.per_def.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1060 assert!(def_id.is_local());
1066 fn encode_stability(&mut self, def_id: DefId) {
1067 debug!("EncodeContext::encode_stability({:?})", def_id);
1068 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1069 record!(self.per_def.stability[def_id] <- stab)
1073 fn encode_deprecation(&mut self, def_id: DefId) {
1074 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1075 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1076 record!(self.per_def.deprecation[def_id] <- depr);
1080 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1081 let body = self.tcx.hir().body(body_id);
1082 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1083 let rendered_const = &RenderedConst(rendered);
1084 self.lazy(rendered_const)
1087 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item) {
1090 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1092 record!(self.per_def.kind[def_id] <- match item.kind {
1093 hir::ItemKind::Static(_, hir::Mutability::Mutable, _) => EntryKind::MutStatic,
1094 hir::ItemKind::Static(_, hir::Mutability::Immutable, _) => EntryKind::ImmStatic,
1095 hir::ItemKind::Const(_, body_id) => {
1096 let mir = self.tcx.at(item.span).mir_const_qualif(def_id);
1098 ConstQualif { mir },
1099 self.encode_rendered_const_for_body(body_id)
1102 hir::ItemKind::Fn(ref sig, .., body) => {
1104 asyncness: sig.header.asyncness,
1105 constness: sig.header.constness,
1106 param_names: self.encode_fn_param_names_for_body(body),
1109 EntryKind::Fn(self.lazy(data))
1111 hir::ItemKind::Mod(ref m) => {
1112 return self.encode_info_for_mod(item.hir_id, m, &item.attrs, &item.vis);
1114 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1115 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1116 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1117 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1118 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1119 hir::ItemKind::Struct(ref struct_def, _) => {
1120 let adt_def = self.tcx.adt_def(def_id);
1121 let variant = adt_def.non_enum_variant();
1123 // Encode def_ids for each field and method
1124 // for methods, write all the stuff get_trait_method
1126 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1127 self.tcx.hir().local_def_id(ctor_hir_id).index
1130 EntryKind::Struct(self.lazy(VariantData {
1131 ctor_kind: variant.ctor_kind,
1132 discr: variant.discr,
1136 hir::ItemKind::Union(..) => {
1137 let adt_def = self.tcx.adt_def(def_id);
1138 let variant = adt_def.non_enum_variant();
1140 EntryKind::Union(self.lazy(VariantData {
1141 ctor_kind: variant.ctor_kind,
1142 discr: variant.discr,
1146 hir::ItemKind::Impl(_, _, defaultness, ..) => {
1147 let trait_ref = self.tcx.impl_trait_ref(def_id);
1148 let polarity = self.tcx.impl_polarity(def_id);
1149 let parent = if let Some(trait_ref) = trait_ref {
1150 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1151 trait_def.ancestors(self.tcx, def_id).nth(1).and_then(|node| {
1153 specialization_graph::Node::Impl(parent) => Some(parent),
1161 // if this is an impl of `CoerceUnsized`, create its
1162 // "unsized info", else just store None
1163 let coerce_unsized_info =
1164 trait_ref.and_then(|t| {
1165 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1166 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1172 let data = ImplData {
1175 parent_impl: parent,
1176 coerce_unsized_info,
1179 EntryKind::Impl(self.lazy(data))
1181 hir::ItemKind::Trait(..) => {
1182 let trait_def = self.tcx.trait_def(def_id);
1183 let data = TraitData {
1184 unsafety: trait_def.unsafety,
1185 paren_sugar: trait_def.paren_sugar,
1186 has_auto_impl: self.tcx.trait_is_auto(def_id),
1187 is_marker: trait_def.is_marker,
1190 EntryKind::Trait(self.lazy(data))
1192 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1193 hir::ItemKind::ExternCrate(_) |
1194 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1196 record!(self.per_def.visibility[def_id] <-
1197 ty::Visibility::from_hir(&item.vis, item.hir_id, tcx));
1198 record!(self.per_def.span[def_id] <- item.span);
1199 record!(self.per_def.attributes[def_id] <- &item.attrs);
1200 // FIXME(eddyb) there should be a nicer way to do this.
1202 hir::ItemKind::ForeignMod(ref fm) => record!(self.per_def.children[def_id] <-
1205 .map(|foreign_item| tcx.hir().local_def_id(
1206 foreign_item.hir_id).index)
1208 hir::ItemKind::Enum(..) => record!(self.per_def.children[def_id] <-
1209 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1210 assert!(v.def_id.is_local());
1214 hir::ItemKind::Struct(..) |
1215 hir::ItemKind::Union(..) => record!(self.per_def.children[def_id] <-
1216 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1217 assert!(f.did.is_local());
1221 hir::ItemKind::Impl(..) |
1222 hir::ItemKind::Trait(..) => {
1223 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1224 record!(self.per_def.children[def_id] <-
1225 associated_item_def_ids.iter().map(|&def_id| {
1226 assert!(def_id.is_local());
1233 self.encode_stability(def_id);
1234 self.encode_deprecation(def_id);
1236 hir::ItemKind::Static(..) |
1237 hir::ItemKind::Const(..) |
1238 hir::ItemKind::Fn(..) |
1239 hir::ItemKind::TyAlias(..) |
1240 hir::ItemKind::OpaqueTy(..) |
1241 hir::ItemKind::Enum(..) |
1242 hir::ItemKind::Struct(..) |
1243 hir::ItemKind::Union(..) |
1244 hir::ItemKind::Impl(..) => self.encode_item_type(def_id),
1247 if let hir::ItemKind::Fn(..) = item.kind {
1248 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
1250 if let hir::ItemKind::Impl(..) = item.kind {
1251 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1252 record!(self.per_def.impl_trait_ref[def_id] <- trait_ref);
1255 self.encode_inherent_implementations(def_id);
1257 hir::ItemKind::Enum(..) |
1258 hir::ItemKind::Struct(..) |
1259 hir::ItemKind::Union(..) |
1260 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1264 hir::ItemKind::Static(..) |
1265 hir::ItemKind::Const(..) |
1266 hir::ItemKind::Fn(..) |
1267 hir::ItemKind::TyAlias(..) |
1268 hir::ItemKind::Enum(..) |
1269 hir::ItemKind::Struct(..) |
1270 hir::ItemKind::Union(..) |
1271 hir::ItemKind::Impl(..) |
1272 hir::ItemKind::OpaqueTy(..) |
1273 hir::ItemKind::Trait(..) |
1274 hir::ItemKind::TraitAlias(..) => {
1275 self.encode_generics(def_id);
1276 self.encode_explicit_predicates(def_id);
1277 self.encode_inferred_outlives(def_id);
1282 hir::ItemKind::Trait(..) |
1283 hir::ItemKind::TraitAlias(..) => {
1284 self.encode_super_predicates(def_id);
1289 let mir = match item.kind {
1290 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1291 hir::ItemKind::Fn(ref sig, ..) => {
1292 let generics = tcx.generics_of(def_id);
1294 (generics.requires_monomorphization(tcx) ||
1295 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1296 !self.metadata_output_only();
1297 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1298 needs_inline || sig.header.constness == hir::Constness::Const || always_encode_mir
1303 self.encode_optimized_mir(def_id);
1304 self.encode_promoted_mir(def_id);
1308 /// Serialize the text of exported macros
1309 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) {
1310 use syntax::print::pprust;
1311 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1312 record!(self.per_def.kind[def_id] <- EntryKind::MacroDef(self.lazy(MacroDef {
1313 body: pprust::tts_to_string(macro_def.body.clone()),
1314 legacy: macro_def.legacy,
1316 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1317 record!(self.per_def.span[def_id] <- macro_def.span);
1318 record!(self.per_def.attributes[def_id] <- ¯o_def.attrs);
1319 self.encode_stability(def_id);
1320 self.encode_deprecation(def_id);
1323 fn encode_info_for_generic_param(
1326 kind: EntryKind<'tcx>,
1329 record!(self.per_def.kind[def_id] <- kind);
1330 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1331 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1333 self.encode_item_type(def_id);
1337 fn encode_info_for_closure(&mut self, def_id: DefId) {
1338 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1340 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1341 // including on the signature, which is inferred in `typeck_tables_of.
1342 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1343 let ty = self.tcx.typeck_tables_of(def_id).node_type(hir_id);
1345 record!(self.per_def.kind[def_id] <- match ty.kind {
1346 ty::Generator(def_id, ..) => {
1347 let layout = self.tcx.generator_layout(def_id);
1348 let data = GeneratorData {
1349 layout: layout.clone(),
1351 EntryKind::Generator(self.lazy(data))
1354 ty::Closure(..) => EntryKind::Closure,
1356 _ => bug!("closure that is neither generator nor closure"),
1358 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1359 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1360 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
1361 self.encode_item_type(def_id);
1362 if let ty::Closure(def_id, substs) = ty.kind {
1363 record!(self.per_def.fn_sig[def_id] <- substs.as_closure().sig(def_id, self.tcx));
1365 self.encode_generics(def_id);
1366 self.encode_optimized_mir(def_id);
1367 self.encode_promoted_mir(def_id);
1370 fn encode_info_for_anon_const(&mut self, def_id: DefId) {
1371 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1372 let id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1373 let body_id = self.tcx.hir().body_owned_by(id);
1374 let const_data = self.encode_rendered_const_for_body(body_id);
1375 let mir = self.tcx.mir_const_qualif(def_id);
1377 record!(self.per_def.kind[def_id] <- EntryKind::Const(ConstQualif { mir }, const_data));
1378 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1379 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1380 self.encode_item_type(def_id);
1381 self.encode_generics(def_id);
1382 self.encode_explicit_predicates(def_id);
1383 self.encode_inferred_outlives(def_id);
1384 self.encode_optimized_mir(def_id);
1385 self.encode_promoted_mir(def_id);
1388 fn encode_native_libraries(&mut self) -> Lazy<[NativeLibrary]> {
1389 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1390 self.lazy(used_libraries.iter().cloned())
1393 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1394 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1395 self.lazy(foreign_modules.iter().cloned())
1398 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1399 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1402 Some(self.lazy(tcx.hir().krate().items.values().filter_map(|item| {
1403 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
1404 Some(item.hir_id.owner)
1414 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1415 let crates = self.tcx.crates();
1417 let mut deps = crates
1420 let dep = CrateDep {
1421 name: self.tcx.original_crate_name(cnum),
1422 hash: self.tcx.crate_hash(cnum),
1423 host_hash: self.tcx.crate_host_hash(cnum),
1424 kind: self.tcx.dep_kind(cnum),
1425 extra_filename: self.tcx.extra_filename(cnum),
1429 .collect::<Vec<_>>();
1431 deps.sort_by_key(|&(cnum, _)| cnum);
1434 // Sanity-check the crate numbers
1435 let mut expected_cnum = 1;
1436 for &(n, _) in &deps {
1437 assert_eq!(n, CrateNum::new(expected_cnum));
1442 // We're just going to write a list of crate 'name-hash-version's, with
1443 // the assumption that they are numbered 1 to n.
1444 // FIXME (#2166): This is not nearly enough to support correct versioning
1445 // but is enough to get transitive crate dependencies working.
1446 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1449 fn encode_lib_features(&mut self) -> Lazy<[(ast::Name, Option<ast::Name>)]> {
1451 let lib_features = tcx.lib_features();
1452 self.lazy(lib_features.to_vec())
1455 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1457 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1458 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1461 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1463 let lang_items = tcx.lang_items();
1464 let lang_items = lang_items.items().iter();
1465 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1466 if let Some(def_id) = opt_def_id {
1467 if def_id.is_local() {
1468 return Some((def_id.index, i));
1475 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1477 self.lazy(&tcx.lang_items().missing)
1480 /// Encodes an index, mapping each trait to its (local) implementations.
1481 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1482 debug!("EncodeContext::encode_impls()");
1484 let mut visitor = ImplVisitor {
1486 impls: FxHashMap::default(),
1488 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1490 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1492 // Bring everything into deterministic order for hashing
1493 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1494 tcx.def_path_hash(trait_def_id)
1497 let all_impls: Vec<_> = all_impls
1499 .map(|(trait_def_id, mut impls)| {
1500 // Bring everything into deterministic order for hashing
1501 impls.sort_by_cached_key(|&def_index| {
1502 tcx.hir().definitions().def_path_hash(def_index)
1506 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1507 impls: self.lazy(&impls),
1512 self.lazy(&all_impls)
1515 // Encodes all symbols exported from this crate into the metadata.
1517 // This pass is seeded off the reachability list calculated in the
1518 // middle::reachable module but filters out items that either don't have a
1519 // symbol associated with them (they weren't translated) or if they're an FFI
1520 // definition (as that's not defined in this crate).
1521 fn encode_exported_symbols(&mut self,
1522 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)])
1523 -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1524 // The metadata symbol name is special. It should not show up in
1525 // downstream crates.
1526 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1528 self.lazy(exported_symbols
1530 .filter(|&&(ref exported_symbol, _)| {
1531 match *exported_symbol {
1532 ExportedSymbol::NoDefId(symbol_name) => {
1533 symbol_name != metadata_symbol_name
1541 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1542 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1543 for (ty, arr) in formats.iter() {
1544 if *ty != config::CrateType::Dylib {
1547 return self.lazy(arr.iter().map(|slot| {
1549 Linkage::NotLinked |
1550 Linkage::IncludedFromDylib => None,
1552 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1553 Linkage::Static => Some(LinkagePreference::RequireStatic),
1560 fn encode_info_for_foreign_item(
1563 nitem: &hir::ForeignItem,
1567 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1569 record!(self.per_def.kind[def_id] <- match nitem.kind {
1570 hir::ForeignItemKind::Fn(_, ref names, _) => {
1572 asyncness: hir::IsAsync::NotAsync,
1573 constness: hir::Constness::NotConst,
1574 param_names: self.encode_fn_param_names(names),
1576 EntryKind::ForeignFn(self.lazy(data))
1578 hir::ForeignItemKind::Static(_, hir::Mutability::Mutable) =>
1579 EntryKind::ForeignMutStatic,
1580 hir::ForeignItemKind::Static(_, hir::Mutability::Immutable) =>
1581 EntryKind::ForeignImmStatic,
1582 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1584 record!(self.per_def.visibility[def_id] <-
1585 ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx));
1586 record!(self.per_def.span[def_id] <- nitem.span);
1587 record!(self.per_def.attributes[def_id] <- &nitem.attrs);
1588 self.encode_stability(def_id);
1589 self.encode_deprecation(def_id);
1590 self.encode_item_type(def_id);
1591 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1592 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
1593 self.encode_variances_of(def_id);
1595 self.encode_generics(def_id);
1596 self.encode_explicit_predicates(def_id);
1597 self.encode_inferred_outlives(def_id);
1601 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1602 impl Visitor<'tcx> for EncodeContext<'tcx> {
1603 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1604 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1606 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1607 intravisit::walk_expr(self, ex);
1608 self.encode_info_for_expr(ex);
1610 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1611 intravisit::walk_anon_const(self, c);
1612 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1613 self.encode_info_for_anon_const(def_id);
1615 fn visit_item(&mut self, item: &'tcx hir::Item) {
1616 intravisit::walk_item(self, item);
1617 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1619 hir::ItemKind::ExternCrate(_) |
1620 hir::ItemKind::Use(..) => {} // ignore these
1621 _ => self.encode_info_for_item(def_id, item),
1623 self.encode_addl_info_for_item(item);
1625 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1626 intravisit::walk_foreign_item(self, ni);
1627 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1628 self.encode_info_for_foreign_item(def_id, ni);
1630 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1631 intravisit::walk_generics(self, generics);
1632 self.encode_info_for_generics(generics);
1634 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1635 self.encode_info_for_macro_def(macro_def);
1639 impl EncodeContext<'tcx> {
1640 fn encode_fields(&mut self, adt_def_id: DefId) {
1641 let def = self.tcx.adt_def(adt_def_id);
1642 for (variant_index, variant) in def.variants.iter_enumerated() {
1643 for (field_index, _field) in variant.fields.iter().enumerate() {
1644 // FIXME(eddyb) `adt_def_id` is leftover from incremental isolation,
1645 // pass `def`, `variant` or `field` instead.
1646 self.encode_field(adt_def_id, variant_index, field_index);
1651 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1652 for param in &generics.params {
1653 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1655 GenericParamKind::Lifetime { .. } => continue,
1656 GenericParamKind::Type { ref default, .. } => {
1657 self.encode_info_for_generic_param(
1659 EntryKind::TypeParam,
1663 GenericParamKind::Const { .. } => {
1664 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1670 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1672 hir::ExprKind::Closure(..) => {
1673 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1674 self.encode_info_for_closure(def_id);
1680 /// In some cases, along with the item itself, we also
1681 /// encode some sub-items. Usually we want some info from the item
1682 /// so it's easier to do that here then to wait until we would encounter
1683 /// normally in the visitor walk.
1684 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1685 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1687 hir::ItemKind::Static(..) |
1688 hir::ItemKind::Const(..) |
1689 hir::ItemKind::Fn(..) |
1690 hir::ItemKind::Mod(..) |
1691 hir::ItemKind::ForeignMod(..) |
1692 hir::ItemKind::GlobalAsm(..) |
1693 hir::ItemKind::ExternCrate(..) |
1694 hir::ItemKind::Use(..) |
1695 hir::ItemKind::TyAlias(..) |
1696 hir::ItemKind::OpaqueTy(..) |
1697 hir::ItemKind::TraitAlias(..) => {
1698 // no sub-item recording needed in these cases
1700 hir::ItemKind::Enum(..) => {
1701 self.encode_fields(def_id);
1703 let def = self.tcx.adt_def(def_id);
1704 for (i, variant) in def.variants.iter_enumerated() {
1705 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1706 // pass `def` or `variant` instead.
1707 self.encode_enum_variant_info(def_id, i);
1709 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1710 // pass `def`, `variant` or `ctor_def_id` instead.
1711 if let Some(_ctor_def_id) = variant.ctor_def_id {
1712 self.encode_enum_variant_ctor(def_id, i);
1716 hir::ItemKind::Struct(ref struct_def, _) => {
1717 self.encode_fields(def_id);
1719 // If the struct has a constructor, encode it.
1720 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1721 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1722 self.encode_struct_ctor(def_id, ctor_def_id);
1725 hir::ItemKind::Union(..) => {
1726 self.encode_fields(def_id);
1728 hir::ItemKind::Impl(..) => {
1729 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1730 self.encode_info_for_impl_item(trait_item_def_id);
1733 hir::ItemKind::Trait(..) => {
1734 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1735 self.encode_info_for_trait_item(item_def_id);
1742 struct ImplVisitor<'tcx> {
1744 impls: FxHashMap<DefId, Vec<DefIndex>>,
1747 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1748 fn visit_item(&mut self, item: &hir::Item) {
1749 if let hir::ItemKind::Impl(..) = item.kind {
1750 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1751 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1753 .entry(trait_ref.def_id)
1755 .push(impl_id.index);
1760 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1762 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1763 // handled in `visit_item` above
1767 // NOTE(eddyb) The following comment was preserved for posterity, even
1768 // though it's no longer relevant as EBML (which uses nested & tagged
1769 // "documents") was replaced with a scheme that can't go out of bounds.
1771 // And here we run into yet another obscure archive bug: in which metadata
1772 // loaded from archives may have trailing garbage bytes. Awhile back one of
1773 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1774 // and opt) by having ebml generate an out-of-bounds panic when looking at
1777 // Upon investigation it turned out that the metadata file inside of an rlib
1778 // (and ar archive) was being corrupted. Some compilations would generate a
1779 // metadata file which would end in a few extra bytes, while other
1780 // compilations would not have these extra bytes appended to the end. These
1781 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1782 // being interpreted causing the out-of-bounds.
1784 // The root cause of why these extra bytes were appearing was never
1785 // discovered, and in the meantime the solution we're employing is to insert
1786 // the length of the metadata to the start of the metadata. Later on this
1787 // will allow us to slice the metadata to the precise length that we just
1788 // generated regardless of trailing bytes that end up in it.
1790 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1791 let mut encoder = opaque::Encoder::new(vec![]);
1792 encoder.emit_raw_bytes(METADATA_HEADER);
1794 // Will be filled with the root position after encoding everything.
1795 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1797 // Since encoding metadata is not in a query, and nothing is cached,
1798 // there's no need to do dep-graph tracking for any of it.
1799 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1800 let mut ecx = EncodeContext {
1803 per_def: Default::default(),
1804 lazy_state: LazyState::NoNode,
1805 type_shorthands: Default::default(),
1806 predicate_shorthands: Default::default(),
1807 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1808 interpret_allocs: Default::default(),
1809 interpret_allocs_inverse: Default::default(),
1812 // Encode the rustc version string in a predictable location.
1813 rustc_version().encode(&mut ecx).unwrap();
1815 // Encode all the entries and extra information in the crate,
1816 // culminating in the `CrateRoot` which points to all of it.
1817 let root = ecx.encode_crate_root();
1818 (root, ecx.opaque.into_inner())
1821 // Encode the root position.
1822 let header = METADATA_HEADER.len();
1823 let pos = root.position.get();
1824 result[header + 0] = (pos >> 24) as u8;
1825 result[header + 1] = (pos >> 16) as u8;
1826 result[header + 2] = (pos >> 8) as u8;
1827 result[header + 3] = (pos >> 0) as u8;
1829 EncodedMetadata { raw_data: result }