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::proc_macro::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 inherent_impls: PerDefTable<Lazy<[DefIndex]>>,
75 variances: PerDefTable<Lazy<[ty::Variance]>>,
76 generics: PerDefTable<Lazy<ty::Generics>>,
77 predicates: PerDefTable<Lazy<ty::GenericPredicates<'tcx>>>,
78 predicates_defined_on: PerDefTable<Lazy<ty::GenericPredicates<'tcx>>>,
80 mir: PerDefTable<Lazy<mir::Body<'tcx>>>,
81 promoted_mir: PerDefTable<Lazy<IndexVec<mir::Promoted, mir::Body<'tcx>>>>,
84 macro_rules! encoder_methods {
85 ($($name:ident($ty:ty);)*) => {
86 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
87 self.opaque.$name(value)
92 impl<'tcx> Encoder for EncodeContext<'tcx> {
93 type Error = <opaque::Encoder as Encoder>::Error;
95 fn emit_unit(&mut self) -> Result<(), Self::Error> {
122 impl<'tcx, T: Encodable> SpecializedEncoder<Lazy<T>> for EncodeContext<'tcx> {
123 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
124 self.emit_lazy_distance(*lazy)
128 impl<'tcx, T: Encodable> SpecializedEncoder<Lazy<[T]>> for EncodeContext<'tcx> {
129 fn specialized_encode(&mut self, lazy: &Lazy<[T]>) -> Result<(), Self::Error> {
130 self.emit_usize(lazy.meta)?;
134 self.emit_lazy_distance(*lazy)
138 impl<'tcx, T> SpecializedEncoder<Lazy<PerDefTable<T>>> for EncodeContext<'tcx>
139 where Option<T>: FixedSizeEncoding,
141 fn specialized_encode(&mut self, lazy: &Lazy<PerDefTable<T>>) -> Result<(), Self::Error> {
142 self.emit_usize(lazy.meta)?;
143 self.emit_lazy_distance(*lazy)
147 impl<'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'tcx> {
149 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
150 self.emit_u32(cnum.as_u32())
154 impl<'tcx> SpecializedEncoder<DefId> for EncodeContext<'tcx> {
156 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
167 impl<'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'tcx> {
169 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
170 self.emit_u32(def_index.as_u32())
174 impl<'tcx> SpecializedEncoder<Span> for EncodeContext<'tcx> {
175 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
177 return TAG_INVALID_SPAN.encode(self)
180 let span = span.data();
182 // The Span infrastructure should make sure that this invariant holds:
183 debug_assert!(span.lo <= span.hi);
185 if !self.source_file_cache.contains(span.lo) {
186 let source_map = self.tcx.sess.source_map();
187 let source_file_index = source_map.lookup_source_file_idx(span.lo);
188 self.source_file_cache = source_map.files()[source_file_index].clone();
191 if !self.source_file_cache.contains(span.hi) {
192 // Unfortunately, macro expansion still sometimes generates Spans
193 // that malformed in this way.
194 return TAG_INVALID_SPAN.encode(self)
197 TAG_VALID_SPAN.encode(self)?;
198 span.lo.encode(self)?;
200 // Encode length which is usually less than span.hi and profits more
201 // from the variable-length integer encoding that we use.
202 let len = span.hi - span.lo;
205 // Don't encode the expansion context.
209 impl SpecializedEncoder<Ident> for EncodeContext<'tcx> {
210 fn specialized_encode(&mut self, ident: &Ident) -> Result<(), Self::Error> {
211 // FIXME(jseyfried): intercrate hygiene
212 ident.name.encode(self)
216 impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
218 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
219 self.specialized_encode(&def_id.to_def_id())
223 impl<'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'tcx> {
224 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
225 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
229 impl<'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'tcx> {
230 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
231 use std::collections::hash_map::Entry;
232 let index = match self.interpret_allocs.entry(*alloc_id) {
233 Entry::Occupied(e) => *e.get(),
234 Entry::Vacant(e) => {
235 let idx = self.interpret_allocs_inverse.len();
236 self.interpret_allocs_inverse.push(*alloc_id);
246 impl<'tcx> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]> for EncodeContext<'tcx> {
247 fn specialized_encode(&mut self,
248 predicates: &&'tcx [(ty::Predicate<'tcx>, Span)])
249 -> Result<(), Self::Error> {
250 ty_codec::encode_spanned_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
254 impl<'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'tcx> {
255 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
256 f.encode_opaque(&mut self.opaque)
260 impl<'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'tcx> {
261 fn specialized_encode(&mut self,
262 _: &mir::ClearCrossCrate<T>)
263 -> Result<(), Self::Error> {
268 impl<'tcx> TyEncoder for EncodeContext<'tcx> {
269 fn position(&self) -> usize {
270 self.opaque.position()
274 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
275 trait EncodeContentsForLazy<T: ?Sized + LazyMeta> {
276 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> T::Meta;
279 impl<T: Encodable> EncodeContentsForLazy<T> for &T {
280 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
281 self.encode(ecx).unwrap()
285 impl<T: Encodable> EncodeContentsForLazy<T> for T {
286 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
287 self.encode(ecx).unwrap()
291 impl<I, T: Encodable> EncodeContentsForLazy<[T]> for I
292 where I: IntoIterator,
293 I::Item: EncodeContentsForLazy<T>,
295 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> usize {
296 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
300 // Shorthand for `$self.$tables.$table.set($key, $self.lazy($value))`, which would
301 // normally need extra variables to avoid errors about multiple mutable borrows.
302 macro_rules! record {
303 ($self:ident.$tables:ident.$table:ident[$key:expr] <- $value:expr) => {{
306 let lazy = $self.lazy(value);
307 $self.$tables.$table.set($key, lazy);
312 impl<'tcx> EncodeContext<'tcx> {
313 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
316 ) -> Result<(), <Self as Encoder>::Error> {
317 let min_end = lazy.position.get() + T::min_size(lazy.meta);
318 let distance = match self.lazy_state {
319 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
320 LazyState::NodeStart(start) => {
321 let start = start.get();
322 assert!(min_end <= start);
325 LazyState::Previous(last_min_end) => {
327 last_min_end <= lazy.position,
328 "make sure that the calls to `lazy*` \
329 are in the same order as the metadata fields",
331 lazy.position.get() - last_min_end.get()
334 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
335 self.emit_usize(distance)
338 fn lazy<T: ?Sized + LazyMeta>(
340 value: impl EncodeContentsForLazy<T>,
342 let pos = NonZeroUsize::new(self.position()).unwrap();
344 assert_eq!(self.lazy_state, LazyState::NoNode);
345 self.lazy_state = LazyState::NodeStart(pos);
346 let meta = value.encode_contents_for_lazy(self);
347 self.lazy_state = LazyState::NoNode;
349 assert!(pos.get() + <T>::min_size(meta) <= self.position());
351 Lazy::from_position_and_meta(pos, meta)
354 fn encode_info_for_items(&mut self) {
355 let krate = self.tcx.hir().krate();
356 let vis = Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Public };
357 self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.module, &krate.attrs, &vis);
358 krate.visit_all_item_likes(&mut self.as_deep_visitor());
359 for macro_def in &krate.exported_macros {
360 self.visit_macro_def(macro_def);
364 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
365 let definitions = self.tcx.hir().definitions();
366 self.lazy(definitions.def_path_table())
369 fn encode_source_map(&mut self) -> Lazy<[syntax_pos::SourceFile]> {
370 let source_map = self.tcx.sess.source_map();
371 let all_source_files = source_map.files();
373 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
375 let adapted = all_source_files.iter()
376 .filter(|source_file| {
377 // No need to re-export imported source_files, as any downstream
378 // crate will import them from their original source.
379 !source_file.is_imported()
382 match source_file.name {
383 // This path of this SourceFile has been modified by
384 // path-remapping, so we use it verbatim (and avoid
385 // cloning the whole map in the process).
386 _ if source_file.name_was_remapped => source_file.clone(),
388 // Otherwise expand all paths to absolute paths because
389 // any relative paths are potentially relative to a
391 FileName::Real(ref name) => {
392 let mut adapted = (**source_file).clone();
393 adapted.name = Path::new(&working_dir).join(name).into();
394 adapted.name_hash = {
395 let mut hasher: StableHasher = StableHasher::new();
396 adapted.name.hash(&mut hasher);
397 hasher.finish::<u128>()
402 // expanded code, not from a file
403 _ => source_file.clone(),
406 .collect::<Vec<_>>();
408 self.lazy(adapted.iter().map(|rc| &**rc))
411 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
412 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
414 let mut i = self.position();
416 let crate_deps = self.encode_crate_deps();
417 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
418 let dep_bytes = self.position() - i;
420 // Encode the lib features.
422 let lib_features = self.encode_lib_features();
423 let lib_feature_bytes = self.position() - i;
425 // Encode the language items.
427 let lang_items = self.encode_lang_items();
428 let lang_items_missing = self.encode_lang_items_missing();
429 let lang_item_bytes = self.position() - i;
431 // Encode the diagnostic items.
433 let diagnostic_items = self.encode_diagnostic_items();
434 let diagnostic_item_bytes = self.position() - i;
436 // Encode the native libraries used
438 let native_libraries = self.encode_native_libraries();
439 let native_lib_bytes = self.position() - i;
441 let foreign_modules = self.encode_foreign_modules();
445 let source_map = self.encode_source_map();
446 let source_map_bytes = self.position() - i;
448 // Encode DefPathTable
450 let def_path_table = self.encode_def_path_table();
451 let def_path_table_bytes = self.position() - i;
453 // Encode the def IDs of impls, for coherence checking.
455 let impls = self.encode_impls();
456 let impl_bytes = self.position() - i;
458 // Encode exported symbols info.
460 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
461 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
462 let exported_symbols_bytes = self.position() - i;
468 self.encode_info_for_items();
469 let item_bytes = self.position() - i;
471 // Encode the allocation index
472 let interpret_alloc_index = {
473 let mut interpret_alloc_index = Vec::new();
475 trace!("beginning to encode alloc ids");
477 let new_n = self.interpret_allocs_inverse.len();
478 // if we have found new ids, serialize those, too
483 trace!("encoding {} further alloc ids", new_n - n);
484 for idx in n..new_n {
485 let id = self.interpret_allocs_inverse[idx];
486 let pos = self.position() as u32;
487 interpret_alloc_index.push(pos);
488 interpret::specialized_encode_alloc_id(
496 self.lazy(interpret_alloc_index)
501 let per_def = LazyPerDefTables {
502 kind: self.per_def.kind.encode(&mut self.opaque),
503 visibility: self.per_def.visibility.encode(&mut self.opaque),
504 span: self.per_def.span.encode(&mut self.opaque),
505 attributes: self.per_def.attributes.encode(&mut self.opaque),
506 children: self.per_def.children.encode(&mut self.opaque),
507 stability: self.per_def.stability.encode(&mut self.opaque),
508 deprecation: self.per_def.deprecation.encode(&mut self.opaque),
510 ty: self.per_def.ty.encode(&mut self.opaque),
511 inherent_impls: self.per_def.inherent_impls.encode(&mut self.opaque),
512 variances: self.per_def.variances.encode(&mut self.opaque),
513 generics: self.per_def.generics.encode(&mut self.opaque),
514 predicates: self.per_def.predicates.encode(&mut self.opaque),
515 predicates_defined_on: self.per_def.predicates_defined_on.encode(&mut self.opaque),
517 mir: self.per_def.mir.encode(&mut self.opaque),
518 promoted_mir: self.per_def.promoted_mir.encode(&mut self.opaque),
520 let per_def_bytes = self.position() - i;
522 // Encode the proc macro data
524 let proc_macro_data = self.encode_proc_macros();
525 let proc_macro_data_bytes = self.position() - i;
528 let attrs = tcx.hir().krate_attrs();
529 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
530 let has_global_allocator = *tcx.sess.has_global_allocator.get();
531 let has_panic_handler = *tcx.sess.has_panic_handler.try_get().unwrap_or(&false);
533 let root = self.lazy(CrateRoot {
534 name: tcx.crate_name(LOCAL_CRATE),
535 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
536 triple: tcx.sess.opts.target_triple.clone(),
537 hash: tcx.crate_hash(LOCAL_CRATE),
538 disambiguator: tcx.sess.local_crate_disambiguator(),
539 panic_strategy: tcx.sess.panic_strategy(),
540 edition: tcx.sess.edition(),
541 has_global_allocator: has_global_allocator,
542 has_panic_handler: has_panic_handler,
543 has_default_lib_allocator: has_default_lib_allocator,
544 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
545 proc_macro_decls_static: if is_proc_macro {
546 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
552 proc_macro_stability: if is_proc_macro {
553 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| stab.clone())
557 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
558 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
559 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
560 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
561 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
562 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
563 sanitizer_runtime: attr::contains_name(&attrs, sym::sanitizer_runtime),
564 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
567 dylib_dependency_formats,
578 interpret_alloc_index,
582 let total_bytes = self.position();
584 if self.tcx.sess.meta_stats() {
585 let mut zero_bytes = 0;
586 for e in self.opaque.data.iter() {
592 println!("metadata stats:");
593 println!(" dep bytes: {}", dep_bytes);
594 println!(" lib feature bytes: {}", lib_feature_bytes);
595 println!(" lang item bytes: {}", lang_item_bytes);
596 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
597 println!(" native bytes: {}", native_lib_bytes);
598 println!(" source_map bytes: {}", source_map_bytes);
599 println!(" impl bytes: {}", impl_bytes);
600 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
601 println!(" def-path table bytes: {}", def_path_table_bytes);
602 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
603 println!(" item bytes: {}", item_bytes);
604 println!(" per-def table bytes: {}", per_def_bytes);
605 println!(" zero bytes: {}", zero_bytes);
606 println!(" total bytes: {}", total_bytes);
613 impl EncodeContext<'tcx> {
614 fn encode_variances_of(&mut self, def_id: DefId) {
615 debug!("EncodeContext::encode_variances_of({:?})", def_id);
616 record!(self.per_def.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
619 fn encode_item_type(&mut self, def_id: DefId) {
620 debug!("EncodeContext::encode_item_type({:?})", def_id);
621 record!(self.per_def.ty[def_id] <- self.tcx.type_of(def_id));
624 fn encode_enum_variant_info(
630 let def = tcx.adt_def(enum_did);
631 let variant = &def.variants[index];
632 let def_id = variant.def_id;
633 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
635 let data = VariantData {
636 ctor_kind: variant.ctor_kind,
637 discr: variant.discr,
638 // FIXME(eddyb) deduplicate these with `encode_enum_variant_ctor`.
639 ctor: variant.ctor_def_id.map(|did| did.index),
640 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
641 variant.ctor_def_id.map(|ctor_def_id| self.lazy(&tcx.fn_sig(ctor_def_id)))
647 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
648 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
650 record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
651 record!(self.per_def.visibility[def_id] <-
652 ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
653 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
654 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
655 record!(self.per_def.children[def_id] <- variant.fields.iter().map(|f| {
656 assert!(f.did.is_local());
659 self.encode_stability(def_id);
660 self.encode_deprecation(def_id);
661 self.encode_item_type(def_id);
662 if variant.ctor_kind == CtorKind::Fn {
663 self.encode_variances_of(def_id);
665 self.encode_generics(def_id);
666 self.encode_predicates(def_id);
667 self.encode_optimized_mir(def_id);
668 self.encode_promoted_mir(def_id);
671 fn encode_enum_variant_ctor(
677 let def = tcx.adt_def(enum_did);
678 let variant = &def.variants[index];
679 let def_id = variant.ctor_def_id.unwrap();
680 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
682 let data = VariantData {
683 ctor_kind: variant.ctor_kind,
684 discr: variant.discr,
685 ctor: Some(def_id.index),
686 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
687 Some(self.lazy(tcx.fn_sig(def_id)))
693 // Variant constructors have the same visibility as the parent enums, unless marked as
694 // non-exhaustive, in which case they are lowered to `pub(crate)`.
695 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
696 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
697 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
698 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
699 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
702 record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
703 record!(self.per_def.visibility[def_id] <- ctor_vis);
704 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
705 self.encode_stability(def_id);
706 self.encode_deprecation(def_id);
707 self.encode_item_type(def_id);
708 if variant.ctor_kind == CtorKind::Fn {
709 self.encode_variances_of(def_id);
711 self.encode_generics(def_id);
712 self.encode_predicates(def_id);
713 self.encode_optimized_mir(def_id);
714 self.encode_promoted_mir(def_id);
717 fn encode_info_for_mod(
721 attrs: &[ast::Attribute],
722 vis: &hir::Visibility,
725 let def_id = tcx.hir().local_def_id(id);
726 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
729 reexports: match tcx.module_exports(def_id) {
730 Some(exports) => self.lazy(exports),
735 record!(self.per_def.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
736 record!(self.per_def.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
737 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
738 record!(self.per_def.attributes[def_id] <- attrs);
739 record!(self.per_def.children[def_id] <- md.item_ids.iter().map(|item_id| {
740 tcx.hir().local_def_id(item_id.id).index
742 self.encode_stability(def_id);
743 self.encode_deprecation(def_id);
749 variant_index: VariantIdx,
753 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
754 let field = &variant.fields[field_index];
756 let def_id = field.did;
757 debug!("EncodeContext::encode_field({:?})", def_id);
759 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
760 let variant_data = tcx.hir().expect_variant_data(variant_id);
762 record!(self.per_def.kind[def_id] <- EntryKind::Field);
763 record!(self.per_def.visibility[def_id] <- field.vis);
764 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
765 record!(self.per_def.attributes[def_id] <- &variant_data.fields()[field_index].attrs);
766 self.encode_stability(def_id);
767 self.encode_deprecation(def_id);
768 self.encode_item_type(def_id);
769 self.encode_generics(def_id);
770 self.encode_predicates(def_id);
773 fn encode_struct_ctor(&mut self, adt_def_id: DefId, def_id: DefId) {
774 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
776 let adt_def = tcx.adt_def(adt_def_id);
777 let variant = adt_def.non_enum_variant();
779 let data = VariantData {
780 ctor_kind: variant.ctor_kind,
781 discr: variant.discr,
782 ctor: Some(def_id.index),
783 ctor_sig: if variant.ctor_kind == CtorKind::Fn {
784 Some(self.lazy(tcx.fn_sig(def_id)))
790 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
791 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
792 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
793 for field in &variant.fields {
794 if ctor_vis.is_at_least(field.vis, tcx) {
795 ctor_vis = field.vis;
799 // If the structure is marked as non_exhaustive then lower the visibility
800 // to within the crate.
801 if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
802 ctor_vis == ty::Visibility::Public
804 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
807 record!(self.per_def.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
808 record!(self.per_def.visibility[def_id] <- ctor_vis);
809 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
810 self.encode_stability(def_id);
811 self.encode_deprecation(def_id);
812 self.encode_item_type(def_id);
813 if variant.ctor_kind == CtorKind::Fn {
814 self.encode_variances_of(def_id);
816 self.encode_generics(def_id);
817 self.encode_predicates(def_id);
818 self.encode_optimized_mir(def_id);
819 self.encode_promoted_mir(def_id);
822 fn encode_generics(&mut self, def_id: DefId) {
823 debug!("EncodeContext::encode_generics({:?})", def_id);
824 record!(self.per_def.generics[def_id] <- self.tcx.generics_of(def_id));
827 fn encode_predicates(&mut self, def_id: DefId) {
828 debug!("EncodeContext::encode_predicates({:?})", def_id);
829 record!(self.per_def.predicates[def_id] <- self.tcx.predicates_of(def_id));
832 fn encode_predicates_defined_on(&mut self, def_id: DefId) {
833 debug!("EncodeContext::encode_predicates_defined_on({:?})", def_id);
834 record!(self.per_def.predicates_defined_on[def_id] <-
835 self.tcx.predicates_defined_on(def_id))
838 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
839 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
842 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
843 let ast_item = tcx.hir().expect_trait_item(hir_id);
844 let trait_item = tcx.associated_item(def_id);
846 let container = match trait_item.defaultness {
847 hir::Defaultness::Default { has_value: true } =>
848 AssocContainer::TraitWithDefault,
849 hir::Defaultness::Default { has_value: false } =>
850 AssocContainer::TraitRequired,
851 hir::Defaultness::Final =>
852 span_bug!(ast_item.span, "traits cannot have final items"),
855 record!(self.per_def.kind[def_id] <- match trait_item.kind {
856 ty::AssocKind::Const => {
858 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
859 let rendered_const = self.lazy(RenderedConst(rendered));
861 EntryKind::AssocConst(container, ConstQualif { mir: 0 }, rendered_const)
863 ty::AssocKind::Method => {
864 let fn_data = if let hir::TraitItemKind::Method(m_sig, m) = &ast_item.kind {
865 let param_names = match *m {
866 hir::TraitMethod::Required(ref names) => {
867 self.encode_fn_param_names(names)
869 hir::TraitMethod::Provided(body) => {
870 self.encode_fn_param_names_for_body(body)
874 asyncness: m_sig.header.asyncness,
875 constness: hir::Constness::NotConst,
877 sig: self.lazy(tcx.fn_sig(def_id)),
882 EntryKind::Method(self.lazy(MethodData {
885 has_self: trait_item.method_has_self_argument,
888 ty::AssocKind::Type => EntryKind::AssocType(container),
889 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
891 record!(self.per_def.visibility[def_id] <- trait_item.vis);
892 record!(self.per_def.span[def_id] <- ast_item.span);
893 record!(self.per_def.attributes[def_id] <- &ast_item.attrs);
894 self.encode_stability(def_id);
895 self.encode_deprecation(def_id);
896 match trait_item.kind {
897 ty::AssocKind::Const |
898 ty::AssocKind::Method => {
899 self.encode_item_type(def_id);
901 ty::AssocKind::Type => {
902 if trait_item.defaultness.has_value() {
903 self.encode_item_type(def_id);
906 ty::AssocKind::OpaqueTy => unreachable!(),
908 if trait_item.kind == ty::AssocKind::Method {
909 self.encode_variances_of(def_id);
911 self.encode_generics(def_id);
912 self.encode_predicates(def_id);
913 self.encode_optimized_mir(def_id);
914 self.encode_promoted_mir(def_id);
917 fn metadata_output_only(&self) -> bool {
918 // MIR optimisation can be skipped when we're just interested in the metadata.
919 !self.tcx.sess.opts.output_types.should_codegen()
922 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
923 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
926 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
927 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
928 let impl_item = self.tcx.associated_item(def_id);
930 let container = match impl_item.defaultness {
931 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
932 hir::Defaultness::Final => AssocContainer::ImplFinal,
933 hir::Defaultness::Default { has_value: false } =>
934 span_bug!(ast_item.span, "impl items always have values (currently)"),
937 record!(self.per_def.kind[def_id] <- match impl_item.kind {
938 ty::AssocKind::Const => {
939 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
940 let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
942 EntryKind::AssocConst(container,
944 self.encode_rendered_const_for_body(body_id))
949 ty::AssocKind::Method => {
950 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.kind {
952 asyncness: sig.header.asyncness,
953 constness: sig.header.constness,
954 param_names: self.encode_fn_param_names_for_body(body),
955 sig: self.lazy(tcx.fn_sig(def_id)),
960 EntryKind::Method(self.lazy(MethodData {
963 has_self: impl_item.method_has_self_argument,
966 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
967 ty::AssocKind::Type => EntryKind::AssocType(container)
969 record!(self.per_def.visibility[def_id] <- impl_item.vis);
970 record!(self.per_def.span[def_id] <- ast_item.span);
971 record!(self.per_def.attributes[def_id] <- &ast_item.attrs);
972 self.encode_stability(def_id);
973 self.encode_deprecation(def_id);
974 self.encode_item_type(def_id);
975 if impl_item.kind == ty::AssocKind::Method {
976 self.encode_variances_of(def_id);
978 self.encode_generics(def_id);
979 self.encode_predicates(def_id);
980 let mir = match ast_item.kind {
981 hir::ImplItemKind::Const(..) => true,
982 hir::ImplItemKind::Method(ref sig, _) => {
983 let generics = self.tcx.generics_of(def_id);
984 let needs_inline = (generics.requires_monomorphization(self.tcx) ||
985 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
986 !self.metadata_output_only();
987 let is_const_fn = sig.header.constness == hir::Constness::Const;
988 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
989 needs_inline || is_const_fn || always_encode_mir
991 hir::ImplItemKind::OpaqueTy(..) |
992 hir::ImplItemKind::TyAlias(..) => false,
995 self.encode_optimized_mir(def_id);
996 self.encode_promoted_mir(def_id);
1000 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId)
1001 -> Lazy<[ast::Name]> {
1002 self.tcx.dep_graph.with_ignore(|| {
1003 let body = self.tcx.hir().body(body_id);
1004 self.lazy(body.params.iter().map(|arg| {
1005 match arg.pat.kind {
1006 PatKind::Binding(_, _, ident, _) => ident.name,
1013 fn encode_fn_param_names(&mut self, param_names: &[ast::Ident]) -> Lazy<[ast::Name]> {
1014 self.lazy(param_names.iter().map(|ident| ident.name))
1017 fn encode_optimized_mir(&mut self, def_id: DefId) {
1018 debug!("EntryBuilder::encode_mir({:?})", def_id);
1019 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1020 record!(self.per_def.mir[def_id] <- self.tcx.optimized_mir(def_id));
1024 fn encode_promoted_mir(&mut self, def_id: DefId) {
1025 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1026 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1027 record!(self.per_def.promoted_mir[def_id] <- self.tcx.promoted_mir(def_id));
1031 // Encodes the inherent implementations of a structure, enumeration, or trait.
1032 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1033 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1034 let implementations = self.tcx.inherent_impls(def_id);
1035 if !implementations.is_empty() {
1036 record!(self.per_def.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1037 assert!(def_id.is_local());
1043 fn encode_stability(&mut self, def_id: DefId) {
1044 debug!("EncodeContext::encode_stability({:?})", def_id);
1045 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1046 record!(self.per_def.stability[def_id] <- stab)
1050 fn encode_deprecation(&mut self, def_id: DefId) {
1051 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1052 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1053 record!(self.per_def.deprecation[def_id] <- depr);
1057 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1058 let body = self.tcx.hir().body(body_id);
1059 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1060 let rendered_const = &RenderedConst(rendered);
1061 self.lazy(rendered_const)
1064 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item) {
1067 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1069 record!(self.per_def.kind[def_id] <- match item.kind {
1070 hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1071 hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1072 hir::ItemKind::Const(_, body_id) => {
1073 let mir = self.tcx.at(item.span).mir_const_qualif(def_id).0;
1075 ConstQualif { mir },
1076 self.encode_rendered_const_for_body(body_id)
1079 hir::ItemKind::Fn(_, header, .., body) => {
1081 asyncness: header.asyncness,
1082 constness: header.constness,
1083 param_names: self.encode_fn_param_names_for_body(body),
1084 sig: self.lazy(tcx.fn_sig(def_id)),
1087 EntryKind::Fn(self.lazy(data))
1089 hir::ItemKind::Mod(ref m) => {
1090 return self.encode_info_for_mod(item.hir_id, m, &item.attrs, &item.vis);
1092 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1093 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1094 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1095 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1096 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1097 hir::ItemKind::Struct(ref struct_def, _) => {
1098 let adt_def = self.tcx.adt_def(def_id);
1099 let variant = adt_def.non_enum_variant();
1101 // Encode def_ids for each field and method
1102 // for methods, write all the stuff get_trait_method
1104 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1105 self.tcx.hir().local_def_id(ctor_hir_id).index
1108 EntryKind::Struct(self.lazy(VariantData {
1109 ctor_kind: variant.ctor_kind,
1110 discr: variant.discr,
1115 hir::ItemKind::Union(..) => {
1116 let adt_def = self.tcx.adt_def(def_id);
1117 let variant = adt_def.non_enum_variant();
1119 EntryKind::Union(self.lazy(VariantData {
1120 ctor_kind: variant.ctor_kind,
1121 discr: variant.discr,
1126 hir::ItemKind::Impl(_, _, defaultness, ..) => {
1127 let trait_ref = self.tcx.impl_trait_ref(def_id);
1128 let polarity = self.tcx.impl_polarity(def_id);
1129 let parent = if let Some(trait_ref) = trait_ref {
1130 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1131 trait_def.ancestors(self.tcx, def_id).nth(1).and_then(|node| {
1133 specialization_graph::Node::Impl(parent) => Some(parent),
1141 // if this is an impl of `CoerceUnsized`, create its
1142 // "unsized info", else just store None
1143 let coerce_unsized_info =
1144 trait_ref.and_then(|t| {
1145 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1146 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1152 let data = ImplData {
1155 parent_impl: parent,
1156 coerce_unsized_info,
1157 trait_ref: trait_ref.map(|trait_ref| self.lazy(trait_ref)),
1160 EntryKind::Impl(self.lazy(data))
1162 hir::ItemKind::Trait(..) => {
1163 let trait_def = self.tcx.trait_def(def_id);
1164 let data = TraitData {
1165 unsafety: trait_def.unsafety,
1166 paren_sugar: trait_def.paren_sugar,
1167 has_auto_impl: self.tcx.trait_is_auto(def_id),
1168 is_marker: trait_def.is_marker,
1169 super_predicates: self.lazy(tcx.super_predicates_of(def_id)),
1172 EntryKind::Trait(self.lazy(data))
1174 hir::ItemKind::TraitAlias(..) => {
1175 let data = TraitAliasData {
1176 super_predicates: self.lazy(tcx.super_predicates_of(def_id)),
1179 EntryKind::TraitAlias(self.lazy(data))
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 self.encode_inherent_implementations(def_id);
1237 hir::ItemKind::Enum(..) |
1238 hir::ItemKind::Struct(..) |
1239 hir::ItemKind::Union(..) |
1240 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1244 hir::ItemKind::Static(..) |
1245 hir::ItemKind::Const(..) |
1246 hir::ItemKind::Fn(..) |
1247 hir::ItemKind::TyAlias(..) |
1248 hir::ItemKind::Enum(..) |
1249 hir::ItemKind::Struct(..) |
1250 hir::ItemKind::Union(..) |
1251 hir::ItemKind::Impl(..) |
1252 hir::ItemKind::OpaqueTy(..) |
1253 hir::ItemKind::Trait(..) |
1254 hir::ItemKind::TraitAlias(..) => {
1255 self.encode_generics(def_id);
1256 self.encode_predicates(def_id);
1260 // The only time that `predicates_defined_on` is used (on
1261 // an external item) is for traits, during chalk lowering,
1262 // so only encode it in that case as an efficiency
1263 // hack. (No reason not to expand it in the future if
1266 hir::ItemKind::Trait(..) |
1267 hir::ItemKind::TraitAlias(..) => {
1268 self.encode_predicates_defined_on(def_id);
1270 _ => {} // not *wrong* for other kinds of items, but not needed
1273 let mir = match item.kind {
1274 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1275 hir::ItemKind::Fn(_, header, ..) => {
1276 let generics = tcx.generics_of(def_id);
1278 (generics.requires_monomorphization(tcx) ||
1279 tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1280 !self.metadata_output_only();
1281 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1282 needs_inline || header.constness == hir::Constness::Const || always_encode_mir
1287 self.encode_optimized_mir(def_id);
1288 self.encode_promoted_mir(def_id);
1292 /// Serialize the text of exported macros
1293 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) {
1294 use syntax::print::pprust;
1295 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1296 record!(self.per_def.kind[def_id] <- EntryKind::MacroDef(self.lazy(MacroDef {
1297 body: pprust::tts_to_string(macro_def.body.clone()),
1298 legacy: macro_def.legacy,
1300 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1301 record!(self.per_def.span[def_id] <- macro_def.span);
1302 record!(self.per_def.attributes[def_id] <- ¯o_def.attrs);
1303 self.encode_stability(def_id);
1304 self.encode_deprecation(def_id);
1307 fn encode_info_for_generic_param(
1310 kind: EntryKind<'tcx>,
1313 record!(self.per_def.kind[def_id] <- kind);
1314 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1315 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1317 self.encode_item_type(def_id);
1321 fn encode_info_for_closure(&mut self, def_id: DefId) {
1322 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1324 let tables = self.tcx.typeck_tables_of(def_id);
1325 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1327 record!(self.per_def.kind[def_id] <- match tables.node_type(hir_id).kind {
1328 ty::Generator(def_id, ..) => {
1329 let layout = self.tcx.generator_layout(def_id);
1330 let data = GeneratorData {
1331 layout: layout.clone(),
1333 EntryKind::Generator(self.lazy(data))
1336 ty::Closure(def_id, substs) => {
1337 let sig = substs.as_closure().sig(def_id, self.tcx);
1338 let data = ClosureData { sig: self.lazy(sig) };
1339 EntryKind::Closure(self.lazy(data))
1342 _ => bug!("closure that is neither generator nor closure"),
1344 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1345 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1346 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
1347 self.encode_item_type(def_id);
1348 self.encode_generics(def_id);
1349 self.encode_optimized_mir(def_id);
1350 self.encode_promoted_mir(def_id);
1353 fn encode_info_for_anon_const(&mut self, def_id: DefId) {
1354 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1355 let id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1356 let body_id = self.tcx.hir().body_owned_by(id);
1357 let const_data = self.encode_rendered_const_for_body(body_id);
1358 let mir = self.tcx.mir_const_qualif(def_id).0;
1360 record!(self.per_def.kind[def_id] <- EntryKind::Const(ConstQualif { mir }, const_data));
1361 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1362 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1363 self.encode_item_type(def_id);
1364 self.encode_generics(def_id);
1365 self.encode_predicates(def_id);
1366 self.encode_optimized_mir(def_id);
1367 self.encode_promoted_mir(def_id);
1370 fn encode_native_libraries(&mut self) -> Lazy<[NativeLibrary]> {
1371 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1372 self.lazy(used_libraries.iter().cloned())
1375 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1376 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1377 self.lazy(foreign_modules.iter().cloned())
1380 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1381 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1384 Some(self.lazy(tcx.hir().krate().items.values().filter_map(|item| {
1385 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
1386 Some(item.hir_id.owner)
1396 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1397 let crates = self.tcx.crates();
1399 let mut deps = crates
1402 let dep = CrateDep {
1403 name: self.tcx.original_crate_name(cnum),
1404 hash: self.tcx.crate_hash(cnum),
1405 kind: self.tcx.dep_kind(cnum),
1406 extra_filename: self.tcx.extra_filename(cnum),
1410 .collect::<Vec<_>>();
1412 deps.sort_by_key(|&(cnum, _)| cnum);
1415 // Sanity-check the crate numbers
1416 let mut expected_cnum = 1;
1417 for &(n, _) in &deps {
1418 assert_eq!(n, CrateNum::new(expected_cnum));
1423 // We're just going to write a list of crate 'name-hash-version's, with
1424 // the assumption that they are numbered 1 to n.
1425 // FIXME (#2166): This is not nearly enough to support correct versioning
1426 // but is enough to get transitive crate dependencies working.
1427 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1430 fn encode_lib_features(&mut self) -> Lazy<[(ast::Name, Option<ast::Name>)]> {
1432 let lib_features = tcx.lib_features();
1433 self.lazy(lib_features.to_vec())
1436 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1438 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1439 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1442 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1444 let lang_items = tcx.lang_items();
1445 let lang_items = lang_items.items().iter();
1446 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1447 if let Some(def_id) = opt_def_id {
1448 if def_id.is_local() {
1449 return Some((def_id.index, i));
1456 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1458 self.lazy(&tcx.lang_items().missing)
1461 /// Encodes an index, mapping each trait to its (local) implementations.
1462 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1463 debug!("EncodeContext::encode_impls()");
1465 let mut visitor = ImplVisitor {
1467 impls: FxHashMap::default(),
1469 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1471 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1473 // Bring everything into deterministic order for hashing
1474 all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1475 tcx.def_path_hash(trait_def_id)
1478 let all_impls: Vec<_> = all_impls
1480 .map(|(trait_def_id, mut impls)| {
1481 // Bring everything into deterministic order for hashing
1482 impls.sort_by_cached_key(|&def_index| {
1483 tcx.hir().definitions().def_path_hash(def_index)
1487 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1488 impls: self.lazy(&impls),
1493 self.lazy(&all_impls)
1496 // Encodes all symbols exported from this crate into the metadata.
1498 // This pass is seeded off the reachability list calculated in the
1499 // middle::reachable module but filters out items that either don't have a
1500 // symbol associated with them (they weren't translated) or if they're an FFI
1501 // definition (as that's not defined in this crate).
1502 fn encode_exported_symbols(&mut self,
1503 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)])
1504 -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1505 // The metadata symbol name is special. It should not show up in
1506 // downstream crates.
1507 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1509 self.lazy(exported_symbols
1511 .filter(|&&(ref exported_symbol, _)| {
1512 match *exported_symbol {
1513 ExportedSymbol::NoDefId(symbol_name) => {
1514 symbol_name != metadata_symbol_name
1522 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1523 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1524 for (ty, arr) in formats.iter() {
1525 if *ty != config::CrateType::Dylib {
1528 return self.lazy(arr.iter().map(|slot| {
1530 Linkage::NotLinked |
1531 Linkage::IncludedFromDylib => None,
1533 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1534 Linkage::Static => Some(LinkagePreference::RequireStatic),
1541 fn encode_info_for_foreign_item(
1544 nitem: &hir::ForeignItem,
1548 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1550 record!(self.per_def.kind[def_id] <- match nitem.kind {
1551 hir::ForeignItemKind::Fn(_, ref names, _) => {
1553 asyncness: hir::IsAsync::NotAsync,
1554 constness: hir::Constness::NotConst,
1555 param_names: self.encode_fn_param_names(names),
1556 sig: self.lazy(tcx.fn_sig(def_id)),
1558 EntryKind::ForeignFn(self.lazy(data))
1560 hir::ForeignItemKind::Static(_, hir::MutMutable) => EntryKind::ForeignMutStatic,
1561 hir::ForeignItemKind::Static(_, hir::MutImmutable) => EntryKind::ForeignImmStatic,
1562 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1564 record!(self.per_def.visibility[def_id] <-
1565 ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx));
1566 record!(self.per_def.span[def_id] <- nitem.span);
1567 record!(self.per_def.attributes[def_id] <- &nitem.attrs);
1568 self.encode_stability(def_id);
1569 self.encode_deprecation(def_id);
1570 self.encode_item_type(def_id);
1571 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1572 self.encode_variances_of(def_id);
1574 self.encode_generics(def_id);
1575 self.encode_predicates(def_id);
1579 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1580 impl Visitor<'tcx> for EncodeContext<'tcx> {
1581 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1582 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1584 fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1585 intravisit::walk_expr(self, ex);
1586 self.encode_info_for_expr(ex);
1588 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1589 intravisit::walk_anon_const(self, c);
1590 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1591 self.encode_info_for_anon_const(def_id);
1593 fn visit_item(&mut self, item: &'tcx hir::Item) {
1594 intravisit::walk_item(self, item);
1595 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1597 hir::ItemKind::ExternCrate(_) |
1598 hir::ItemKind::Use(..) => {} // ignore these
1599 _ => self.encode_info_for_item(def_id, item),
1601 self.encode_addl_info_for_item(item);
1603 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1604 intravisit::walk_foreign_item(self, ni);
1605 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1606 self.encode_info_for_foreign_item(def_id, ni);
1608 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1609 intravisit::walk_generics(self, generics);
1610 self.encode_info_for_generics(generics);
1612 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1613 self.encode_info_for_macro_def(macro_def);
1617 impl EncodeContext<'tcx> {
1618 fn encode_fields(&mut self, adt_def_id: DefId) {
1619 let def = self.tcx.adt_def(adt_def_id);
1620 for (variant_index, variant) in def.variants.iter_enumerated() {
1621 for (field_index, _field) in variant.fields.iter().enumerate() {
1622 // FIXME(eddyb) `adt_def_id` is leftover from incremental isolation,
1623 // pass `def`, `variant` or `field` instead.
1624 self.encode_field(adt_def_id, variant_index, field_index);
1629 fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1630 for param in &generics.params {
1631 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1633 GenericParamKind::Lifetime { .. } => continue,
1634 GenericParamKind::Type { ref default, .. } => {
1635 self.encode_info_for_generic_param(
1637 EntryKind::TypeParam,
1641 GenericParamKind::Const { .. } => {
1642 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1648 fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1650 hir::ExprKind::Closure(..) => {
1651 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1652 self.encode_info_for_closure(def_id);
1658 /// In some cases, along with the item itself, we also
1659 /// encode some sub-items. Usually we want some info from the item
1660 /// so it's easier to do that here then to wait until we would encounter
1661 /// normally in the visitor walk.
1662 fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1663 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1665 hir::ItemKind::Static(..) |
1666 hir::ItemKind::Const(..) |
1667 hir::ItemKind::Fn(..) |
1668 hir::ItemKind::Mod(..) |
1669 hir::ItemKind::ForeignMod(..) |
1670 hir::ItemKind::GlobalAsm(..) |
1671 hir::ItemKind::ExternCrate(..) |
1672 hir::ItemKind::Use(..) |
1673 hir::ItemKind::TyAlias(..) |
1674 hir::ItemKind::OpaqueTy(..) |
1675 hir::ItemKind::TraitAlias(..) => {
1676 // no sub-item recording needed in these cases
1678 hir::ItemKind::Enum(..) => {
1679 self.encode_fields(def_id);
1681 let def = self.tcx.adt_def(def_id);
1682 for (i, variant) in def.variants.iter_enumerated() {
1683 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1684 // pass `def` or `variant` instead.
1685 self.encode_enum_variant_info(def_id, i);
1687 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1688 // pass `def`, `variant` or `ctor_def_id` instead.
1689 if let Some(_ctor_def_id) = variant.ctor_def_id {
1690 self.encode_enum_variant_ctor(def_id, i);
1694 hir::ItemKind::Struct(ref struct_def, _) => {
1695 self.encode_fields(def_id);
1697 // If the struct has a constructor, encode it.
1698 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1699 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1700 self.encode_struct_ctor(def_id, ctor_def_id);
1703 hir::ItemKind::Union(..) => {
1704 self.encode_fields(def_id);
1706 hir::ItemKind::Impl(..) => {
1707 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1708 self.encode_info_for_impl_item(trait_item_def_id);
1711 hir::ItemKind::Trait(..) => {
1712 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1713 self.encode_info_for_trait_item(item_def_id);
1720 struct ImplVisitor<'tcx> {
1722 impls: FxHashMap<DefId, Vec<DefIndex>>,
1725 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1726 fn visit_item(&mut self, item: &hir::Item) {
1727 if let hir::ItemKind::Impl(..) = item.kind {
1728 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1729 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1731 .entry(trait_ref.def_id)
1733 .push(impl_id.index);
1738 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1740 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1741 // handled in `visit_item` above
1745 // NOTE(eddyb) The following comment was preserved for posterity, even
1746 // though it's no longer relevant as EBML (which uses nested & tagged
1747 // "documents") was replaced with a scheme that can't go out of bounds.
1749 // And here we run into yet another obscure archive bug: in which metadata
1750 // loaded from archives may have trailing garbage bytes. Awhile back one of
1751 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1752 // and opt) by having ebml generate an out-of-bounds panic when looking at
1755 // Upon investigation it turned out that the metadata file inside of an rlib
1756 // (and ar archive) was being corrupted. Some compilations would generate a
1757 // metadata file which would end in a few extra bytes, while other
1758 // compilations would not have these extra bytes appended to the end. These
1759 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1760 // being interpreted causing the out-of-bounds.
1762 // The root cause of why these extra bytes were appearing was never
1763 // discovered, and in the meantime the solution we're employing is to insert
1764 // the length of the metadata to the start of the metadata. Later on this
1765 // will allow us to slice the metadata to the precise length that we just
1766 // generated regardless of trailing bytes that end up in it.
1768 crate fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1769 let mut encoder = opaque::Encoder::new(vec![]);
1770 encoder.emit_raw_bytes(METADATA_HEADER);
1772 // Will be filled with the root position after encoding everything.
1773 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1775 // Since encoding metadata is not in a query, and nothing is cached,
1776 // there's no need to do dep-graph tracking for any of it.
1777 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1778 let mut ecx = EncodeContext {
1781 per_def: Default::default(),
1782 lazy_state: LazyState::NoNode,
1783 type_shorthands: Default::default(),
1784 predicate_shorthands: Default::default(),
1785 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1786 interpret_allocs: Default::default(),
1787 interpret_allocs_inverse: Default::default(),
1790 // Encode the rustc version string in a predictable location.
1791 rustc_version().encode(&mut ecx).unwrap();
1793 // Encode all the entries and extra information in the crate,
1794 // culminating in the `CrateRoot` which points to all of it.
1795 let root = ecx.encode_crate_root();
1796 (root, ecx.opaque.into_inner())
1799 // Encode the root position.
1800 let header = METADATA_HEADER.len();
1801 let pos = root.position.get();
1802 result[header + 0] = (pos >> 24) as u8;
1803 result[header + 1] = (pos >> 16) as u8;
1804 result[header + 2] = (pos >> 8) as u8;
1805 result[header + 3] = (pos >> 0) as u8;
1807 EncodedMetadata { raw_data: result }