1 use dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
2 use errors::Diagnostic;
4 use hir::def_id::{CrateNum, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
5 use hir::map::definitions::DefPathHash;
6 use ich::{CachingSourceMapView, Fingerprint};
7 use mir::{self, interpret};
8 use mir::interpret::{AllocDecodingSession, AllocDecodingState};
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::thin_vec::ThinVec;
11 use rustc_data_structures::sync::{Lrc, Lock, HashMapExt, Once};
12 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
13 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque,
14 SpecializedDecoder, SpecializedEncoder,
15 UseSpecializedDecodable, UseSpecializedEncodable};
16 use session::{CrateDisambiguator, Session};
18 use syntax::ast::NodeId;
19 use syntax::source_map::{SourceMap, StableSourceFileId};
20 use syntax_pos::{BytePos, Span, DUMMY_SP, SourceFile};
21 use syntax_pos::hygiene::{Mark, SyntaxContext, ExpnInfo};
23 use ty::codec::{self as ty_codec, TyDecoder, TyEncoder};
24 use ty::context::TyCtxt;
25 use util::common::time;
27 const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
29 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
30 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
32 const TAG_NO_EXPANSION_INFO: u8 = 0;
33 const TAG_EXPANSION_INFO_SHORTHAND: u8 = 1;
34 const TAG_EXPANSION_INFO_INLINE: u8 = 2;
36 const TAG_VALID_SPAN: u8 = 0;
37 const TAG_INVALID_SPAN: u8 = 1;
39 /// `OnDiskCache` provides an interface to incr. comp. data cached from the
40 /// previous compilation session. This data will eventually include the results
41 /// of a few selected queries (like `typeck_tables_of` and `mir_optimized`) and
42 /// any diagnostics that have been emitted during a query.
43 pub struct OnDiskCache<'sess> {
45 // The complete cache data in serialized form.
46 serialized_data: Vec<u8>,
48 // This field collects all Diagnostics emitted during the current
49 // compilation session.
50 current_diagnostics: Lock<FxHashMap<DepNodeIndex, Vec<Diagnostic>>>,
52 prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
53 cnum_map: Once<IndexVec<CrateNum, Option<CrateNum>>>,
55 source_map: &'sess SourceMap,
56 file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
58 // These two fields caches that are populated lazily during decoding.
59 file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
60 synthetic_expansion_infos: Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
62 // A map from dep-node to the position of the cached query result in
64 query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
66 // A map from dep-node to the position of any associated diagnostics in
68 prev_diagnostics_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
70 alloc_decoding_state: AllocDecodingState,
73 // This type is used only for (de-)serialization.
74 #[derive(RustcEncodable, RustcDecodable)]
76 file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
77 prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
78 query_result_index: EncodedQueryResultIndex,
79 diagnostics_index: EncodedQueryResultIndex,
80 // the location of all allocations
81 interpret_alloc_index: Vec<u32>,
84 type EncodedQueryResultIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
85 type EncodedDiagnosticsIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
86 type EncodedDiagnostics = Vec<Diagnostic>;
88 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
89 struct SourceFileIndex(u32);
91 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, RustcEncodable, RustcDecodable)]
92 struct AbsoluteBytePos(u32);
94 impl AbsoluteBytePos {
95 fn new(pos: usize) -> AbsoluteBytePos {
96 debug_assert!(pos <= ::std::u32::MAX as usize);
97 AbsoluteBytePos(pos as u32)
100 fn to_usize(self) -> usize {
105 impl<'sess> OnDiskCache<'sess> {
106 /// Create a new OnDiskCache instance from the serialized data in `data`.
107 pub fn new(sess: &'sess Session, data: Vec<u8>, start_pos: usize) -> OnDiskCache<'sess> {
108 debug_assert!(sess.opts.incremental.is_some());
110 // Wrapping in a scope so we can borrow `data`
111 let footer: Footer = {
112 let mut decoder = opaque::Decoder::new(&data[..], start_pos);
114 // Decode the *position* of the footer which can be found in the
115 // last 8 bytes of the file.
116 decoder.set_position(data.len() - IntEncodedWithFixedSize::ENCODED_SIZE);
117 let query_result_index_pos = IntEncodedWithFixedSize::decode(&mut decoder)
118 .expect("Error while trying to decode query result index position.")
121 // Decoder the file footer which contains all the lookup tables, etc.
122 decoder.set_position(query_result_index_pos);
123 decode_tagged(&mut decoder, TAG_FILE_FOOTER)
124 .expect("Error while trying to decode query result index position.")
128 serialized_data: data,
129 file_index_to_stable_id: footer.file_index_to_stable_id,
130 file_index_to_file: Default::default(),
131 prev_cnums: footer.prev_cnums,
132 cnum_map: Once::new(),
133 source_map: sess.source_map(),
134 current_diagnostics: Default::default(),
135 query_result_index: footer.query_result_index.into_iter().collect(),
136 prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
137 synthetic_expansion_infos: Default::default(),
138 alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
142 pub fn new_empty(source_map: &'sess SourceMap) -> OnDiskCache<'sess> {
144 serialized_data: Vec::new(),
145 file_index_to_stable_id: Default::default(),
146 file_index_to_file: Default::default(),
148 cnum_map: Once::new(),
150 current_diagnostics: Default::default(),
151 query_result_index: Default::default(),
152 prev_diagnostics_index: Default::default(),
153 synthetic_expansion_infos: Default::default(),
154 alloc_decoding_state: AllocDecodingState::new(Vec::new()),
158 pub fn serialize<'a, 'tcx, E>(&self,
159 tcx: TyCtxt<'a, 'tcx, 'tcx>,
161 -> Result<(), E::Error>
162 where E: ty_codec::TyEncoder
164 // Serializing the DepGraph should not modify it:
165 tcx.dep_graph.with_ignore(|| {
166 // Allocate SourceFileIndices
167 let (file_to_file_index, file_index_to_stable_id) = {
168 let files = tcx.sess.source_map().files();
169 let mut file_to_file_index = FxHashMap::with_capacity_and_hasher(
170 files.len(), Default::default());
171 let mut file_index_to_stable_id = FxHashMap::with_capacity_and_hasher(
172 files.len(), Default::default());
174 for (index, file) in files.iter().enumerate() {
175 let index = SourceFileIndex(index as u32);
176 let file_ptr: *const SourceFile = &**file as *const _;
177 file_to_file_index.insert(file_ptr, index);
178 file_index_to_stable_id.insert(index, StableSourceFileId::new(&file));
181 (file_to_file_index, file_index_to_stable_id)
184 let mut encoder = CacheEncoder {
187 type_shorthands: Default::default(),
188 predicate_shorthands: Default::default(),
189 expn_info_shorthands: Default::default(),
190 interpret_allocs: Default::default(),
191 interpret_allocs_inverse: Vec::new(),
192 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
196 // Load everything into memory so we can write it out to the on-disk
197 // cache. The vast majority of cacheable query results should already
198 // be in memory, so this should be a cheap operation.
199 tcx.dep_graph.exec_cache_promotions(tcx);
201 // Encode query results
202 let mut query_result_index = EncodedQueryResultIndex::new();
204 time(tcx.sess, "encode query results", || {
205 use ty::query::queries::*;
206 let enc = &mut encoder;
207 let qri = &mut query_result_index;
209 encode_query_results::<type_of<'_>, _>(tcx, enc, qri)?;
210 encode_query_results::<generics_of<'_>, _>(tcx, enc, qri)?;
211 encode_query_results::<predicates_of<'_>, _>(tcx, enc, qri)?;
212 encode_query_results::<used_trait_imports<'_>, _>(tcx, enc, qri)?;
213 encode_query_results::<typeck_tables_of<'_>, _>(tcx, enc, qri)?;
214 encode_query_results::<codegen_fulfill_obligation<'_>, _>(tcx, enc, qri)?;
215 encode_query_results::<optimized_mir<'_>, _>(tcx, enc, qri)?;
216 encode_query_results::<unsafety_check_result<'_>, _>(tcx, enc, qri)?;
217 encode_query_results::<borrowck<'_>, _>(tcx, enc, qri)?;
218 encode_query_results::<mir_borrowck<'_>, _>(tcx, enc, qri)?;
219 encode_query_results::<mir_const_qualif<'_>, _>(tcx, enc, qri)?;
220 encode_query_results::<def_symbol_name<'_>, _>(tcx, enc, qri)?;
221 encode_query_results::<const_is_rvalue_promotable_to_static<'_>, _>(tcx, enc, qri)?;
222 encode_query_results::<symbol_name<'_>, _>(tcx, enc, qri)?;
223 encode_query_results::<check_match<'_>, _>(tcx, enc, qri)?;
224 encode_query_results::<codegen_fn_attrs<'_>, _>(tcx, enc, qri)?;
225 encode_query_results::<specialization_graph_of<'_>, _>(tcx, enc, qri)?;
227 // const eval is special, it only encodes successfully evaluated constants
228 use ty::query::QueryAccessors;
229 let cache = const_eval::query_cache(tcx).borrow();
230 assert!(cache.active.is_empty());
231 for (key, entry) in cache.results.iter() {
232 use ty::query::config::QueryDescription;
233 if const_eval::cache_on_disk(key.clone()) {
234 if let Ok(ref value) = entry.value {
235 let dep_node = SerializedDepNodeIndex::new(entry.index.index());
237 // Record position of the cache entry
238 qri.push((dep_node, AbsoluteBytePos::new(enc.position())));
240 // Encode the type check tables with the SerializedDepNodeIndex
242 enc.encode_tagged(dep_node, value)?;
250 // Encode diagnostics
251 let diagnostics_index: EncodedDiagnosticsIndex = self.current_diagnostics.borrow()
253 .map(|(dep_node_index, diagnostics)|
255 let pos = AbsoluteBytePos::new(encoder.position());
256 // Let's make sure we get the expected type here:
257 let diagnostics: &EncodedDiagnostics = diagnostics;
258 let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
259 encoder.encode_tagged(dep_node_index, diagnostics)?;
261 Ok((dep_node_index, pos))
263 .collect::<Result<_, _>>()?;
265 let interpret_alloc_index = {
266 let mut interpret_alloc_index = Vec::new();
269 let new_n = encoder.interpret_allocs_inverse.len();
270 // if we have found new ids, serialize those, too
275 interpret_alloc_index.reserve(new_n - n);
276 for idx in n..new_n {
277 let id = encoder.interpret_allocs_inverse[idx];
278 let pos = encoder.position() as u32;
279 interpret_alloc_index.push(pos);
280 interpret::specialized_encode_alloc_id(
288 interpret_alloc_index
291 let sorted_cnums = sorted_cnums_including_local_crate(tcx);
292 let prev_cnums: Vec<_> = sorted_cnums.iter().map(|&cnum| {
293 let crate_name = tcx.original_crate_name(cnum).as_str().to_string();
294 let crate_disambiguator = tcx.crate_disambiguator(cnum);
295 (cnum.as_u32(), crate_name, crate_disambiguator)
298 // Encode the file footer
299 let footer_pos = encoder.position() as u64;
300 encoder.encode_tagged(TAG_FILE_FOOTER, &Footer {
301 file_index_to_stable_id,
305 interpret_alloc_index,
308 // Encode the position of the footer as the last 8 bytes of the
309 // file so we know where to look for it.
310 IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder)?;
312 // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
313 // of the footer must be the last thing in the data stream.
317 fn sorted_cnums_including_local_crate(tcx: TyCtxt<'_, '_, '_>) -> Vec<CrateNum> {
318 let mut cnums = vec![LOCAL_CRATE];
319 cnums.extend_from_slice(&tcx.crates()[..]);
320 cnums.sort_unstable();
321 // Just to be sure...
328 /// Load a diagnostic emitted during the previous compilation session.
329 pub fn load_diagnostics<'a, 'tcx>(&self,
330 tcx: TyCtxt<'a, 'tcx, 'tcx>,
331 dep_node_index: SerializedDepNodeIndex)
333 let diagnostics: Option<EncodedDiagnostics> = self.load_indexed(
336 &self.prev_diagnostics_index,
339 diagnostics.unwrap_or_default()
342 /// Store a diagnostic emitted during the current compilation session.
343 /// Anything stored like this will be available via `load_diagnostics` in
344 /// the next compilation session.
347 pub fn store_diagnostics(&self,
348 dep_node_index: DepNodeIndex,
349 diagnostics: ThinVec<Diagnostic>) {
350 let mut current_diagnostics = self.current_diagnostics.borrow_mut();
351 let prev = current_diagnostics.insert(dep_node_index, diagnostics.into());
352 debug_assert!(prev.is_none());
355 /// Returns the cached query result if there is something in the cache for
356 /// the given SerializedDepNodeIndex. Otherwise returns None.
357 pub fn try_load_query_result<'tcx, T>(&self,
358 tcx: TyCtxt<'_, 'tcx, 'tcx>,
359 dep_node_index: SerializedDepNodeIndex)
363 self.load_indexed(tcx,
365 &self.query_result_index,
369 /// Store a diagnostic emitted during computation of an anonymous query.
370 /// Since many anonymous queries can share the same `DepNode`, we aggregate
371 /// them -- as opposed to regular queries where we assume that there is a
372 /// 1:1 relationship between query-key and `DepNode`.
375 pub fn store_diagnostics_for_anon_node(&self,
376 dep_node_index: DepNodeIndex,
377 diagnostics: ThinVec<Diagnostic>) {
378 let mut current_diagnostics = self.current_diagnostics.borrow_mut();
380 let x = current_diagnostics.entry(dep_node_index).or_insert(Vec::new());
382 x.extend(Into::<Vec<_>>::into(diagnostics));
385 fn load_indexed<'tcx, T>(&self,
386 tcx: TyCtxt<'_, 'tcx, 'tcx>,
387 dep_node_index: SerializedDepNodeIndex,
388 index: &FxHashMap<SerializedDepNodeIndex,
390 debug_tag: &'static str)
394 let pos = index.get(&dep_node_index).cloned()?;
396 // Initialize the cnum_map using the value from the thread which finishes the closure first
397 self.cnum_map.init_nonlocking_same(|| {
398 Self::compute_cnum_map(tcx, &self.prev_cnums[..])
401 let mut decoder = CacheDecoder {
403 opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()),
404 source_map: self.source_map,
405 cnum_map: self.cnum_map.get(),
406 file_index_to_file: &self.file_index_to_file,
407 file_index_to_stable_id: &self.file_index_to_stable_id,
408 synthetic_expansion_infos: &self.synthetic_expansion_infos,
409 alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
412 match decode_tagged(&mut decoder, dep_node_index) {
417 bug!("Could not decode cached {}: {}", debug_tag, e)
422 // This function builds mapping from previous-session-CrateNum to
423 // current-session-CrateNum. There might be CrateNums from the previous
424 // Session that don't occur in the current one. For these, the mapping
426 fn compute_cnum_map(tcx: TyCtxt<'_, '_, '_>,
427 prev_cnums: &[(u32, String, CrateDisambiguator)])
428 -> IndexVec<CrateNum, Option<CrateNum>>
430 tcx.dep_graph.with_ignore(|| {
431 let current_cnums = tcx.all_crate_nums(LOCAL_CRATE).iter().map(|&cnum| {
432 let crate_name = tcx.original_crate_name(cnum)
434 let crate_disambiguator = tcx.crate_disambiguator(cnum);
435 ((crate_name, crate_disambiguator), cnum)
436 }).collect::<FxHashMap<_,_>>();
438 let map_size = prev_cnums.iter()
439 .map(|&(cnum, ..)| cnum)
442 let mut map = IndexVec::from_elem_n(None, map_size as usize);
444 for &(prev_cnum, ref crate_name, crate_disambiguator) in prev_cnums {
445 let key = (crate_name.clone(), crate_disambiguator);
446 map[CrateNum::from_u32(prev_cnum)] = current_cnums.get(&key).cloned();
449 map[LOCAL_CRATE] = Some(LOCAL_CRATE);
455 //- DECODING -------------------------------------------------------------------
457 /// A decoder that can read the incr. comp. cache. It is similar to the one
458 /// we use for crate metadata decoding in that it can rebase spans and
459 /// eventually will also handle things that contain `Ty` instances.
460 struct CacheDecoder<'a, 'tcx: 'a, 'x> {
461 tcx: TyCtxt<'a, 'tcx, 'tcx>,
462 opaque: opaque::Decoder<'x>,
463 source_map: &'x SourceMap,
464 cnum_map: &'x IndexVec<CrateNum, Option<CrateNum>>,
465 synthetic_expansion_infos: &'x Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
466 file_index_to_file: &'x Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
467 file_index_to_stable_id: &'x FxHashMap<SourceFileIndex, StableSourceFileId>,
468 alloc_decoding_session: AllocDecodingSession<'x>,
471 impl<'a, 'tcx, 'x> CacheDecoder<'a, 'tcx, 'x> {
472 fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
474 ref file_index_to_file,
475 ref file_index_to_stable_id,
480 file_index_to_file.borrow_mut().entry(index).or_insert_with(|| {
481 let stable_id = file_index_to_stable_id[&index];
482 source_map.source_file_by_stable_id(stable_id)
483 .expect("Failed to lookup SourceFile in new context.")
488 trait DecoderWithPosition: Decoder {
489 fn position(&self) -> usize;
492 impl<'enc> DecoderWithPosition for opaque::Decoder<'enc> {
493 fn position(&self) -> usize {
498 impl<'a, 'tcx, 'x> DecoderWithPosition for CacheDecoder<'a, 'tcx, 'x> {
499 fn position(&self) -> usize {
500 self.opaque.position()
504 // Decode something that was encoded with encode_tagged() and verify that the
505 // tag matches and the correct amount of bytes was read.
506 fn decode_tagged<'a, 'tcx, D, T, V>(decoder: &mut D,
508 -> Result<V, D::Error>
509 where T: Decodable + Eq + ::std::fmt::Debug,
511 D: DecoderWithPosition,
514 let start_pos = decoder.position();
516 let actual_tag = T::decode(decoder)?;
517 assert_eq!(actual_tag, expected_tag);
518 let value = V::decode(decoder)?;
519 let end_pos = decoder.position();
521 let expected_len: u64 = Decodable::decode(decoder)?;
522 assert_eq!((end_pos - start_pos) as u64, expected_len);
528 impl<'a, 'tcx: 'a, 'x> ty_codec::TyDecoder<'a, 'tcx> for CacheDecoder<'a, 'tcx, 'x> {
531 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
536 fn position(&self) -> usize {
537 self.opaque.position()
541 fn peek_byte(&self) -> u8 {
542 self.opaque.data[self.opaque.position()]
545 fn cached_ty_for_shorthand<F>(&mut self,
548 -> Result<ty::Ty<'tcx>, Self::Error>
549 where F: FnOnce(&mut Self) -> Result<ty::Ty<'tcx>, Self::Error>
551 let tcx = self.tcx();
553 let cache_key = ty::CReaderCacheKey {
554 cnum: CrateNum::ReservedForIncrCompCache,
558 if let Some(&ty) = tcx.rcache.borrow().get(&cache_key) {
562 let ty = or_insert_with(self)?;
563 // This may overwrite the entry, but it should overwrite with the same value
564 tcx.rcache.borrow_mut().insert_same(cache_key, ty);
568 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
569 where F: FnOnce(&mut Self) -> R
571 debug_assert!(pos < self.opaque.data.len());
573 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
574 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
576 self.opaque = old_opaque;
580 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
581 self.cnum_map[cnum].unwrap_or_else(|| {
582 bug!("Could not find new CrateNum for {:?}", cnum)
587 implement_ty_decoder!( CacheDecoder<'a, 'tcx, 'x> );
589 impl<'a, 'tcx, 'x> SpecializedDecoder<interpret::AllocId> for CacheDecoder<'a, 'tcx, 'x> {
590 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
591 let alloc_decoding_session = self.alloc_decoding_session;
592 alloc_decoding_session.decode_alloc_id(self)
596 impl<'a, 'tcx, 'x> SpecializedDecoder<Span> for CacheDecoder<'a, 'tcx, 'x> {
597 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
598 let tag: u8 = Decodable::decode(self)?;
600 if tag == TAG_INVALID_SPAN {
603 debug_assert_eq!(tag, TAG_VALID_SPAN);
606 let file_lo_index = SourceFileIndex::decode(self)?;
607 let line_lo = usize::decode(self)?;
608 let col_lo = BytePos::decode(self)?;
609 let len = BytePos::decode(self)?;
611 let file_lo = self.file_index_to_file(file_lo_index);
612 let lo = file_lo.lines[line_lo - 1] + col_lo;
615 let expn_info_tag = u8::decode(self)?;
617 let ctxt = match expn_info_tag {
618 TAG_NO_EXPANSION_INFO => {
619 SyntaxContext::empty()
621 TAG_EXPANSION_INFO_INLINE => {
622 let pos = AbsoluteBytePos::new(self.opaque.position());
623 let expn_info: ExpnInfo = Decodable::decode(self)?;
624 let ctxt = SyntaxContext::allocate_directly(expn_info);
625 self.synthetic_expansion_infos.borrow_mut().insert(pos, ctxt);
628 TAG_EXPANSION_INFO_SHORTHAND => {
629 let pos = AbsoluteBytePos::decode(self)?;
630 let cached_ctxt = self.synthetic_expansion_infos
635 if let Some(ctxt) = cached_ctxt {
638 let expn_info = self.with_position(pos.to_usize(), |this| {
639 ExpnInfo::decode(this)
641 let ctxt = SyntaxContext::allocate_directly(expn_info);
642 self.synthetic_expansion_infos.borrow_mut().insert(pos, ctxt);
651 Ok(Span::new(lo, hi, ctxt))
655 // This impl makes sure that we get a runtime error when we try decode a
656 // DefIndex that is not contained in a DefId. Such a case would be problematic
657 // because we would not know how to transform the DefIndex to the current
659 impl<'a, 'tcx, 'x> SpecializedDecoder<DefIndex> for CacheDecoder<'a, 'tcx, 'x> {
660 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
661 bug!("Trying to decode DefIndex outside the context of a DefId")
665 // Both the CrateNum and the DefIndex of a DefId can change in between two
666 // compilation sessions. We use the DefPathHash, which is stable across
667 // sessions, to map the old DefId to the new one.
668 impl<'a, 'tcx, 'x> SpecializedDecoder<DefId> for CacheDecoder<'a, 'tcx, 'x> {
670 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
671 // Load the DefPathHash which is was we encoded the DefId as.
672 let def_path_hash = DefPathHash::decode(self)?;
674 // Using the DefPathHash, we can lookup the new DefId
675 Ok(self.tcx().def_path_hash_to_def_id.as_ref().unwrap()[&def_path_hash])
679 impl<'a, 'tcx, 'x> SpecializedDecoder<LocalDefId> for CacheDecoder<'a, 'tcx, 'x> {
681 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
682 Ok(LocalDefId::from_def_id(DefId::decode(self)?))
686 impl<'a, 'tcx, 'x> SpecializedDecoder<hir::HirId> for CacheDecoder<'a, 'tcx, 'x> {
687 fn specialized_decode(&mut self) -> Result<hir::HirId, Self::Error> {
688 // Load the DefPathHash which is was we encoded the DefIndex as.
689 let def_path_hash = DefPathHash::decode(self)?;
691 // Use the DefPathHash to map to the current DefId.
692 let def_id = self.tcx()
693 .def_path_hash_to_def_id
695 .unwrap()[&def_path_hash];
697 debug_assert!(def_id.is_local());
699 // The ItemLocalId needs no remapping.
700 let local_id = hir::ItemLocalId::decode(self)?;
702 // Reconstruct the HirId and look up the corresponding NodeId in the
703 // context of the current session.
711 // NodeIds are not stable across compilation sessions, so we store them in their
712 // HirId representation. This allows use to map them to the current NodeId.
713 impl<'a, 'tcx, 'x> SpecializedDecoder<NodeId> for CacheDecoder<'a, 'tcx, 'x> {
715 fn specialized_decode(&mut self) -> Result<NodeId, Self::Error> {
716 let hir_id = hir::HirId::decode(self)?;
717 Ok(self.tcx().hir().hir_to_node_id(hir_id))
721 impl<'a, 'tcx, 'x> SpecializedDecoder<Fingerprint> for CacheDecoder<'a, 'tcx, 'x> {
722 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
723 Fingerprint::decode_opaque(&mut self.opaque)
727 impl<'a, 'tcx, 'x, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
728 for CacheDecoder<'a, 'tcx, 'x> {
730 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
731 let discr = u8::decode(self)?;
734 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(mir::ClearCrossCrate::Clear),
735 TAG_CLEAR_CROSS_CRATE_SET => {
736 let val = T::decode(self)?;
737 Ok(mir::ClearCrossCrate::Set(val))
746 //- ENCODING -------------------------------------------------------------------
748 struct CacheEncoder<'enc, 'a, 'tcx, E>
749 where E: 'enc + ty_codec::TyEncoder,
752 tcx: TyCtxt<'a, 'tcx, 'tcx>,
753 encoder: &'enc mut E,
754 type_shorthands: FxHashMap<ty::Ty<'tcx>, usize>,
755 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
756 expn_info_shorthands: FxHashMap<Mark, AbsoluteBytePos>,
757 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
758 interpret_allocs_inverse: Vec<interpret::AllocId>,
759 source_map: CachingSourceMapView<'tcx>,
760 file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
763 impl<'enc, 'a, 'tcx, E> CacheEncoder<'enc, 'a, 'tcx, E>
764 where E: 'enc + ty_codec::TyEncoder
766 fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
767 self.file_to_file_index[&(&*source_file as *const SourceFile)]
770 /// Encode something with additional information that allows to do some
771 /// sanity checks when decoding the data again. This method will first
772 /// encode the specified tag, then the given value, then the number of
773 /// bytes taken up by tag and value. On decoding, we can then verify that
774 /// we get the expected tag and read the expected number of bytes.
775 fn encode_tagged<T: Encodable, V: Encodable>(&mut self,
778 -> Result<(), E::Error>
780 use ty::codec::TyEncoder;
781 let start_pos = self.position();
786 let end_pos = self.position();
787 ((end_pos - start_pos) as u64).encode(self)
791 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<interpret::AllocId> for CacheEncoder<'enc, 'a, 'tcx, E>
792 where E: 'enc + ty_codec::TyEncoder
794 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
795 use std::collections::hash_map::Entry;
796 let index = match self.interpret_allocs.entry(*alloc_id) {
797 Entry::Occupied(e) => *e.get(),
798 Entry::Vacant(e) => {
799 let idx = self.interpret_allocs_inverse.len();
800 self.interpret_allocs_inverse.push(*alloc_id);
810 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<Span> for CacheEncoder<'enc, 'a, 'tcx, E>
811 where E: 'enc + ty_codec::TyEncoder
813 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
815 if *span == DUMMY_SP {
816 return TAG_INVALID_SPAN.encode(self);
819 let span_data = span.data();
821 if span_data.hi < span_data.lo {
822 return TAG_INVALID_SPAN.encode(self);
825 let (file_lo, line_lo, col_lo) = match self.source_map
826 .byte_pos_to_line_and_col(span_data.lo) {
828 None => return TAG_INVALID_SPAN.encode(self)
831 if !file_lo.contains(span_data.hi) {
832 return TAG_INVALID_SPAN.encode(self);
835 let len = span_data.hi - span_data.lo;
837 let source_file_index = self.source_file_index(file_lo);
839 TAG_VALID_SPAN.encode(self)?;
840 source_file_index.encode(self)?;
841 line_lo.encode(self)?;
842 col_lo.encode(self)?;
845 if span_data.ctxt == SyntaxContext::empty() {
846 TAG_NO_EXPANSION_INFO.encode(self)
848 let mark = span_data.ctxt.outer();
850 if let Some(expn_info) = mark.expn_info() {
851 if let Some(pos) = self.expn_info_shorthands.get(&mark).cloned() {
852 TAG_EXPANSION_INFO_SHORTHAND.encode(self)?;
855 TAG_EXPANSION_INFO_INLINE.encode(self)?;
856 let pos = AbsoluteBytePos::new(self.position());
857 self.expn_info_shorthands.insert(mark, pos);
858 expn_info.encode(self)
861 TAG_NO_EXPANSION_INFO.encode(self)
867 impl<'enc, 'a, 'tcx, E> ty_codec::TyEncoder for CacheEncoder<'enc, 'a, 'tcx, E>
868 where E: 'enc + ty_codec::TyEncoder
871 fn position(&self) -> usize {
872 self.encoder.position()
876 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<CrateNum> for CacheEncoder<'enc, 'a, 'tcx, E>
877 where E: 'enc + ty_codec::TyEncoder
880 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
881 self.emit_u32(cnum.as_u32())
885 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<ty::Ty<'tcx>> for CacheEncoder<'enc, 'a, 'tcx, E>
886 where E: 'enc + ty_codec::TyEncoder
889 fn specialized_encode(&mut self, ty: &ty::Ty<'tcx>) -> Result<(), Self::Error> {
890 ty_codec::encode_with_shorthand(self, ty,
891 |encoder| &mut encoder.type_shorthands)
895 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<ty::GenericPredicates<'tcx>>
896 for CacheEncoder<'enc, 'a, 'tcx, E>
897 where E: 'enc + ty_codec::TyEncoder
900 fn specialized_encode(&mut self,
901 predicates: &ty::GenericPredicates<'tcx>)
902 -> Result<(), Self::Error> {
903 ty_codec::encode_predicates(self, predicates,
904 |encoder| &mut encoder.predicate_shorthands)
908 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<hir::HirId> for CacheEncoder<'enc, 'a, 'tcx, E>
909 where E: 'enc + ty_codec::TyEncoder
912 fn specialized_encode(&mut self, id: &hir::HirId) -> Result<(), Self::Error> {
918 let def_path_hash = self.tcx.hir().definitions().def_path_hash(owner);
920 def_path_hash.encode(self)?;
921 local_id.encode(self)
926 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<DefId> for CacheEncoder<'enc, 'a, 'tcx, E>
927 where E: 'enc + ty_codec::TyEncoder
930 fn specialized_encode(&mut self, id: &DefId) -> Result<(), Self::Error> {
931 let def_path_hash = self.tcx.def_path_hash(*id);
932 def_path_hash.encode(self)
936 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<LocalDefId> for CacheEncoder<'enc, 'a, 'tcx, E>
937 where E: 'enc + ty_codec::TyEncoder
940 fn specialized_encode(&mut self, id: &LocalDefId) -> Result<(), Self::Error> {
941 id.to_def_id().encode(self)
945 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<DefIndex> for CacheEncoder<'enc, 'a, 'tcx, E>
946 where E: 'enc + ty_codec::TyEncoder
948 fn specialized_encode(&mut self, _: &DefIndex) -> Result<(), Self::Error> {
949 bug!("Encoding DefIndex without context.")
953 // NodeIds are not stable across compilation sessions, so we store them in their
954 // HirId representation. This allows use to map them to the current NodeId.
955 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<NodeId> for CacheEncoder<'enc, 'a, 'tcx, E>
956 where E: 'enc + ty_codec::TyEncoder
959 fn specialized_encode(&mut self, node_id: &NodeId) -> Result<(), Self::Error> {
960 let hir_id = self.tcx.hir().node_to_hir_id(*node_id);
965 impl<'enc, 'a, 'tcx> SpecializedEncoder<Fingerprint>
966 for CacheEncoder<'enc, 'a, 'tcx, opaque::Encoder>
968 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
969 f.encode_opaque(&mut self.encoder)
973 impl<'enc, 'a, 'tcx, E, T> SpecializedEncoder<mir::ClearCrossCrate<T>>
974 for CacheEncoder<'enc, 'a, 'tcx, E>
975 where E: 'enc + ty_codec::TyEncoder,
979 fn specialized_encode(&mut self,
980 val: &mir::ClearCrossCrate<T>)
981 -> Result<(), Self::Error> {
983 mir::ClearCrossCrate::Clear => {
984 TAG_CLEAR_CROSS_CRATE_CLEAR.encode(self)
986 mir::ClearCrossCrate::Set(ref val) => {
987 TAG_CLEAR_CROSS_CRATE_SET.encode(self)?;
994 macro_rules! encoder_methods {
995 ($($name:ident($ty:ty);)*) => {
996 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
997 self.encoder.$name(value)
1002 impl<'enc, 'a, 'tcx, E> Encoder for CacheEncoder<'enc, 'a, 'tcx, E>
1003 where E: 'enc + ty_codec::TyEncoder
1005 type Error = E::Error;
1007 fn emit_unit(&mut self) -> Result<(), Self::Error> {
1034 // An integer that will always encode to 8 bytes.
1035 struct IntEncodedWithFixedSize(u64);
1037 impl IntEncodedWithFixedSize {
1038 pub const ENCODED_SIZE: usize = 8;
1041 impl UseSpecializedEncodable for IntEncodedWithFixedSize {}
1042 impl UseSpecializedDecodable for IntEncodedWithFixedSize {}
1044 impl SpecializedEncoder<IntEncodedWithFixedSize> for opaque::Encoder {
1045 fn specialized_encode(&mut self, x: &IntEncodedWithFixedSize) -> Result<(), Self::Error> {
1046 let start_pos = self.position();
1047 for i in 0 .. IntEncodedWithFixedSize::ENCODED_SIZE {
1048 ((x.0 >> i * 8) as u8).encode(self)?;
1050 let end_pos = self.position();
1051 assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1056 impl<'enc> SpecializedDecoder<IntEncodedWithFixedSize> for opaque::Decoder<'enc> {
1057 fn specialized_decode(&mut self) -> Result<IntEncodedWithFixedSize, Self::Error> {
1058 let mut value: u64 = 0;
1059 let start_pos = self.position();
1061 for i in 0 .. IntEncodedWithFixedSize::ENCODED_SIZE {
1062 let byte: u8 = Decodable::decode(self)?;
1063 value |= (byte as u64) << (i * 8);
1066 let end_pos = self.position();
1067 assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1069 Ok(IntEncodedWithFixedSize(value))
1073 fn encode_query_results<'enc, 'a, 'tcx, Q, E>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1074 encoder: &mut CacheEncoder<'enc, 'a, 'tcx, E>,
1075 query_result_index: &mut EncodedQueryResultIndex)
1076 -> Result<(), E::Error>
1077 where Q: super::config::QueryDescription<'tcx>,
1078 E: 'enc + TyEncoder,
1079 Q::Value: Encodable,
1081 let desc = &format!("encode_query_results for {}",
1082 unsafe { ::std::intrinsics::type_name::<Q>() });
1084 time(tcx.sess, desc, || {
1086 let map = Q::query_cache(tcx).borrow();
1087 assert!(map.active.is_empty());
1088 for (key, entry) in map.results.iter() {
1089 if Q::cache_on_disk(key.clone()) {
1090 let dep_node = SerializedDepNodeIndex::new(entry.index.index());
1092 // Record position of the cache entry
1093 query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.position())));
1095 // Encode the type check tables with the SerializedDepNodeIndex
1097 encoder.encode_tagged(dep_node, &entry.value)?;