2 use crate::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 predicates: PerDefTable<Lazy<ty::GenericPredicates<'tcx>>>,
80 predicates_defined_on: PerDefTable<Lazy<ty::GenericPredicates<'tcx>>>,
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 predicates: self.per_def.predicates.encode(&mut self.opaque),
528 predicates_defined_on: self.per_def.predicates_defined_on.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();
545 let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false);
547 let root = self.lazy(CrateRoot {
548 name: tcx.crate_name(LOCAL_CRATE),
549 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
550 triple: tcx.sess.opts.target_triple.clone(),
551 hash: tcx.crate_hash(LOCAL_CRATE),
552 disambiguator: tcx.sess.local_crate_disambiguator(),
553 panic_strategy: tcx.sess.panic_strategy(),
554 edition: tcx.sess.edition(),
555 has_global_allocator: has_global_allocator,
556 has_panic_handler: has_panic_handler,
557 has_default_lib_allocator: has_default_lib_allocator,
558 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
559 proc_macro_decls_static: if is_proc_macro {
560 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
566 proc_macro_stability: if is_proc_macro {
567 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| stab.clone())
571 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
572 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
573 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
574 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
575 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
576 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
577 sanitizer_runtime: attr::contains_name(&attrs, sym::sanitizer_runtime),
578 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
581 dylib_dependency_formats,
592 interpret_alloc_index,
596 let total_bytes = self.position();
598 if self.tcx.sess.meta_stats() {
599 let mut zero_bytes = 0;
600 for e in self.opaque.data.iter() {
606 println!("metadata stats:");
607 println!(" dep bytes: {}", dep_bytes);
608 println!(" lib feature bytes: {}", lib_feature_bytes);
609 println!(" lang item bytes: {}", lang_item_bytes);
610 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
611 println!(" native bytes: {}", native_lib_bytes);
612 println!(" source_map bytes: {}", source_map_bytes);
613 println!(" impl bytes: {}", impl_bytes);
614 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
615 println!(" def-path table bytes: {}", def_path_table_bytes);
616 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
617 println!(" item bytes: {}", item_bytes);
618 println!(" per-def table bytes: {}", per_def_bytes);
619 println!(" zero bytes: {}", zero_bytes);
620 println!(" total bytes: {}", total_bytes);
627 impl EncodeContext<'tcx> {
628 fn encode_variances_of(&mut self, def_id: DefId) {
629 debug!("EncodeContext::encode_variances_of({:?})", def_id);
630 record!(self.per_def.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
633 fn encode_item_type(&mut self, def_id: DefId) {
634 debug!("EncodeContext::encode_item_type({:?})", def_id);
635 record!(self.per_def.ty[def_id] <- self.tcx.type_of(def_id));
638 fn encode_enum_variant_info(
644 let def = tcx.adt_def(enum_did);
645 let variant = &def.variants[index];
646 let def_id = variant.def_id;
647 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
649 let data = VariantData {
650 ctor_kind: variant.ctor_kind,
651 discr: variant.discr,
652 ctor: variant.ctor_def_id.map(|did| did.index),
655 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
656 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
658 record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
659 record!(self.per_def.visibility[def_id] <-
660 ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
661 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
662 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
663 record!(self.per_def.children[def_id] <- variant.fields.iter().map(|f| {
664 assert!(f.did.is_local());
667 self.encode_stability(def_id);
668 self.encode_deprecation(def_id);
669 self.encode_item_type(def_id);
670 if variant.ctor_kind == CtorKind::Fn {
671 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
672 if let Some(ctor_def_id) = variant.ctor_def_id {
673 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
675 // FIXME(eddyb) is this ever used?
676 self.encode_variances_of(def_id);
678 self.encode_generics(def_id);
679 self.encode_predicates(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_predicates(def_id);
723 self.encode_optimized_mir(def_id);
724 self.encode_promoted_mir(def_id);
727 fn encode_info_for_mod(
731 attrs: &[ast::Attribute],
732 vis: &hir::Visibility,
735 let def_id = tcx.hir().local_def_id(id);
736 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
739 reexports: match tcx.module_exports(def_id) {
740 Some(exports) => self.lazy(exports),
745 record!(self.per_def.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
746 record!(self.per_def.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
747 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
748 record!(self.per_def.attributes[def_id] <- attrs);
749 record!(self.per_def.children[def_id] <- md.item_ids.iter().map(|item_id| {
750 tcx.hir().local_def_id(item_id.id).index
752 self.encode_stability(def_id);
753 self.encode_deprecation(def_id);
759 variant_index: VariantIdx,
763 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
764 let field = &variant.fields[field_index];
766 let def_id = field.did;
767 debug!("EncodeContext::encode_field({:?})", def_id);
769 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
770 let variant_data = tcx.hir().expect_variant_data(variant_id);
772 record!(self.per_def.kind[def_id] <- EntryKind::Field);
773 record!(self.per_def.visibility[def_id] <- field.vis);
774 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
775 record!(self.per_def.attributes[def_id] <- &variant_data.fields()[field_index].attrs);
776 self.encode_stability(def_id);
777 self.encode_deprecation(def_id);
778 self.encode_item_type(def_id);
779 self.encode_generics(def_id);
780 self.encode_predicates(def_id);
783 fn encode_struct_ctor(&mut self, adt_def_id: DefId, def_id: DefId) {
784 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
786 let adt_def = tcx.adt_def(adt_def_id);
787 let variant = adt_def.non_enum_variant();
789 let data = VariantData {
790 ctor_kind: variant.ctor_kind,
791 discr: variant.discr,
792 ctor: Some(def_id.index),
795 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
796 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
797 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
798 for field in &variant.fields {
799 if ctor_vis.is_at_least(field.vis, tcx) {
800 ctor_vis = field.vis;
804 // If the structure is marked as non_exhaustive then lower the visibility
805 // to within the crate.
806 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
807 ctor_vis == ty::Visibility::Public
809 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
812 record!(self.per_def.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
813 record!(self.per_def.visibility[def_id] <- ctor_vis);
814 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
815 self.encode_stability(def_id);
816 self.encode_deprecation(def_id);
817 self.encode_item_type(def_id);
818 if variant.ctor_kind == CtorKind::Fn {
819 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
820 self.encode_variances_of(def_id);
822 self.encode_generics(def_id);
823 self.encode_predicates(def_id);
824 self.encode_optimized_mir(def_id);
825 self.encode_promoted_mir(def_id);
828 fn encode_generics(&mut self, def_id: DefId) {
829 debug!("EncodeContext::encode_generics({:?})", def_id);
830 record!(self.per_def.generics[def_id] <- self.tcx.generics_of(def_id));
833 fn encode_predicates(&mut self, def_id: DefId) {
834 debug!("EncodeContext::encode_predicates({:?})", def_id);
835 record!(self.per_def.predicates[def_id] <- self.tcx.predicates_of(def_id));
838 fn encode_predicates_defined_on(&mut self, def_id: DefId) {
839 debug!("EncodeContext::encode_predicates_defined_on({:?})", def_id);
840 record!(self.per_def.predicates_defined_on[def_id] <-
841 self.tcx.predicates_defined_on(def_id))
844 fn encode_super_predicates(&mut self, def_id: DefId) {
845 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
846 record!(self.per_def.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
849 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
850 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
853 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
854 let ast_item = tcx.hir().expect_trait_item(hir_id);
855 let trait_item = tcx.associated_item(def_id);
857 let container = match trait_item.defaultness {
858 hir::Defaultness::Default { has_value: true } =>
859 AssocContainer::TraitWithDefault,
860 hir::Defaultness::Default { has_value: false } =>
861 AssocContainer::TraitRequired,
862 hir::Defaultness::Final =>
863 span_bug!(ast_item.span, "traits cannot have final items"),
866 record!(self.per_def.kind[def_id] <- match trait_item.kind {
867 ty::AssocKind::Const => {
869 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
870 let rendered_const = self.lazy(RenderedConst(rendered));
872 EntryKind::AssocConst(container, ConstQualif { mir: 0 }, rendered_const)
874 ty::AssocKind::Method => {
875 let fn_data = if let hir::TraitItemKind::Method(m_sig, m) = &ast_item.kind {
876 let param_names = match *m {
877 hir::TraitMethod::Required(ref names) => {
878 self.encode_fn_param_names(names)
880 hir::TraitMethod::Provided(body) => {
881 self.encode_fn_param_names_for_body(body)
885 asyncness: m_sig.header.asyncness,
886 constness: hir::Constness::NotConst,
892 EntryKind::Method(self.lazy(MethodData {
895 has_self: trait_item.method_has_self_argument,
898 ty::AssocKind::Type => EntryKind::AssocType(container),
899 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
901 record!(self.per_def.visibility[def_id] <- trait_item.vis);
902 record!(self.per_def.span[def_id] <- ast_item.span);
903 record!(self.per_def.attributes[def_id] <- &ast_item.attrs);
904 self.encode_stability(def_id);
905 self.encode_deprecation(def_id);
906 match trait_item.kind {
907 ty::AssocKind::Const |
908 ty::AssocKind::Method => {
909 self.encode_item_type(def_id);
911 ty::AssocKind::Type => {
912 if trait_item.defaultness.has_value() {
913 self.encode_item_type(def_id);
916 ty::AssocKind::OpaqueTy => unreachable!(),
918 if trait_item.kind == ty::AssocKind::Method {
919 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
920 self.encode_variances_of(def_id);
922 self.encode_generics(def_id);
923 self.encode_predicates(def_id);
924 self.encode_optimized_mir(def_id);
925 self.encode_promoted_mir(def_id);
928 fn metadata_output_only(&self) -> bool {
929 // MIR optimisation can be skipped when we're just interested in the metadata.
930 !self.tcx.sess.opts.output_types.should_codegen()
933 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
934 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
937 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
938 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
939 let impl_item = self.tcx.associated_item(def_id);
941 let container = match impl_item.defaultness {
942 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
943 hir::Defaultness::Final => AssocContainer::ImplFinal,
944 hir::Defaultness::Default { has_value: false } =>
945 span_bug!(ast_item.span, "impl items always have values (currently)"),
948 record!(self.per_def.kind[def_id] <- match impl_item.kind {
949 ty::AssocKind::Const => {
950 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
951 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
953 EntryKind::AssocConst(container,
955 self.encode_rendered_const_for_body(body_id))
960 ty::AssocKind::Method => {
961 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.kind {
963 asyncness: sig.header.asyncness,
964 constness: sig.header.constness,
965 param_names: self.encode_fn_param_names_for_body(body),
970 EntryKind::Method(self.lazy(MethodData {
973 has_self: impl_item.method_has_self_argument,
976 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
977 ty::AssocKind::Type => EntryKind::AssocType(container)
979 record!(self.per_def.visibility[def_id] <- impl_item.vis);
980 record!(self.per_def.span[def_id] <- ast_item.span);
981 record!(self.per_def.attributes[def_id] <- &ast_item.attrs);
982 self.encode_stability(def_id);
983 self.encode_deprecation(def_id);
984 self.encode_item_type(def_id);
985 if impl_item.kind == ty::AssocKind::Method {
986 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
987 self.encode_variances_of(def_id);
989 self.encode_generics(def_id);
990 self.encode_predicates(def_id);
991 let mir = match ast_item.kind {
992 hir::ImplItemKind::Const(..) => true,
993 hir::ImplItemKind::Method(ref sig, _) => {
994 let generics = self.tcx.generics_of(def_id);
995 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
996 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
997 !self.metadata_output_only();
998 let is_const_fn = sig.header.constness == hir::Constness::Const;
999 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1000 needs_inline || is_const_fn || always_encode_mir
1002 hir::ImplItemKind::OpaqueTy(..) |
1003 hir::ImplItemKind::TyAlias(..) => false,
1006 self.encode_optimized_mir(def_id);
1007 self.encode_promoted_mir(def_id);
1011 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId)
1012 -> Lazy<[ast::Name]> {
1013 self.tcx.dep_graph.with_ignore(|| {
1014 let body = self.tcx.hir().body(body_id);
1015 self.lazy(body.params.iter().map(|arg| {
1016 match arg.pat.kind {
1017 PatKind::Binding(_, _, ident, _) => ident.name,
1024 fn encode_fn_param_names(&mut self, param_names: &[ast::Ident]) -> Lazy<[ast::Name]> {
1025 self.lazy(param_names.iter().map(|ident| ident.name))
1028 fn encode_optimized_mir(&mut self, def_id: DefId) {
1029 debug!("EntryBuilder::encode_mir({:?})", def_id);
1030 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1031 record!(self.per_def.mir[def_id] <- self.tcx.optimized_mir(def_id));
1035 fn encode_promoted_mir(&mut self, def_id: DefId) {
1036 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1037 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1038 record!(self.per_def.promoted_mir[def_id] <- self.tcx.promoted_mir(def_id));
1042 // Encodes the inherent implementations of a structure, enumeration, or trait.
1043 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1044 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1045 let implementations = self.tcx.inherent_impls(def_id);
1046 if !implementations.is_empty() {
1047 record!(self.per_def.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1048 assert!(def_id.is_local());
1054 fn encode_stability(&mut self, def_id: DefId) {
1055 debug!("EncodeContext::encode_stability({:?})", def_id);
1056 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1057 record!(self.per_def.stability[def_id] <- stab)
1061 fn encode_deprecation(&mut self, def_id: DefId) {
1062 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1063 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1064 record!(self.per_def.deprecation[def_id] <- depr);
1068 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1069 let body = self.tcx.hir().body(body_id);
1070 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1071 let rendered_const = &RenderedConst(rendered);
1072 self.lazy(rendered_const)
1075 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item) {
1078 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1080 record!(self.per_def.kind[def_id] <- match item.kind {
1081 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1082 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1083 hir::ItemKind::Const(_, body_id) => {
1084 let mir = self.tcx.at(item.span).mir_const_qualif(def_id).0;
1086 ConstQualif { mir },
1087 self.encode_rendered_const_for_body(body_id)
1090 hir::ItemKind::Fn(_, header, .., body) => {
1092 asyncness: header.asyncness,
1093 constness: header.constness,
1094 param_names: self.encode_fn_param_names_for_body(body),
1097 EntryKind::Fn(self.lazy(data))
1099 hir::ItemKind::Mod(ref m) => {
1100 return self.encode_info_for_mod(item.hir_id, m, &item.attrs, &item.vis);
1102 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1103 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1104 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1105 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1106 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1107 hir::ItemKind::Struct(ref struct_def, _) => {
1108 let adt_def = self.tcx.adt_def(def_id);
1109 let variant = adt_def.non_enum_variant();
1111 // Encode def_ids for each field and method
1112 // for methods, write all the stuff get_trait_method
1114 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1115 self.tcx.hir().local_def_id(ctor_hir_id).index
1118 EntryKind::Struct(self.lazy(VariantData {
1119 ctor_kind: variant.ctor_kind,
1120 discr: variant.discr,
1124 hir::ItemKind::Union(..) => {
1125 let adt_def = self.tcx.adt_def(def_id);
1126 let variant = adt_def.non_enum_variant();
1128 EntryKind::Union(self.lazy(VariantData {
1129 ctor_kind: variant.ctor_kind,
1130 discr: variant.discr,
1134 hir::ItemKind::Impl(_, _, defaultness, ..) => {
1135 let trait_ref = self.tcx.impl_trait_ref(def_id);
1136 let polarity = self.tcx.impl_polarity(def_id);
1137 let parent = if let Some(trait_ref) = trait_ref {
1138 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1139 trait_def.ancestors(self.tcx, def_id).nth(1).and_then(|node| {
1141 specialization_graph::Node::Impl(parent) => Some(parent),
1149 // if this is an impl of `CoerceUnsized`, create its
1150 // "unsized info", else just store None
1151 let coerce_unsized_info =
1152 trait_ref.and_then(|t| {
1153 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1154 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1160 let data = ImplData {
1163 parent_impl: parent,
1164 coerce_unsized_info,
1167 EntryKind::Impl(self.lazy(data))
1169 hir::ItemKind::Trait(..) => {
1170 let trait_def = self.tcx.trait_def(def_id);
1171 let data = TraitData {
1172 unsafety: trait_def.unsafety,
1173 paren_sugar: trait_def.paren_sugar,
1174 has_auto_impl: self.tcx.trait_is_auto(def_id),
1175 is_marker: trait_def.is_marker,
1178 EntryKind::Trait(self.lazy(data))
1180 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1181 hir::ItemKind::ExternCrate(_) |
1182 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1184 record!(self.per_def.visibility[def_id] <-
1185 ty::Visibility::from_hir(&item.vis, item.hir_id, tcx));
1186 record!(self.per_def.span[def_id] <- item.span);
1187 record!(self.per_def.attributes[def_id] <- &item.attrs);
1188 // FIXME(eddyb) there should be a nicer way to do this.
1190 hir::ItemKind::ForeignMod(ref fm) => record!(self.per_def.children[def_id] <-
1193 .map(|foreign_item| tcx.hir().local_def_id(
1194 foreign_item.hir_id).index)
1196 hir::ItemKind::Enum(..) => record!(self.per_def.children[def_id] <-
1197 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1198 assert!(v.def_id.is_local());
1202 hir::ItemKind::Struct(..) |
1203 hir::ItemKind::Union(..) => record!(self.per_def.children[def_id] <-
1204 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1205 assert!(f.did.is_local());
1209 hir::ItemKind::Impl(..) |
1210 hir::ItemKind::Trait(..) => {
1211 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1212 record!(self.per_def.children[def_id] <-
1213 associated_item_def_ids.iter().map(|&def_id| {
1214 assert!(def_id.is_local());
1221 self.encode_stability(def_id);
1222 self.encode_deprecation(def_id);
1224 hir::ItemKind::Static(..) |
1225 hir::ItemKind::Const(..) |
1226 hir::ItemKind::Fn(..) |
1227 hir::ItemKind::TyAlias(..) |
1228 hir::ItemKind::OpaqueTy(..) |
1229 hir::ItemKind::Enum(..) |
1230 hir::ItemKind::Struct(..) |
1231 hir::ItemKind::Union(..) |
1232 hir::ItemKind::Impl(..) => self.encode_item_type(def_id),
1235 if let hir::ItemKind::Fn(..) = item.kind {
1236 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
1238 if let hir::ItemKind::Impl(..) = item.kind {
1239 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1240 record!(self.per_def.impl_trait_ref[def_id] <- trait_ref);
1243 self.encode_inherent_implementations(def_id);
1245 hir::ItemKind::Enum(..) |
1246 hir::ItemKind::Struct(..) |
1247 hir::ItemKind::Union(..) |
1248 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1252 hir::ItemKind::Static(..) |
1253 hir::ItemKind::Const(..) |
1254 hir::ItemKind::Fn(..) |
1255 hir::ItemKind::TyAlias(..) |
1256 hir::ItemKind::Enum(..) |
1257 hir::ItemKind::Struct(..) |
1258 hir::ItemKind::Union(..) |
1259 hir::ItemKind::Impl(..) |
1260 hir::ItemKind::OpaqueTy(..) |
1261 hir::ItemKind::Trait(..) |
1262 hir::ItemKind::TraitAlias(..) => {
1263 self.encode_generics(def_id);
1264 self.encode_predicates(def_id);
1268 // The only time that `predicates_defined_on` is used (on
1269 // an external item) is for traits, during chalk lowering,
1270 // so only encode it in that case as an efficiency
1271 // hack. (No reason not to expand it in the future if
1274 hir::ItemKind::Trait(..) |
1275 hir::ItemKind::TraitAlias(..) => {
1276 self.encode_predicates_defined_on(def_id);
1278 _ => {} // not *wrong* for other kinds of items, but not needed
1281 hir::ItemKind::Trait(..) |
1282 hir::ItemKind::TraitAlias(..) => {
1283 self.encode_super_predicates(def_id);
1288 let mir = match item.kind {
1289 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1290 hir::ItemKind::Fn(_, header, ..) => {
1291 let generics = tcx.generics_of(def_id);
1293 (generics.requires_monomorphization(tcx) ||
1294 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1295 !self.metadata_output_only();
1296 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1297 needs_inline || header.constness == hir::Constness::Const || always_encode_mir
1302 self.encode_optimized_mir(def_id);
1303 self.encode_promoted_mir(def_id);
1307 /// Serialize the text of exported macros
1308 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) {
1309 use syntax::print::pprust;
1310 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1311 record!(self.per_def.kind[def_id] <- EntryKind::MacroDef(self.lazy(MacroDef {
1312 body: pprust::tts_to_string(macro_def.body.clone()),
1313 legacy: macro_def.legacy,
1315 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1316 record!(self.per_def.span[def_id] <- macro_def.span);
1317 record!(self.per_def.attributes[def_id] <- ¯o_def.attrs);
1318 self.encode_stability(def_id);
1319 self.encode_deprecation(def_id);
1322 fn encode_info_for_generic_param(
1325 kind: EntryKind<'tcx>,
1328 record!(self.per_def.kind[def_id] <- kind);
1329 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1330 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1332 self.encode_item_type(def_id);
1336 fn encode_info_for_closure(&mut self, def_id: DefId) {
1337 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1339 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1340 // including on the signature, which is inferred in `typeck_tables_of.
1341 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1342 let ty = self.tcx.typeck_tables_of(def_id).node_type(hir_id);
1344 record!(self.per_def.kind[def_id] <- match ty.kind {
1345 ty::Generator(def_id, ..) => {
1346 let layout = self.tcx.generator_layout(def_id);
1347 let data = GeneratorData {
1348 layout: layout.clone(),
1350 EntryKind::Generator(self.lazy(data))
1353 ty::Closure(..) => EntryKind::Closure,
1355 _ => bug!("closure that is neither generator nor closure"),
1357 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1358 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1359 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
1360 self.encode_item_type(def_id);
1361 if let ty::Closure(def_id, substs) = ty.kind {
1362 record!(self.per_def.fn_sig[def_id] <- substs.as_closure().sig(def_id, self.tcx));
1364 self.encode_generics(def_id);
1365 self.encode_optimized_mir(def_id);
1366 self.encode_promoted_mir(def_id);
1369 fn encode_info_for_anon_const(&mut self, def_id: DefId) {
1370 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1371 let id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1372 let body_id = self.tcx.hir().body_owned_by(id);
1373 let const_data = self.encode_rendered_const_for_body(body_id);
1374 let mir = self.tcx.mir_const_qualif(def_id).0;
1376 record!(self.per_def.kind[def_id] <- EntryKind::Const(ConstQualif { mir }, const_data));
1377 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1378 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1379 self.encode_item_type(def_id);
1380 self.encode_generics(def_id);
1381 self.encode_predicates(def_id);
1382 self.encode_optimized_mir(def_id);
1383 self.encode_promoted_mir(def_id);
1386 fn encode_native_libraries(&mut self) -> Lazy<[NativeLibrary]> {
1387 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1388 self.lazy(used_libraries.iter().cloned())
1391 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1392 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1393 self.lazy(foreign_modules.iter().cloned())
1396 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1397 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1400 Some(self.lazy(tcx.hir().krate().items.values().filter_map(|item| {
1401 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
1402 Some(item.hir_id.owner)
1412 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1413 let crates = self.tcx.crates();
1415 let mut deps = crates
1418 let dep = CrateDep {
1419 name: self.tcx.original_crate_name(cnum),
1420 hash: self.tcx.crate_hash(cnum),
1421 host_hash: self.tcx.crate_host_hash(cnum),
1422 kind: self.tcx.dep_kind(cnum),
1423 extra_filename: self.tcx.extra_filename(cnum),
1427 .collect::<Vec<_>>();
1429 deps.sort_by_key(|&(cnum, _)| cnum);
1432 // Sanity-check the crate numbers
1433 let mut expected_cnum = 1;
1434 for &(n, _) in &deps {
1435 assert_eq!(n, CrateNum::new(expected_cnum));
1440 // We're just going to write a list of crate 'name-hash-version's, with
1441 // the assumption that they are numbered 1 to n.
1442 // FIXME (#2166): This is not nearly enough to support correct versioning
1443 // but is enough to get transitive crate dependencies working.
1444 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1447 fn encode_lib_features(&mut self) -> Lazy<[(ast::Name, Option<ast::Name>)]> {
1449 let lib_features = tcx.lib_features();
1450 self.lazy(lib_features.to_vec())
1453 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1455 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1456 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1459 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1461 let lang_items = tcx.lang_items();
1462 let lang_items = lang_items.items().iter();
1463 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1464 if let Some(def_id) = opt_def_id {
1465 if def_id.is_local() {
1466 return Some((def_id.index, i));
1473 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1475 self.lazy(&tcx.lang_items().missing)
1478 /// Encodes an index, mapping each trait to its (local) implementations.
1479 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1480 debug!("EncodeContext::encode_impls()");
1482 let mut visitor = ImplVisitor {
1484 impls: FxHashMap::default(),
1486 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1488 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1490 // Bring everything into deterministic order for hashing
1491 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1492 tcx.def_path_hash(trait_def_id)
1495 let all_impls: Vec<_> = all_impls
1497 .map(|(trait_def_id, mut impls)| {
1498 // Bring everything into deterministic order for hashing
1499 impls.sort_by_cached_key(|&def_index| {
1500 tcx.hir().definitions().def_path_hash(def_index)
1504 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1505 impls: self.lazy(&impls),
1510 self.lazy(&all_impls)
1513 // Encodes all symbols exported from this crate into the metadata.
1515 // This pass is seeded off the reachability list calculated in the
1516 // middle::reachable module but filters out items that either don't have a
1517 // symbol associated with them (they weren't translated) or if they're an FFI
1518 // definition (as that's not defined in this crate).
1519 fn encode_exported_symbols(&mut self,
1520 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)])
1521 -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1522 // The metadata symbol name is special. It should not show up in
1523 // downstream crates.
1524 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1526 self.lazy(exported_symbols
1528 .filter(|&&(ref exported_symbol, _)| {
1529 match *exported_symbol {
1530 ExportedSymbol::NoDefId(symbol_name) => {
1531 symbol_name != metadata_symbol_name
1539 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1540 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1541 for (ty, arr) in formats.iter() {
1542 if *ty != config::CrateType::Dylib {
1545 return self.lazy(arr.iter().map(|slot| {
1547 Linkage::NotLinked |
1548 Linkage::IncludedFromDylib => None,
1550 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1551 Linkage::Static => Some(LinkagePreference::RequireStatic),
1558 fn encode_info_for_foreign_item(
1561 nitem: &hir::ForeignItem,
1565 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1567 record!(self.per_def.kind[def_id] <- match nitem.kind {
1568 hir::ForeignItemKind::Fn(_, ref names, _) => {
1570 asyncness: hir::IsAsync::NotAsync,
1571 constness: hir::Constness::NotConst,
1572 param_names: self.encode_fn_param_names(names),
1574 EntryKind::ForeignFn(self.lazy(data))
1576 hir::ForeignItemKind::Static(_, hir::MutMutable) => EntryKind::ForeignMutStatic,
1577 hir::ForeignItemKind::Static(_, hir::MutImmutable) => EntryKind::ForeignImmStatic,
1578 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1580 record!(self.per_def.visibility[def_id] <-
1581 ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx));
1582 record!(self.per_def.span[def_id] <- nitem.span);
1583 record!(self.per_def.attributes[def_id] <- &nitem.attrs);
1584 self.encode_stability(def_id);
1585 self.encode_deprecation(def_id);
1586 self.encode_item_type(def_id);
1587 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1588 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
1589 self.encode_variances_of(def_id);
1591 self.encode_generics(def_id);
1592 self.encode_predicates(def_id);
1596 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1597 impl Visitor<'tcx> for EncodeContext<'tcx> {
1598 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1599 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1601 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1602 intravisit::walk_expr(self, ex);
1603 self.encode_info_for_expr(ex);
1605 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1606 intravisit::walk_anon_const(self, c);
1607 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1608 self.encode_info_for_anon_const(def_id);
1610 fn visit_item(&mut self, item: &'tcx hir::Item) {
1611 intravisit::walk_item(self, item);
1612 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1614 hir::ItemKind::ExternCrate(_) |
1615 hir::ItemKind::Use(..) => {} // ignore these
1616 _ => self.encode_info_for_item(def_id, item),
1618 self.encode_addl_info_for_item(item);
1620 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1621 intravisit::walk_foreign_item(self, ni);
1622 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1623 self.encode_info_for_foreign_item(def_id, ni);
1625 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1626 intravisit::walk_generics(self, generics);
1627 self.encode_info_for_generics(generics);
1629 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1630 self.encode_info_for_macro_def(macro_def);
1634 impl EncodeContext<'tcx> {
1635 fn encode_fields(&mut self, adt_def_id: DefId) {
1636 let def = self.tcx.adt_def(adt_def_id);
1637 for (variant_index, variant) in def.variants.iter_enumerated() {
1638 for (field_index, _field) in variant.fields.iter().enumerate() {
1639 // FIXME(eddyb) `adt_def_id` is leftover from incremental isolation,
1640 // pass `def`, `variant` or `field` instead.
1641 self.encode_field(adt_def_id, variant_index, field_index);
1646 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1647 for param in &generics.params {
1648 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1650 GenericParamKind::Lifetime { .. } => continue,
1651 GenericParamKind::Type { ref default, .. } => {
1652 self.encode_info_for_generic_param(
1654 EntryKind::TypeParam,
1658 GenericParamKind::Const { .. } => {
1659 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1665 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1667 hir::ExprKind::Closure(..) => {
1668 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1669 self.encode_info_for_closure(def_id);
1675 /// In some cases, along with the item itself, we also
1676 /// encode some sub-items. Usually we want some info from the item
1677 /// so it's easier to do that here then to wait until we would encounter
1678 /// normally in the visitor walk.
1679 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1680 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1682 hir::ItemKind::Static(..) |
1683 hir::ItemKind::Const(..) |
1684 hir::ItemKind::Fn(..) |
1685 hir::ItemKind::Mod(..) |
1686 hir::ItemKind::ForeignMod(..) |
1687 hir::ItemKind::GlobalAsm(..) |
1688 hir::ItemKind::ExternCrate(..) |
1689 hir::ItemKind::Use(..) |
1690 hir::ItemKind::TyAlias(..) |
1691 hir::ItemKind::OpaqueTy(..) |
1692 hir::ItemKind::TraitAlias(..) => {
1693 // no sub-item recording needed in these cases
1695 hir::ItemKind::Enum(..) => {
1696 self.encode_fields(def_id);
1698 let def = self.tcx.adt_def(def_id);
1699 for (i, variant) in def.variants.iter_enumerated() {
1700 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1701 // pass `def` or `variant` instead.
1702 self.encode_enum_variant_info(def_id, i);
1704 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1705 // pass `def`, `variant` or `ctor_def_id` instead.
1706 if let Some(_ctor_def_id) = variant.ctor_def_id {
1707 self.encode_enum_variant_ctor(def_id, i);
1711 hir::ItemKind::Struct(ref struct_def, _) => {
1712 self.encode_fields(def_id);
1714 // If the struct has a constructor, encode it.
1715 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1716 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1717 self.encode_struct_ctor(def_id, ctor_def_id);
1720 hir::ItemKind::Union(..) => {
1721 self.encode_fields(def_id);
1723 hir::ItemKind::Impl(..) => {
1724 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1725 self.encode_info_for_impl_item(trait_item_def_id);
1728 hir::ItemKind::Trait(..) => {
1729 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1730 self.encode_info_for_trait_item(item_def_id);
1737 struct ImplVisitor<'tcx> {
1739 impls: FxHashMap<DefId, Vec<DefIndex>>,
1742 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1743 fn visit_item(&mut self, item: &hir::Item) {
1744 if let hir::ItemKind::Impl(..) = item.kind {
1745 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1746 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1748 .entry(trait_ref.def_id)
1750 .push(impl_id.index);
1755 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1757 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1758 // handled in `visit_item` above
1762 // NOTE(eddyb) The following comment was preserved for posterity, even
1763 // though it's no longer relevant as EBML (which uses nested & tagged
1764 // "documents") was replaced with a scheme that can't go out of bounds.
1766 // And here we run into yet another obscure archive bug: in which metadata
1767 // loaded from archives may have trailing garbage bytes. Awhile back one of
1768 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1769 // and opt) by having ebml generate an out-of-bounds panic when looking at
1772 // Upon investigation it turned out that the metadata file inside of an rlib
1773 // (and ar archive) was being corrupted. Some compilations would generate a
1774 // metadata file which would end in a few extra bytes, while other
1775 // compilations would not have these extra bytes appended to the end. These
1776 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1777 // being interpreted causing the out-of-bounds.
1779 // The root cause of why these extra bytes were appearing was never
1780 // discovered, and in the meantime the solution we're employing is to insert
1781 // the length of the metadata to the start of the metadata. Later on this
1782 // will allow us to slice the metadata to the precise length that we just
1783 // generated regardless of trailing bytes that end up in it.
1785 crate fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1786 let mut encoder = opaque::Encoder::new(vec![]);
1787 encoder.emit_raw_bytes(METADATA_HEADER);
1789 // Will be filled with the root position after encoding everything.
1790 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1792 // Since encoding metadata is not in a query, and nothing is cached,
1793 // there's no need to do dep-graph tracking for any of it.
1794 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1795 let mut ecx = EncodeContext {
1798 per_def: Default::default(),
1799 lazy_state: LazyState::NoNode,
1800 type_shorthands: Default::default(),
1801 predicate_shorthands: Default::default(),
1802 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1803 interpret_allocs: Default::default(),
1804 interpret_allocs_inverse: Default::default(),
1807 // Encode the rustc version string in a predictable location.
1808 rustc_version().encode(&mut ecx).unwrap();
1810 // Encode all the entries and extra information in the crate,
1811 // culminating in the `CrateRoot` which points to all of it.
1812 let root = ecx.encode_crate_root();
1813 (root, ecx.opaque.into_inner())
1816 // Encode the root position.
1817 let header = METADATA_HEADER.len();
1818 let pos = root.position.get();
1819 result[header + 0] = (pos >> 24) as u8;
1820 result[header + 1] = (pos >> 16) as u8;
1821 result[header + 2] = (pos >> 8) as u8;
1822 result[header + 3] = (pos >> 0) as u8;
1824 EncodedMetadata { raw_data: result }