]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/encoder.rs
Use assert_eq! in copy_from_slice
[rust.git] / src / librustc_metadata / encoder.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use index::Index;
12 use index_builder::{FromId, IndexBuilder, Untracked};
13 use isolated_encoder::IsolatedEncoder;
14 use schema::*;
15
16 use rustc::middle::cstore::{LinkMeta, LinkagePreference, NativeLibrary,
17                             EncodedMetadata, ForeignModule};
18 use rustc::hir::def::CtorKind;
19 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
20 use rustc::hir::map::definitions::DefPathTable;
21 use rustc::ich::Fingerprint;
22 use rustc::middle::dependency_format::Linkage;
23 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel,
24                                       metadata_symbol_name};
25 use rustc::middle::lang_items;
26 use rustc::mir::{self, interpret};
27 use rustc::traits::specialization_graph;
28 use rustc::ty::{self, Ty, TyCtxt, ReprOptions, SymbolName};
29 use rustc::ty::codec::{self as ty_codec, TyEncoder};
30
31 use rustc::session::config::{self, CrateTypeProcMacro};
32 use rustc::util::nodemap::FxHashMap;
33
34 use rustc_data_structures::stable_hasher::StableHasher;
35 use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
36
37 use std::hash::Hash;
38 use std::io::prelude::*;
39 use std::io::Cursor;
40 use std::path::Path;
41 use rustc_data_structures::sync::Lrc;
42 use std::u32;
43 use syntax::ast::{self, CRATE_NODE_ID};
44 use syntax::codemap::Spanned;
45 use syntax::attr;
46 use syntax::symbol::Symbol;
47 use syntax_pos::{self, hygiene, FileName, FileMap, Span, DUMMY_SP};
48
49 use rustc::hir::{self, PatKind};
50 use rustc::hir::itemlikevisit::ItemLikeVisitor;
51 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
52 use rustc::hir::intravisit;
53
54 pub struct EncodeContext<'a, 'tcx: 'a> {
55     opaque: opaque::Encoder<'a>,
56     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
57     link_meta: &'a LinkMeta,
58
59     lazy_state: LazyState,
60     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
61     predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
62
63     interpret_allocs: FxHashMap<interpret::AllocId, usize>,
64     interpret_allocs_inverse: Vec<interpret::AllocId>,
65
66     // This is used to speed up Span encoding.
67     filemap_cache: Lrc<FileMap>,
68 }
69
70 macro_rules! encoder_methods {
71     ($($name:ident($ty:ty);)*) => {
72         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
73             self.opaque.$name(value)
74         })*
75     }
76 }
77
78 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
79     type Error = <opaque::Encoder<'a> as Encoder>::Error;
80
81     fn emit_nil(&mut self) -> Result<(), Self::Error> {
82         Ok(())
83     }
84
85     encoder_methods! {
86         emit_usize(usize);
87         emit_u128(u128);
88         emit_u64(u64);
89         emit_u32(u32);
90         emit_u16(u16);
91         emit_u8(u8);
92
93         emit_isize(isize);
94         emit_i128(i128);
95         emit_i64(i64);
96         emit_i32(i32);
97         emit_i16(i16);
98         emit_i8(i8);
99
100         emit_bool(bool);
101         emit_f64(f64);
102         emit_f32(f32);
103         emit_char(char);
104         emit_str(&str);
105     }
106 }
107
108 impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
109     fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
110         self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
111     }
112 }
113
114 impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
115     fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
116         self.emit_usize(seq.len)?;
117         if seq.len == 0 {
118             return Ok(());
119         }
120         self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
121     }
122 }
123
124 impl<'a, 'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'a, 'tcx> {
125     #[inline]
126     fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
127         self.emit_u32(cnum.as_u32())
128     }
129 }
130
131 impl<'a, 'tcx> SpecializedEncoder<DefId> for EncodeContext<'a, 'tcx> {
132     #[inline]
133     fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
134         let DefId {
135             krate,
136             index,
137         } = *def_id;
138
139         krate.encode(self)?;
140         index.encode(self)
141     }
142 }
143
144 impl<'a, 'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'a, 'tcx> {
145     #[inline]
146     fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
147         self.emit_u32(def_index.as_raw_u32())
148     }
149 }
150
151 impl<'a, 'tcx> SpecializedEncoder<Span> for EncodeContext<'a, 'tcx> {
152     fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
153         if *span == DUMMY_SP {
154             return TAG_INVALID_SPAN.encode(self)
155         }
156
157         let span = span.data();
158
159         // The Span infrastructure should make sure that this invariant holds:
160         debug_assert!(span.lo <= span.hi);
161
162         if !self.filemap_cache.contains(span.lo) {
163             let codemap = self.tcx.sess.codemap();
164             let filemap_index = codemap.lookup_filemap_idx(span.lo);
165             self.filemap_cache = codemap.files()[filemap_index].clone();
166         }
167
168         if !self.filemap_cache.contains(span.hi) {
169             // Unfortunately, macro expansion still sometimes generates Spans
170             // that malformed in this way.
171             return TAG_INVALID_SPAN.encode(self)
172         }
173
174         TAG_VALID_SPAN.encode(self)?;
175         span.lo.encode(self)?;
176
177         // Encode length which is usually less than span.hi and profits more
178         // from the variable-length integer encoding that we use.
179         let len = span.hi - span.lo;
180         len.encode(self)
181
182         // Don't encode the expansion context.
183     }
184 }
185
186 impl<'a, 'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'a, 'tcx> {
187     #[inline]
188     fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
189         self.specialized_encode(&def_id.to_def_id())
190     }
191 }
192
193 impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
194     fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
195         ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
196     }
197 }
198
199 impl<'a, 'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'a, 'tcx> {
200     fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
201         use std::collections::hash_map::Entry;
202         let index = match self.interpret_allocs.entry(*alloc_id) {
203             Entry::Occupied(e) => *e.get(),
204             Entry::Vacant(e) => {
205                 let idx = self.interpret_allocs_inverse.len();
206                 self.interpret_allocs_inverse.push(*alloc_id);
207                 e.insert(idx);
208                 idx
209             },
210         };
211
212         index.encode(self)
213     }
214 }
215
216 impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
217     fn specialized_encode(&mut self,
218                           predicates: &ty::GenericPredicates<'tcx>)
219                           -> Result<(), Self::Error> {
220         ty_codec::encode_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
221     }
222 }
223
224 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'a, 'tcx> {
225     fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
226         f.encode_opaque(&mut self.opaque)
227     }
228 }
229
230 impl<'a, 'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>>
231 for EncodeContext<'a, 'tcx> {
232     fn specialized_encode(&mut self,
233                           _: &mir::ClearCrossCrate<T>)
234                           -> Result<(), Self::Error> {
235         Ok(())
236     }
237 }
238
239 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
240     fn position(&self) -> usize {
241         self.opaque.position()
242     }
243 }
244
245 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
246
247     fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
248         assert_eq!(self.lazy_state, LazyState::NoNode);
249         let pos = self.position();
250         self.lazy_state = LazyState::NodeStart(pos);
251         let r = f(self, pos);
252         self.lazy_state = LazyState::NoNode;
253         r
254     }
255
256     fn emit_lazy_distance(&mut self,
257                           position: usize,
258                           min_size: usize)
259                           -> Result<(), <Self as Encoder>::Error> {
260         let min_end = position + min_size;
261         let distance = match self.lazy_state {
262             LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
263             LazyState::NodeStart(start) => {
264                 assert!(min_end <= start);
265                 start - min_end
266             }
267             LazyState::Previous(last_min_end) => {
268                 assert!(
269                     last_min_end <= position,
270                     "make sure that the calls to `lazy*` \
271                     are in the same order as the metadata fields",
272                 );
273                 position - last_min_end
274             }
275         };
276         self.lazy_state = LazyState::Previous(min_end);
277         self.emit_usize(distance)
278     }
279
280     pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
281         self.emit_node(|ecx, pos| {
282             value.encode(ecx).unwrap();
283
284             assert!(pos + Lazy::<T>::min_size() <= ecx.position());
285             Lazy::with_position(pos)
286         })
287     }
288
289     pub fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
290         where I: IntoIterator<Item = T>,
291               T: Encodable
292     {
293         self.emit_node(|ecx, pos| {
294             let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
295
296             assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
297             LazySeq::with_position_and_length(pos, len)
298         })
299     }
300
301     pub fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
302         where I: IntoIterator<Item = &'b T>,
303               T: 'b + Encodable
304     {
305         self.emit_node(|ecx, pos| {
306             let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();
307
308             assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
309             LazySeq::with_position_and_length(pos, len)
310         })
311     }
312
313     // Encodes something that corresponds to a single DepNode::GlobalMetaData
314     // and registers the Fingerprint in the `metadata_hashes` map.
315     pub fn tracked<'x, DATA, R>(&'x mut self,
316                                 op: fn(&mut IsolatedEncoder<'x, 'a, 'tcx>, DATA) -> R,
317                                 data: DATA)
318                                 -> R {
319         op(&mut IsolatedEncoder::new(self), data)
320     }
321
322     fn encode_info_for_items(&mut self) -> Index {
323         let krate = self.tcx.hir.krate();
324         let mut index = IndexBuilder::new(self);
325         index.record(DefId::local(CRATE_DEF_INDEX),
326                      IsolatedEncoder::encode_info_for_mod,
327                      FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
328         let mut visitor = EncodeVisitor { index: index };
329         krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
330         for macro_def in &krate.exported_macros {
331             visitor.visit_macro_def(macro_def);
332         }
333         visitor.index.into_items()
334     }
335
336     fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
337         let definitions = self.tcx.hir.definitions();
338         self.lazy(definitions.def_path_table())
339     }
340
341     fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
342         let codemap = self.tcx.sess.codemap();
343         let all_filemaps = codemap.files();
344
345         let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone();
346
347         let adapted = all_filemaps.iter()
348             .filter(|filemap| {
349                 // No need to re-export imported filemaps, as any downstream
350                 // crate will import them from their original source.
351                 !filemap.is_imported()
352             })
353             .map(|filemap| {
354                 // When exporting FileMaps, we expand all paths to absolute
355                 // paths because any relative paths are potentially relative to
356                 // a wrong directory.
357                 // However, if a path has been modified via
358                 // `--remap-path-prefix` we assume the user has already set
359                 // things up the way they want and don't touch the path values
360                 // anymore.
361                 match filemap.name {
362                     FileName::Real(ref name) => {
363                         if filemap.name_was_remapped ||
364                         (name.is_relative() && working_dir_was_remapped) {
365                             // This path of this FileMap has been modified by
366                             // path-remapping, so we use it verbatim (and avoid cloning
367                             // the whole map in the process).
368                             filemap.clone()
369                         } else {
370                             let mut adapted = (**filemap).clone();
371                             adapted.name = Path::new(&working_dir).join(name).into();
372                             adapted.name_hash = {
373                                 let mut hasher: StableHasher<u128> = StableHasher::new();
374                                 adapted.name.hash(&mut hasher);
375                                 hasher.finish()
376                             };
377                             Lrc::new(adapted)
378                         }
379                     },
380                     // expanded code, not from a file
381                     _ => filemap.clone(),
382                 }
383             })
384             .collect::<Vec<_>>();
385
386         self.lazy_seq_ref(adapted.iter().map(|rc| &**rc))
387     }
388
389     fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
390         let mut i = self.position();
391
392         let crate_deps = self.tracked(IsolatedEncoder::encode_crate_deps, ());
393         let dylib_dependency_formats = self.tracked(
394             IsolatedEncoder::encode_dylib_dependency_formats,
395             ());
396         let dep_bytes = self.position() - i;
397
398         // Encode the language items.
399         i = self.position();
400         let lang_items = self.tracked(IsolatedEncoder::encode_lang_items, ());
401         let lang_items_missing = self.tracked(
402             IsolatedEncoder::encode_lang_items_missing,
403             ());
404         let lang_item_bytes = self.position() - i;
405
406         // Encode the native libraries used
407         i = self.position();
408         let native_libraries = self.tracked(
409             IsolatedEncoder::encode_native_libraries,
410             ());
411         let native_lib_bytes = self.position() - i;
412
413         let foreign_modules = self.tracked(
414             IsolatedEncoder::encode_foreign_modules,
415             ());
416
417         // Encode codemap
418         i = self.position();
419         let codemap = self.encode_codemap();
420         let codemap_bytes = self.position() - i;
421
422         // Encode DefPathTable
423         i = self.position();
424         let def_path_table = self.encode_def_path_table();
425         let def_path_table_bytes = self.position() - i;
426
427         // Encode the def IDs of impls, for coherence checking.
428         i = self.position();
429         let impls = self.tracked(IsolatedEncoder::encode_impls, ());
430         let impl_bytes = self.position() - i;
431
432         // Encode exported symbols info.
433         i = self.position();
434         let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
435         let exported_symbols = self.tracked(
436             IsolatedEncoder::encode_exported_symbols,
437             &exported_symbols);
438         let exported_symbols_bytes = self.position() - i;
439
440         // encode wasm custom sections
441         let wasm_custom_sections = self.tcx.wasm_custom_sections(LOCAL_CRATE);
442         let wasm_custom_sections = self.tracked(
443             IsolatedEncoder::encode_wasm_custom_sections,
444             &wasm_custom_sections);
445
446         let tcx = self.tcx;
447
448         // Encode the items.
449         i = self.position();
450         let items = self.encode_info_for_items();
451         let item_bytes = self.position() - i;
452
453         // Encode the allocation index
454         let interpret_alloc_index = {
455             let mut interpret_alloc_index = Vec::new();
456             let mut n = 0;
457             trace!("beginning to encode alloc ids");
458             loop {
459                 let new_n = self.interpret_allocs_inverse.len();
460                 // if we have found new ids, serialize those, too
461                 if n == new_n {
462                     // otherwise, abort
463                     break;
464                 }
465                 trace!("encoding {} further alloc ids", new_n - n);
466                 for idx in n..new_n {
467                     let id = self.interpret_allocs_inverse[idx];
468                     let pos = self.position() as u32;
469                     interpret_alloc_index.push(pos);
470                     interpret::specialized_encode_alloc_id(
471                         self,
472                         tcx,
473                         id,
474                     ).unwrap();
475                 }
476                 n = new_n;
477             }
478             self.lazy_seq(interpret_alloc_index)
479         };
480
481         // Index the items
482         i = self.position();
483         let index = items.write_index(&mut self.opaque.cursor);
484         let index_bytes = self.position() - i;
485
486         let attrs = tcx.hir.krate_attrs();
487         let link_meta = self.link_meta;
488         let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
489         let has_default_lib_allocator = attr::contains_name(&attrs, "default_lib_allocator");
490         let has_global_allocator = *tcx.sess.has_global_allocator.get();
491
492         let root = self.lazy(&CrateRoot {
493             name: tcx.crate_name(LOCAL_CRATE),
494             extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
495             triple: tcx.sess.opts.target_triple.clone(),
496             hash: link_meta.crate_hash,
497             disambiguator: tcx.sess.local_crate_disambiguator(),
498             panic_strategy: tcx.sess.panic_strategy(),
499             edition: hygiene::default_edition(),
500             has_global_allocator: has_global_allocator,
501             has_default_lib_allocator: has_default_lib_allocator,
502             plugin_registrar_fn: tcx.sess
503                 .plugin_registrar_fn
504                 .get()
505                 .map(|id| tcx.hir.local_def_id(id).index),
506             macro_derive_registrar: if is_proc_macro {
507                 let id = tcx.sess.derive_registrar_fn.get().unwrap();
508                 Some(tcx.hir.local_def_id(id).index)
509             } else {
510                 None
511             },
512
513             compiler_builtins: attr::contains_name(&attrs, "compiler_builtins"),
514             needs_allocator: attr::contains_name(&attrs, "needs_allocator"),
515             needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"),
516             no_builtins: attr::contains_name(&attrs, "no_builtins"),
517             panic_runtime: attr::contains_name(&attrs, "panic_runtime"),
518             profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"),
519             sanitizer_runtime: attr::contains_name(&attrs, "sanitizer_runtime"),
520
521             crate_deps,
522             dylib_dependency_formats,
523             lang_items,
524             lang_items_missing,
525             native_libraries,
526             foreign_modules,
527             codemap,
528             def_path_table,
529             impls,
530             exported_symbols,
531             wasm_custom_sections,
532             interpret_alloc_index,
533             index,
534         });
535
536         let total_bytes = self.position();
537
538         if self.tcx.sess.meta_stats() {
539             let mut zero_bytes = 0;
540             for e in self.opaque.cursor.get_ref() {
541                 if *e == 0 {
542                     zero_bytes += 1;
543                 }
544             }
545
546             println!("metadata stats:");
547             println!("             dep bytes: {}", dep_bytes);
548             println!("       lang item bytes: {}", lang_item_bytes);
549             println!("          native bytes: {}", native_lib_bytes);
550             println!("         codemap bytes: {}", codemap_bytes);
551             println!("            impl bytes: {}", impl_bytes);
552             println!("    exp. symbols bytes: {}", exported_symbols_bytes);
553             println!("  def-path table bytes: {}", def_path_table_bytes);
554             println!("            item bytes: {}", item_bytes);
555             println!("           index bytes: {}", index_bytes);
556             println!("            zero bytes: {}", zero_bytes);
557             println!("           total bytes: {}", total_bytes);
558         }
559
560         root
561     }
562 }
563
564 // These are methods for encoding various things. They are meant to be used with
565 // IndexBuilder::record() and EncodeContext::tracked(). They actually
566 // would not have to be methods of IsolatedEncoder (free standing functions
567 // taking IsolatedEncoder as first argument would be just fine) but by making
568 // them methods we don't have to repeat the lengthy `<'a, 'b: 'a, 'tcx: 'b>`
569 // clause again and again.
570 impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
571     fn encode_variances_of(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
572         debug!("IsolatedEncoder::encode_variances_of({:?})", def_id);
573         let tcx = self.tcx;
574         self.lazy_seq_from_slice(&tcx.variances_of(def_id))
575     }
576
577     fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
578         let tcx = self.tcx;
579         let ty = tcx.type_of(def_id);
580         debug!("IsolatedEncoder::encode_item_type({:?}) => {:?}", def_id, ty);
581         self.lazy(&ty)
582     }
583
584     /// Encode data for the given variant of the given ADT. The
585     /// index of the variant is untracked: this is ok because we
586     /// will have to lookup the adt-def by its id, and that gives us
587     /// the right to access any information in the adt-def (including,
588     /// e.g., the length of the various vectors).
589     fn encode_enum_variant_info(&mut self,
590                                 (enum_did, Untracked(index)): (DefId, Untracked<usize>))
591                                 -> Entry<'tcx> {
592         let tcx = self.tcx;
593         let def = tcx.adt_def(enum_did);
594         let variant = &def.variants[index];
595         let def_id = variant.did;
596         debug!("IsolatedEncoder::encode_enum_variant_info({:?})", def_id);
597
598         let data = VariantData {
599             ctor_kind: variant.ctor_kind,
600             discr: variant.discr,
601             struct_ctor: None,
602             ctor_sig: if variant.ctor_kind == CtorKind::Fn {
603                 Some(self.lazy(&tcx.fn_sig(def_id)))
604             } else {
605                 None
606             }
607         };
608
609         let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
610         let enum_vis = &tcx.hir.expect_item(enum_id).vis;
611
612         Entry {
613             kind: EntryKind::Variant(self.lazy(&data)),
614             visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
615             span: self.lazy(&tcx.def_span(def_id)),
616             attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
617             children: self.lazy_seq(variant.fields.iter().map(|f| {
618                 assert!(f.did.is_local());
619                 f.did.index
620             })),
621             stability: self.encode_stability(def_id),
622             deprecation: self.encode_deprecation(def_id),
623
624             ty: Some(self.encode_item_type(def_id)),
625             inherent_impls: LazySeq::empty(),
626             variances: if variant.ctor_kind == CtorKind::Fn {
627                 self.encode_variances_of(def_id)
628             } else {
629                 LazySeq::empty()
630             },
631             generics: Some(self.encode_generics(def_id)),
632             predicates: Some(self.encode_predicates(def_id)),
633
634             mir: self.encode_optimized_mir(def_id),
635         }
636     }
637
638     fn encode_info_for_mod(&mut self,
639                            FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
640                                                                  &[ast::Attribute],
641                                                                  &hir::Visibility)>)
642                            -> Entry<'tcx> {
643         let tcx = self.tcx;
644         let def_id = tcx.hir.local_def_id(id);
645         debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
646
647         let data = ModData {
648             reexports: match tcx.module_exports(def_id) {
649                 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
650                 _ => LazySeq::empty(),
651             },
652         };
653
654         Entry {
655             kind: EntryKind::Mod(self.lazy(&data)),
656             visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
657             span: self.lazy(&tcx.def_span(def_id)),
658             attributes: self.encode_attributes(attrs),
659             children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
660                 tcx.hir.local_def_id(item_id.id).index
661             })),
662             stability: self.encode_stability(def_id),
663             deprecation: self.encode_deprecation(def_id),
664
665             ty: None,
666             inherent_impls: LazySeq::empty(),
667             variances: LazySeq::empty(),
668             generics: None,
669             predicates: None,
670
671             mir: None
672         }
673     }
674
675     /// Encode data for the given field of the given variant of the
676     /// given ADT. The indices of the variant/field are untracked:
677     /// this is ok because we will have to lookup the adt-def by its
678     /// id, and that gives us the right to access any information in
679     /// the adt-def (including, e.g., the length of the various
680     /// vectors).
681     fn encode_field(&mut self,
682                     (adt_def_id, Untracked((variant_index, field_index))): (DefId,
683                                                                             Untracked<(usize,
684                                                                                        usize)>))
685                     -> Entry<'tcx> {
686         let tcx = self.tcx;
687         let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
688         let field = &variant.fields[field_index];
689
690         let def_id = field.did;
691         debug!("IsolatedEncoder::encode_field({:?})", def_id);
692
693         let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
694         let variant_data = tcx.hir.expect_variant_data(variant_id);
695
696         Entry {
697             kind: EntryKind::Field,
698             visibility: self.lazy(&field.vis),
699             span: self.lazy(&tcx.def_span(def_id)),
700             attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
701             children: LazySeq::empty(),
702             stability: self.encode_stability(def_id),
703             deprecation: self.encode_deprecation(def_id),
704
705             ty: Some(self.encode_item_type(def_id)),
706             inherent_impls: LazySeq::empty(),
707             variances: LazySeq::empty(),
708             generics: Some(self.encode_generics(def_id)),
709             predicates: Some(self.encode_predicates(def_id)),
710
711             mir: None,
712         }
713     }
714
715     fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
716         debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
717         let tcx = self.tcx;
718         let adt_def = tcx.adt_def(adt_def_id);
719         let variant = adt_def.non_enum_variant();
720
721         let data = VariantData {
722             ctor_kind: variant.ctor_kind,
723             discr: variant.discr,
724             struct_ctor: Some(def_id.index),
725             ctor_sig: if variant.ctor_kind == CtorKind::Fn {
726                 Some(self.lazy(&tcx.fn_sig(def_id)))
727             } else {
728                 None
729             }
730         };
731
732         let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
733         let struct_vis = &tcx.hir.expect_item(struct_id).vis;
734         let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
735         for field in &variant.fields {
736             if ctor_vis.is_at_least(field.vis, tcx) {
737                 ctor_vis = field.vis;
738             }
739         }
740
741         // If the structure is marked as non_exhaustive then lower the visibility
742         // to within the crate.
743         if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
744             ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
745         }
746
747         let repr_options = get_repr_options(&tcx, adt_def_id);
748
749         Entry {
750             kind: EntryKind::Struct(self.lazy(&data), repr_options),
751             visibility: self.lazy(&ctor_vis),
752             span: self.lazy(&tcx.def_span(def_id)),
753             attributes: LazySeq::empty(),
754             children: LazySeq::empty(),
755             stability: self.encode_stability(def_id),
756             deprecation: self.encode_deprecation(def_id),
757
758             ty: Some(self.encode_item_type(def_id)),
759             inherent_impls: LazySeq::empty(),
760             variances: if variant.ctor_kind == CtorKind::Fn {
761                 self.encode_variances_of(def_id)
762             } else {
763                 LazySeq::empty()
764             },
765             generics: Some(self.encode_generics(def_id)),
766             predicates: Some(self.encode_predicates(def_id)),
767
768             mir: self.encode_optimized_mir(def_id),
769         }
770     }
771
772     fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
773         debug!("IsolatedEncoder::encode_generics({:?})", def_id);
774         let tcx = self.tcx;
775         self.lazy(tcx.generics_of(def_id))
776     }
777
778     fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
779         debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
780         let tcx = self.tcx;
781         self.lazy(&tcx.predicates_of(def_id))
782     }
783
784     fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
785         debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
786         let tcx = self.tcx;
787
788         let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
789         let ast_item = tcx.hir.expect_trait_item(node_id);
790         let trait_item = tcx.associated_item(def_id);
791
792         let container = match trait_item.defaultness {
793             hir::Defaultness::Default { has_value: true } =>
794                 AssociatedContainer::TraitWithDefault,
795             hir::Defaultness::Default { has_value: false } =>
796                 AssociatedContainer::TraitRequired,
797             hir::Defaultness::Final =>
798                 span_bug!(ast_item.span, "traits cannot have final items"),
799         };
800
801         let kind = match trait_item.kind {
802             ty::AssociatedKind::Const => {
803                 let const_qualif =
804                     if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
805                         self.const_qualif(0, body)
806                     } else {
807                         ConstQualif { mir: 0, ast_promotable: false }
808                     };
809
810                 let rendered =
811                     hir::print::to_string(&self.tcx.hir, |s| s.print_trait_item(ast_item));
812                 let rendered_const = self.lazy(&RenderedConst(rendered));
813
814                 EntryKind::AssociatedConst(container, const_qualif, rendered_const)
815             }
816             ty::AssociatedKind::Method => {
817                 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
818                     let arg_names = match *m {
819                         hir::TraitMethod::Required(ref names) => {
820                             self.encode_fn_arg_names(names)
821                         }
822                         hir::TraitMethod::Provided(body) => {
823                             self.encode_fn_arg_names_for_body(body)
824                         }
825                     };
826                     FnData {
827                         constness: hir::Constness::NotConst,
828                         arg_names,
829                         sig: self.lazy(&tcx.fn_sig(def_id)),
830                     }
831                 } else {
832                     bug!()
833                 };
834                 EntryKind::Method(self.lazy(&MethodData {
835                     fn_data,
836                     container,
837                     has_self: trait_item.method_has_self_argument,
838                 }))
839             }
840             ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
841         };
842
843         Entry {
844             kind,
845             visibility: self.lazy(&trait_item.vis),
846             span: self.lazy(&ast_item.span),
847             attributes: self.encode_attributes(&ast_item.attrs),
848             children: LazySeq::empty(),
849             stability: self.encode_stability(def_id),
850             deprecation: self.encode_deprecation(def_id),
851
852             ty: match trait_item.kind {
853                 ty::AssociatedKind::Const |
854                 ty::AssociatedKind::Method => {
855                     Some(self.encode_item_type(def_id))
856                 }
857                 ty::AssociatedKind::Type => {
858                     if trait_item.defaultness.has_value() {
859                         Some(self.encode_item_type(def_id))
860                     } else {
861                         None
862                     }
863                 }
864             },
865             inherent_impls: LazySeq::empty(),
866             variances: if trait_item.kind == ty::AssociatedKind::Method {
867                 self.encode_variances_of(def_id)
868             } else {
869                 LazySeq::empty()
870             },
871             generics: Some(self.encode_generics(def_id)),
872             predicates: Some(self.encode_predicates(def_id)),
873
874             mir: self.encode_optimized_mir(def_id),
875         }
876     }
877
878     fn metadata_output_only(&self) -> bool {
879         // MIR optimisation can be skipped when we're just interested in the metadata.
880         !self.tcx.sess.opts.output_types.should_codegen()
881     }
882
883     fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
884         let body_owner_def_id = self.tcx.hir.body_owner_def_id(body_id);
885         let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
886
887         ConstQualif { mir, ast_promotable }
888     }
889
890     fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
891         debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
892         let tcx = self.tcx;
893
894         let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
895         let ast_item = self.tcx.hir.expect_impl_item(node_id);
896         let impl_item = self.tcx.associated_item(def_id);
897
898         let container = match impl_item.defaultness {
899             hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
900             hir::Defaultness::Final => AssociatedContainer::ImplFinal,
901             hir::Defaultness::Default { has_value: false } =>
902                 span_bug!(ast_item.span, "impl items always have values (currently)"),
903         };
904
905         let kind = match impl_item.kind {
906             ty::AssociatedKind::Const => {
907                 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
908                     let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
909
910                     EntryKind::AssociatedConst(container,
911                         self.const_qualif(mir, body_id),
912                         self.encode_rendered_const_for_body(body_id))
913                 } else {
914                     bug!()
915                 }
916             }
917             ty::AssociatedKind::Method => {
918                 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
919                     FnData {
920                         constness: sig.header.constness,
921                         arg_names: self.encode_fn_arg_names_for_body(body),
922                         sig: self.lazy(&tcx.fn_sig(def_id)),
923                     }
924                 } else {
925                     bug!()
926                 };
927                 EntryKind::Method(self.lazy(&MethodData {
928                     fn_data,
929                     container,
930                     has_self: impl_item.method_has_self_argument,
931                 }))
932             }
933             ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
934         };
935
936         let mir =
937             match ast_item.node {
938                 hir::ImplItemKind::Const(..) => true,
939                 hir::ImplItemKind::Method(ref sig, _) => {
940                     let generics = self.tcx.generics_of(def_id);
941                     let needs_inline = (generics.requires_monomorphization(self.tcx) ||
942                                         tcx.codegen_fn_attrs(def_id).requests_inline()) &&
943                                         !self.metadata_output_only();
944                     let is_const_fn = sig.header.constness == hir::Constness::Const;
945                     let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
946                     needs_inline || is_const_fn || always_encode_mir
947                 },
948                 hir::ImplItemKind::Type(..) => false,
949             };
950
951         Entry {
952             kind,
953             visibility: self.lazy(&impl_item.vis),
954             span: self.lazy(&ast_item.span),
955             attributes: self.encode_attributes(&ast_item.attrs),
956             children: LazySeq::empty(),
957             stability: self.encode_stability(def_id),
958             deprecation: self.encode_deprecation(def_id),
959
960             ty: Some(self.encode_item_type(def_id)),
961             inherent_impls: LazySeq::empty(),
962             variances: if impl_item.kind == ty::AssociatedKind::Method {
963                 self.encode_variances_of(def_id)
964             } else {
965                 LazySeq::empty()
966             },
967             generics: Some(self.encode_generics(def_id)),
968             predicates: Some(self.encode_predicates(def_id)),
969
970             mir: if mir { self.encode_optimized_mir(def_id) } else { None },
971         }
972     }
973
974     fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
975                                     -> LazySeq<ast::Name> {
976         self.tcx.dep_graph.with_ignore(|| {
977             let body = self.tcx.hir.body(body_id);
978             self.lazy_seq(body.arguments.iter().map(|arg| {
979                 match arg.pat.node {
980                     PatKind::Binding(_, _, name, _) => name.node,
981                     _ => Symbol::intern("")
982                 }
983             }))
984         })
985     }
986
987     fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
988                            -> LazySeq<ast::Name> {
989         self.lazy_seq(names.iter().map(|name| name.node))
990     }
991
992     fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
993         debug!("EntryBuilder::encode_mir({:?})", def_id);
994         if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
995             let mir = self.tcx.optimized_mir(def_id);
996             Some(self.lazy(&mir))
997         } else {
998             None
999         }
1000     }
1001
1002     // Encodes the inherent implementations of a structure, enumeration, or trait.
1003     fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1004         debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
1005         let implementations = self.tcx.inherent_impls(def_id);
1006         if implementations.is_empty() {
1007             LazySeq::empty()
1008         } else {
1009             self.lazy_seq(implementations.iter().map(|&def_id| {
1010                 assert!(def_id.is_local());
1011                 def_id.index
1012             }))
1013         }
1014     }
1015
1016     fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1017         debug!("IsolatedEncoder::encode_stability({:?})", def_id);
1018         self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1019     }
1020
1021     fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1022         debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
1023         self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1024     }
1025
1026     fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1027         let body = self.tcx.hir.body(body_id);
1028         let rendered = hir::print::to_string(&self.tcx.hir, |s| s.print_expr(&body.value));
1029         let rendered_const = &RenderedConst(rendered);
1030         self.lazy(rendered_const)
1031     }
1032
1033     fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1034         let tcx = self.tcx;
1035
1036         debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
1037
1038         let kind = match item.node {
1039             hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
1040             hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1041             hir::ItemConst(_, body_id) => {
1042                 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1043                 EntryKind::Const(
1044                     self.const_qualif(mir, body_id),
1045                     self.encode_rendered_const_for_body(body_id)
1046                 )
1047             }
1048             hir::ItemFn(_, header, .., body) => {
1049                 let data = FnData {
1050                     constness: header.constness,
1051                     arg_names: self.encode_fn_arg_names_for_body(body),
1052                     sig: self.lazy(&tcx.fn_sig(def_id)),
1053                 };
1054
1055                 EntryKind::Fn(self.lazy(&data))
1056             }
1057             hir::ItemMod(ref m) => {
1058                 return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
1059             }
1060             hir::ItemForeignMod(_) => EntryKind::ForeignMod,
1061             hir::ItemGlobalAsm(..) => EntryKind::GlobalAsm,
1062             hir::ItemTy(..) => EntryKind::Type,
1063             hir::ItemExistential(..) => EntryKind::Existential,
1064             hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
1065             hir::ItemStruct(ref struct_def, _) => {
1066                 let variant = tcx.adt_def(def_id).non_enum_variant();
1067
1068                 // Encode def_ids for each field and method
1069                 // for methods, write all the stuff get_trait_method
1070                 // needs to know
1071                 let struct_ctor = if !struct_def.is_struct() {
1072                     Some(tcx.hir.local_def_id(struct_def.id()).index)
1073                 } else {
1074                     None
1075                 };
1076
1077                 let repr_options = get_repr_options(&tcx, def_id);
1078
1079                 EntryKind::Struct(self.lazy(&VariantData {
1080                     ctor_kind: variant.ctor_kind,
1081                     discr: variant.discr,
1082                     struct_ctor,
1083                     ctor_sig: None,
1084                 }), repr_options)
1085             }
1086             hir::ItemUnion(..) => {
1087                 let variant = tcx.adt_def(def_id).non_enum_variant();
1088                 let repr_options = get_repr_options(&tcx, def_id);
1089
1090                 EntryKind::Union(self.lazy(&VariantData {
1091                     ctor_kind: variant.ctor_kind,
1092                     discr: variant.discr,
1093                     struct_ctor: None,
1094                     ctor_sig: None,
1095                 }), repr_options)
1096             }
1097             hir::ItemImpl(_, polarity, defaultness, ..) => {
1098                 let trait_ref = tcx.impl_trait_ref(def_id);
1099                 let parent = if let Some(trait_ref) = trait_ref {
1100                     let trait_def = tcx.trait_def(trait_ref.def_id);
1101                     trait_def.ancestors(tcx, def_id).skip(1).next().and_then(|node| {
1102                         match node {
1103                             specialization_graph::Node::Impl(parent) => Some(parent),
1104                             _ => None,
1105                         }
1106                     })
1107                 } else {
1108                     None
1109                 };
1110
1111                 // if this is an impl of `CoerceUnsized`, create its
1112                 // "unsized info", else just store None
1113                 let coerce_unsized_info =
1114                     trait_ref.and_then(|t| {
1115                         if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1116                             Some(tcx.at(item.span).coerce_unsized_info(def_id))
1117                         } else {
1118                             None
1119                         }
1120                     });
1121
1122                 let data = ImplData {
1123                     polarity,
1124                     defaultness,
1125                     parent_impl: parent,
1126                     coerce_unsized_info,
1127                     trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1128                 };
1129
1130                 EntryKind::Impl(self.lazy(&data))
1131             }
1132             hir::ItemTrait(..) => {
1133                 let trait_def = tcx.trait_def(def_id);
1134                 let data = TraitData {
1135                     unsafety: trait_def.unsafety,
1136                     paren_sugar: trait_def.paren_sugar,
1137                     has_auto_impl: tcx.trait_is_auto(def_id),
1138                     super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1139                 };
1140
1141                 EntryKind::Trait(self.lazy(&data))
1142             }
1143             hir::ItemExternCrate(_) |
1144             hir::ItemTraitAlias(..) |
1145             hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
1146         };
1147
1148         Entry {
1149             kind,
1150             visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
1151             span: self.lazy(&item.span),
1152             attributes: self.encode_attributes(&item.attrs),
1153             children: match item.node {
1154                 hir::ItemForeignMod(ref fm) => {
1155                     self.lazy_seq(fm.items
1156                         .iter()
1157                         .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
1158                 }
1159                 hir::ItemEnum(..) => {
1160                     let def = self.tcx.adt_def(def_id);
1161                     self.lazy_seq(def.variants.iter().map(|v| {
1162                         assert!(v.did.is_local());
1163                         v.did.index
1164                     }))
1165                 }
1166                 hir::ItemStruct(..) |
1167                 hir::ItemUnion(..) => {
1168                     let def = self.tcx.adt_def(def_id);
1169                     self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1170                         assert!(f.did.is_local());
1171                         f.did.index
1172                     }))
1173                 }
1174                 hir::ItemImpl(..) |
1175                 hir::ItemTrait(..) => {
1176                     self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1177                         assert!(def_id.is_local());
1178                         def_id.index
1179                     }))
1180                 }
1181                 _ => LazySeq::empty(),
1182             },
1183             stability: self.encode_stability(def_id),
1184             deprecation: self.encode_deprecation(def_id),
1185
1186             ty: match item.node {
1187                 hir::ItemStatic(..) |
1188                 hir::ItemConst(..) |
1189                 hir::ItemFn(..) |
1190                 hir::ItemTy(..) |
1191                 hir::ItemExistential(..) |
1192                 hir::ItemEnum(..) |
1193                 hir::ItemStruct(..) |
1194                 hir::ItemUnion(..) |
1195                 hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
1196                 _ => None,
1197             },
1198             inherent_impls: self.encode_inherent_implementations(def_id),
1199             variances: match item.node {
1200                 hir::ItemEnum(..) |
1201                 hir::ItemStruct(..) |
1202                 hir::ItemUnion(..) |
1203                 hir::ItemFn(..) => self.encode_variances_of(def_id),
1204                 _ => LazySeq::empty(),
1205             },
1206             generics: match item.node {
1207                 hir::ItemStatic(..) |
1208                 hir::ItemConst(..) |
1209                 hir::ItemFn(..) |
1210                 hir::ItemTy(..) |
1211                 hir::ItemEnum(..) |
1212                 hir::ItemStruct(..) |
1213                 hir::ItemUnion(..) |
1214                 hir::ItemImpl(..) |
1215                 hir::ItemExistential(..) |
1216                 hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
1217                 _ => None,
1218             },
1219             predicates: match item.node {
1220                 hir::ItemStatic(..) |
1221                 hir::ItemConst(..) |
1222                 hir::ItemFn(..) |
1223                 hir::ItemTy(..) |
1224                 hir::ItemEnum(..) |
1225                 hir::ItemStruct(..) |
1226                 hir::ItemUnion(..) |
1227                 hir::ItemImpl(..) |
1228                 hir::ItemExistential(..) |
1229                 hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
1230                 _ => None,
1231             },
1232
1233             mir: match item.node {
1234                 hir::ItemStatic(..) => {
1235                     self.encode_optimized_mir(def_id)
1236                 }
1237                 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
1238                 hir::ItemFn(_, header, ..) => {
1239                     let generics = tcx.generics_of(def_id);
1240                     let has_types = generics.params.iter().any(|param| match param.kind {
1241                         ty::GenericParamDefKind::Type { .. } => true,
1242                         _ => false,
1243                     });
1244                     let needs_inline =
1245                         (has_types || tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1246                             !self.metadata_output_only();
1247                     let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1248                     if needs_inline
1249                         || header.constness == hir::Constness::Const
1250                         || always_encode_mir
1251                     {
1252                         self.encode_optimized_mir(def_id)
1253                     } else {
1254                         None
1255                     }
1256                 }
1257                 _ => None,
1258             },
1259         }
1260     }
1261
1262     /// Serialize the text of exported macros
1263     fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1264         use syntax::print::pprust;
1265         let def_id = self.tcx.hir.local_def_id(macro_def.id);
1266         Entry {
1267             kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1268                 body: pprust::tts_to_string(&macro_def.body.trees().collect::<Vec<_>>()),
1269                 legacy: macro_def.legacy,
1270             })),
1271             visibility: self.lazy(&ty::Visibility::Public),
1272             span: self.lazy(&macro_def.span),
1273             attributes: self.encode_attributes(&macro_def.attrs),
1274             stability: self.encode_stability(def_id),
1275             deprecation: self.encode_deprecation(def_id),
1276
1277             children: LazySeq::empty(),
1278             ty: None,
1279             inherent_impls: LazySeq::empty(),
1280             variances: LazySeq::empty(),
1281             generics: None,
1282             predicates: None,
1283             mir: None,
1284         }
1285     }
1286
1287     fn encode_info_for_ty_param(&mut self,
1288                                 (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
1289                                 -> Entry<'tcx> {
1290         debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1291         let tcx = self.tcx;
1292         Entry {
1293             kind: EntryKind::Type,
1294             visibility: self.lazy(&ty::Visibility::Public),
1295             span: self.lazy(&tcx.def_span(def_id)),
1296             attributes: LazySeq::empty(),
1297             children: LazySeq::empty(),
1298             stability: None,
1299             deprecation: None,
1300
1301             ty: if has_default {
1302                 Some(self.encode_item_type(def_id))
1303             } else {
1304                 None
1305             },
1306             inherent_impls: LazySeq::empty(),
1307             variances: LazySeq::empty(),
1308             generics: None,
1309             predicates: None,
1310
1311             mir: None,
1312         }
1313     }
1314
1315     fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1316         debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1317         let tcx = self.tcx;
1318
1319         let tables = self.tcx.typeck_tables_of(def_id);
1320         let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1321         let hir_id = self.tcx.hir.node_to_hir_id(node_id);
1322         let kind = match tables.node_id_to_type(hir_id).sty {
1323             ty::TyGenerator(def_id, ..) => {
1324                 let layout = self.tcx.generator_layout(def_id);
1325                 let data = GeneratorData {
1326                     layout: layout.clone(),
1327                 };
1328                 EntryKind::Generator(self.lazy(&data))
1329             }
1330
1331             ty::TyClosure(def_id, substs) => {
1332                 let sig = substs.closure_sig(def_id, self.tcx);
1333                 let data = ClosureData { sig: self.lazy(&sig) };
1334                 EntryKind::Closure(self.lazy(&data))
1335             }
1336
1337             _ => bug!("closure that is neither generator nor closure")
1338         };
1339
1340         Entry {
1341             kind,
1342             visibility: self.lazy(&ty::Visibility::Public),
1343             span: self.lazy(&tcx.def_span(def_id)),
1344             attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1345             children: LazySeq::empty(),
1346             stability: None,
1347             deprecation: None,
1348
1349             ty: Some(self.encode_item_type(def_id)),
1350             inherent_impls: LazySeq::empty(),
1351             variances: LazySeq::empty(),
1352             generics: Some(self.encode_generics(def_id)),
1353             predicates: None,
1354
1355             mir: self.encode_optimized_mir(def_id),
1356         }
1357     }
1358
1359     fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1360         debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id);
1361         let tcx = self.tcx;
1362         let id = tcx.hir.as_local_node_id(def_id).unwrap();
1363         let body_id = tcx.hir.body_owned_by(id);
1364         let const_data = self.encode_rendered_const_for_body(body_id);
1365         let mir = tcx.mir_const_qualif(def_id).0;
1366
1367         Entry {
1368             kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1369             visibility: self.lazy(&ty::Visibility::Public),
1370             span: self.lazy(&tcx.def_span(def_id)),
1371             attributes: LazySeq::empty(),
1372             children: LazySeq::empty(),
1373             stability: None,
1374             deprecation: None,
1375
1376             ty: Some(self.encode_item_type(def_id)),
1377             inherent_impls: LazySeq::empty(),
1378             variances: LazySeq::empty(),
1379             generics: Some(self.encode_generics(def_id)),
1380             predicates: Some(self.encode_predicates(def_id)),
1381
1382             mir: self.encode_optimized_mir(def_id),
1383         }
1384     }
1385
1386     fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1387         // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1388         //       we rely on the HashStable specialization for [Attribute]
1389         //       to properly filter things out.
1390         self.lazy_seq_from_slice(attrs)
1391     }
1392
1393     fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1394         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1395         self.lazy_seq(used_libraries.iter().cloned())
1396     }
1397
1398     fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> {
1399         let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1400         self.lazy_seq(foreign_modules.iter().cloned())
1401     }
1402
1403     fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1404         let crates = self.tcx.crates();
1405
1406         let mut deps = crates
1407             .iter()
1408             .map(|&cnum| {
1409                 let dep = CrateDep {
1410                     name: self.tcx.original_crate_name(cnum),
1411                     hash: self.tcx.crate_hash(cnum),
1412                     kind: self.tcx.dep_kind(cnum),
1413                     extra_filename: self.tcx.extra_filename(cnum),
1414                 };
1415                 (cnum, dep)
1416             })
1417             .collect::<Vec<_>>();
1418
1419         deps.sort_by_key(|&(cnum, _)| cnum);
1420
1421         {
1422             // Sanity-check the crate numbers
1423             let mut expected_cnum = 1;
1424             for &(n, _) in &deps {
1425                 assert_eq!(n, CrateNum::new(expected_cnum));
1426                 expected_cnum += 1;
1427             }
1428         }
1429
1430         // We're just going to write a list of crate 'name-hash-version's, with
1431         // the assumption that they are numbered 1 to n.
1432         // FIXME (#2166): This is not nearly enough to support correct versioning
1433         // but is enough to get transitive crate dependencies working.
1434         self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1435     }
1436
1437     fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1438         let tcx = self.tcx;
1439         let lang_items = tcx.lang_items();
1440         let lang_items = lang_items.items().iter();
1441         self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1442             if let Some(def_id) = opt_def_id {
1443                 if def_id.is_local() {
1444                     return Some((def_id.index, i));
1445                 }
1446             }
1447             None
1448         }))
1449     }
1450
1451     fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1452         let tcx = self.tcx;
1453         self.lazy_seq_ref(&tcx.lang_items().missing)
1454     }
1455
1456     /// Encodes an index, mapping each trait to its (local) implementations.
1457     fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1458         debug!("IsolatedEncoder::encode_impls()");
1459         let tcx = self.tcx;
1460         let mut visitor = ImplVisitor {
1461             tcx,
1462             impls: FxHashMap(),
1463         };
1464         tcx.hir.krate().visit_all_item_likes(&mut visitor);
1465
1466         let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1467
1468         // Bring everything into deterministic order for hashing
1469         all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1470             tcx.def_path_hash(trait_def_id)
1471         });
1472
1473         let all_impls: Vec<_> = all_impls
1474             .into_iter()
1475             .map(|(trait_def_id, mut impls)| {
1476                 // Bring everything into deterministic order for hashing
1477                 impls.sort_by_cached_key(|&def_index| {
1478                     tcx.hir.definitions().def_path_hash(def_index)
1479                 });
1480
1481                 TraitImpls {
1482                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1483                     impls: self.lazy_seq_from_slice(&impls[..]),
1484                 }
1485             })
1486             .collect();
1487
1488         self.lazy_seq_from_slice(&all_impls[..])
1489     }
1490
1491     // Encodes all symbols exported from this crate into the metadata.
1492     //
1493     // This pass is seeded off the reachability list calculated in the
1494     // middle::reachable module but filters out items that either don't have a
1495     // symbol associated with them (they weren't translated) or if they're an FFI
1496     // definition (as that's not defined in this crate).
1497     fn encode_exported_symbols(&mut self,
1498                                exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
1499                                -> EncodedExportedSymbols {
1500         // The metadata symbol name is special. It should not show up in
1501         // downstream crates.
1502         let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1503
1504         let lazy_seq = self.lazy_seq(exported_symbols
1505             .iter()
1506             .filter(|&&(ref exported_symbol, _)| {
1507                 match *exported_symbol {
1508                     ExportedSymbol::NoDefId(symbol_name) => {
1509                         symbol_name != metadata_symbol_name
1510                     },
1511                     _ => true,
1512                 }
1513             })
1514             .cloned());
1515
1516         EncodedExportedSymbols {
1517             len: lazy_seq.len,
1518             position: lazy_seq.position,
1519         }
1520     }
1521
1522     fn encode_wasm_custom_sections(&mut self, statics: &[DefId]) -> LazySeq<DefIndex> {
1523         info!("encoding custom wasm section constants {:?}", statics);
1524         self.lazy_seq(statics.iter().map(|id| id.index))
1525     }
1526
1527     fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1528         match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
1529             Some(arr) => {
1530                 self.lazy_seq(arr.iter().map(|slot| {
1531                     match *slot {
1532                         Linkage::NotLinked |
1533                         Linkage::IncludedFromDylib => None,
1534
1535                         Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1536                         Linkage::Static => Some(LinkagePreference::RequireStatic),
1537                     }
1538                 }))
1539             }
1540             None => LazySeq::empty(),
1541         }
1542     }
1543
1544     fn encode_info_for_foreign_item(&mut self,
1545                                     (def_id, nitem): (DefId, &hir::ForeignItem))
1546                                     -> Entry<'tcx> {
1547         let tcx = self.tcx;
1548
1549         debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1550
1551         let kind = match nitem.node {
1552             hir::ForeignItemFn(_, ref names, _) => {
1553                 let data = FnData {
1554                     constness: hir::Constness::NotConst,
1555                     arg_names: self.encode_fn_arg_names(names),
1556                     sig: self.lazy(&tcx.fn_sig(def_id)),
1557                 };
1558                 EntryKind::ForeignFn(self.lazy(&data))
1559             }
1560             hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
1561             hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
1562             hir::ForeignItemType => EntryKind::ForeignType,
1563         };
1564
1565         Entry {
1566             kind,
1567             visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
1568             span: self.lazy(&nitem.span),
1569             attributes: self.encode_attributes(&nitem.attrs),
1570             children: LazySeq::empty(),
1571             stability: self.encode_stability(def_id),
1572             deprecation: self.encode_deprecation(def_id),
1573
1574             ty: Some(self.encode_item_type(def_id)),
1575             inherent_impls: LazySeq::empty(),
1576             variances: match nitem.node {
1577                 hir::ForeignItemFn(..) => self.encode_variances_of(def_id),
1578                 _ => LazySeq::empty(),
1579             },
1580             generics: Some(self.encode_generics(def_id)),
1581             predicates: Some(self.encode_predicates(def_id)),
1582
1583             mir: None,
1584         }
1585     }
1586 }
1587
1588 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1589     index: IndexBuilder<'a, 'b, 'tcx>,
1590 }
1591
1592 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1593     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1594         NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
1595     }
1596     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1597         intravisit::walk_expr(self, ex);
1598         self.index.encode_info_for_expr(ex);
1599     }
1600     fn visit_item(&mut self, item: &'tcx hir::Item) {
1601         intravisit::walk_item(self, item);
1602         let def_id = self.index.tcx.hir.local_def_id(item.id);
1603         match item.node {
1604             hir::ItemExternCrate(_) |
1605             hir::ItemUse(..) => (), // ignore these
1606             _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1607         }
1608         self.index.encode_addl_info_for_item(item);
1609     }
1610     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1611         intravisit::walk_foreign_item(self, ni);
1612         let def_id = self.index.tcx.hir.local_def_id(ni.id);
1613         self.index.record(def_id,
1614                           IsolatedEncoder::encode_info_for_foreign_item,
1615                           (def_id, ni));
1616     }
1617     fn visit_variant(&mut self,
1618                      v: &'tcx hir::Variant,
1619                      g: &'tcx hir::Generics,
1620                      id: ast::NodeId) {
1621         intravisit::walk_variant(self, v, g, id);
1622
1623         if let Some(ref discr) = v.node.disr_expr {
1624             let def_id = self.index.tcx.hir.local_def_id(discr.id);
1625             self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1626         }
1627     }
1628     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1629         intravisit::walk_generics(self, generics);
1630         self.index.encode_info_for_generics(generics);
1631     }
1632     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1633         intravisit::walk_ty(self, ty);
1634         self.index.encode_info_for_ty(ty);
1635     }
1636     fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1637         let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
1638         self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1639     }
1640 }
1641
1642 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1643     fn encode_fields(&mut self, adt_def_id: DefId) {
1644         let def = self.tcx.adt_def(adt_def_id);
1645         for (variant_index, variant) in def.variants.iter().enumerate() {
1646             for (field_index, field) in variant.fields.iter().enumerate() {
1647                 self.record(field.did,
1648                             IsolatedEncoder::encode_field,
1649                             (adt_def_id, Untracked((variant_index, field_index))));
1650             }
1651         }
1652     }
1653
1654     fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1655         generics.params.iter().for_each(|param| match param.kind {
1656             hir::GenericParamKind::Lifetime { .. } => {}
1657             hir::GenericParamKind::Type { ref default, .. } => {
1658                 let def_id = self.tcx.hir.local_def_id(param.id);
1659                 let has_default = Untracked(default.is_some());
1660                 let encode_info = IsolatedEncoder::encode_info_for_ty_param;
1661                 self.record(def_id, encode_info, (def_id, has_default));
1662             }
1663         });
1664     }
1665
1666     fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1667         match ty.node {
1668             hir::TyArray(_, ref length) => {
1669                 let def_id = self.tcx.hir.local_def_id(length.id);
1670                 self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1671             }
1672             _ => {}
1673         }
1674     }
1675
1676     fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1677         match expr.node {
1678             hir::ExprClosure(..) => {
1679                 let def_id = self.tcx.hir.local_def_id(expr.id);
1680                 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1681             }
1682             _ => {}
1683         }
1684     }
1685
1686     /// In some cases, along with the item itself, we also
1687     /// encode some sub-items. Usually we want some info from the item
1688     /// so it's easier to do that here then to wait until we would encounter
1689     /// normally in the visitor walk.
1690     fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1691         let def_id = self.tcx.hir.local_def_id(item.id);
1692         match item.node {
1693             hir::ItemStatic(..) |
1694             hir::ItemConst(..) |
1695             hir::ItemFn(..) |
1696             hir::ItemMod(..) |
1697             hir::ItemForeignMod(..) |
1698             hir::ItemGlobalAsm(..) |
1699             hir::ItemExternCrate(..) |
1700             hir::ItemUse(..) |
1701             hir::ItemTy(..) |
1702             hir::ItemExistential(..) |
1703             hir::ItemTraitAlias(..) => {
1704                 // no sub-item recording needed in these cases
1705             }
1706             hir::ItemEnum(..) => {
1707                 self.encode_fields(def_id);
1708
1709                 let def = self.tcx.adt_def(def_id);
1710                 for (i, variant) in def.variants.iter().enumerate() {
1711                     self.record(variant.did,
1712                                 IsolatedEncoder::encode_enum_variant_info,
1713                                 (def_id, Untracked(i)));
1714                 }
1715             }
1716             hir::ItemStruct(ref struct_def, _) => {
1717                 self.encode_fields(def_id);
1718
1719                 // If the struct has a constructor, encode it.
1720                 if !struct_def.is_struct() {
1721                     let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
1722                     self.record(ctor_def_id,
1723                                 IsolatedEncoder::encode_struct_ctor,
1724                                 (def_id, ctor_def_id));
1725                 }
1726             }
1727             hir::ItemUnion(..) => {
1728                 self.encode_fields(def_id);
1729             }
1730             hir::ItemImpl(..) => {
1731                 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1732                     self.record(trait_item_def_id,
1733                                 IsolatedEncoder::encode_info_for_impl_item,
1734                                 trait_item_def_id);
1735                 }
1736             }
1737             hir::ItemTrait(..) => {
1738                 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1739                     self.record(item_def_id,
1740                                 IsolatedEncoder::encode_info_for_trait_item,
1741                                 item_def_id);
1742                 }
1743             }
1744         }
1745     }
1746 }
1747
1748 struct ImplVisitor<'a, 'tcx: 'a> {
1749     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1750     impls: FxHashMap<DefId, Vec<DefIndex>>,
1751 }
1752
1753 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1754     fn visit_item(&mut self, item: &hir::Item) {
1755         if let hir::ItemImpl(..) = item.node {
1756             let impl_id = self.tcx.hir.local_def_id(item.id);
1757             if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1758                 self.impls
1759                     .entry(trait_ref.def_id)
1760                     .or_insert(vec![])
1761                     .push(impl_id.index);
1762             }
1763         }
1764     }
1765
1766     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1767
1768     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1769         // handled in `visit_item` above
1770     }
1771 }
1772
1773 // NOTE(eddyb) The following comment was preserved for posterity, even
1774 // though it's no longer relevant as EBML (which uses nested & tagged
1775 // "documents") was replaced with a scheme that can't go out of bounds.
1776 //
1777 // And here we run into yet another obscure archive bug: in which metadata
1778 // loaded from archives may have trailing garbage bytes. Awhile back one of
1779 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1780 // and opt) by having ebml generate an out-of-bounds panic when looking at
1781 // metadata.
1782 //
1783 // Upon investigation it turned out that the metadata file inside of an rlib
1784 // (and ar archive) was being corrupted. Some compilations would generate a
1785 // metadata file which would end in a few extra bytes, while other
1786 // compilations would not have these extra bytes appended to the end. These
1787 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1788 // being interpreted causing the out-of-bounds.
1789 //
1790 // The root cause of why these extra bytes were appearing was never
1791 // discovered, and in the meantime the solution we're employing is to insert
1792 // the length of the metadata to the start of the metadata. Later on this
1793 // will allow us to slice the metadata to the precise length that we just
1794 // generated regardless of trailing bytes that end up in it.
1795
1796 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1797                                  link_meta: &LinkMeta)
1798                                  -> EncodedMetadata
1799 {
1800     let mut cursor = Cursor::new(vec![]);
1801     cursor.write_all(METADATA_HEADER).unwrap();
1802
1803     // Will be filled with the root position after encoding everything.
1804     cursor.write_all(&[0, 0, 0, 0]).unwrap();
1805
1806     let root = {
1807         let mut ecx = EncodeContext {
1808             opaque: opaque::Encoder::new(&mut cursor),
1809             tcx,
1810             link_meta,
1811             lazy_state: LazyState::NoNode,
1812             type_shorthands: Default::default(),
1813             predicate_shorthands: Default::default(),
1814             filemap_cache: tcx.sess.codemap().files()[0].clone(),
1815             interpret_allocs: Default::default(),
1816             interpret_allocs_inverse: Default::default(),
1817         };
1818
1819         // Encode the rustc version string in a predictable location.
1820         rustc_version().encode(&mut ecx).unwrap();
1821
1822         // Encode all the entries and extra information in the crate,
1823         // culminating in the `CrateRoot` which points to all of it.
1824         ecx.encode_crate_root()
1825     };
1826     let mut result = cursor.into_inner();
1827
1828     // Encode the root position.
1829     let header = METADATA_HEADER.len();
1830     let pos = root.position;
1831     result[header + 0] = (pos >> 24) as u8;
1832     result[header + 1] = (pos >> 16) as u8;
1833     result[header + 2] = (pos >> 8) as u8;
1834     result[header + 3] = (pos >> 0) as u8;
1835
1836     EncodedMetadata { raw_data: result }
1837 }
1838
1839 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1840     let ty = tcx.type_of(did);
1841     match ty.sty {
1842         ty::TyAdt(ref def, _) => return def.repr,
1843         _ => bug!("{} is not an ADT", ty),
1844     }
1845 }