1 use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
3 use crate::hir::def_id::{CrateNum, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
4 use crate::hir::map::definitions::DefPathHash;
5 use crate::ich::{CachingSourceMapView, Fingerprint};
6 use crate::mir::{self, interpret};
7 use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState};
8 use crate::rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque,
9 SpecializedDecoder, SpecializedEncoder,
10 UseSpecializedDecodable, UseSpecializedEncodable};
11 use crate::session::{CrateDisambiguator, Session};
13 use crate::ty::codec::{self as ty_codec, TyDecoder, TyEncoder};
14 use crate::ty::context::TyCtxt;
15 use crate::util::common::time;
17 use errors::Diagnostic;
18 use rustc_data_structures::fx::FxHashMap;
19 use rustc_data_structures::thin_vec::ThinVec;
20 use rustc_data_structures::sync::{Lrc, Lock, HashMapExt, Once};
21 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
23 use syntax::ast::NodeId;
24 use syntax::source_map::{SourceMap, StableSourceFileId};
25 use syntax_pos::{BytePos, Span, DUMMY_SP, SourceFile};
26 use syntax_pos::hygiene::{Mark, SyntaxContext, ExpnInfo};
28 const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
30 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
31 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
33 const TAG_NO_EXPANSION_INFO: u8 = 0;
34 const TAG_EXPANSION_INFO_SHORTHAND: u8 = 1;
35 const TAG_EXPANSION_INFO_INLINE: u8 = 2;
37 const TAG_VALID_SPAN: u8 = 0;
38 const TAG_INVALID_SPAN: u8 = 1;
40 /// `OnDiskCache` provides an interface to incr. comp. data cached from the
41 /// previous compilation session. This data will eventually include the results
42 /// of a few selected queries (like `typeck_tables_of` and `mir_optimized`) and
43 /// any diagnostics that have been emitted during a query.
44 pub struct OnDiskCache<'sess> {
46 // The complete cache data in serialized form.
47 serialized_data: Vec<u8>,
49 // This field collects all Diagnostics emitted during the current
50 // compilation session.
51 current_diagnostics: Lock<FxHashMap<DepNodeIndex, Vec<Diagnostic>>>,
53 prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
54 cnum_map: Once<IndexVec<CrateNum, Option<CrateNum>>>,
56 source_map: &'sess SourceMap,
57 file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
59 // These two fields caches that are populated lazily during decoding.
60 file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
61 synthetic_expansion_infos: Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
63 // A map from dep-node to the position of the cached query result in
65 query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
67 // A map from dep-node to the position of any associated diagnostics in
69 prev_diagnostics_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
71 alloc_decoding_state: AllocDecodingState,
74 // This type is used only for (de-)serialization.
75 #[derive(RustcEncodable, RustcDecodable)]
77 file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
78 prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
79 query_result_index: EncodedQueryResultIndex,
80 diagnostics_index: EncodedQueryResultIndex,
81 // the location of all allocations
82 interpret_alloc_index: Vec<u32>,
85 type EncodedQueryResultIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
86 type EncodedDiagnosticsIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
87 type EncodedDiagnostics = Vec<Diagnostic>;
89 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
90 struct SourceFileIndex(u32);
92 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, RustcEncodable, RustcDecodable)]
93 struct AbsoluteBytePos(u32);
95 impl AbsoluteBytePos {
96 fn new(pos: usize) -> AbsoluteBytePos {
97 debug_assert!(pos <= ::std::u32::MAX as usize);
98 AbsoluteBytePos(pos as u32)
101 fn to_usize(self) -> usize {
106 impl<'sess> OnDiskCache<'sess> {
107 /// Creates a new OnDiskCache instance from the serialized data in `data`.
108 pub fn new(sess: &'sess Session, data: Vec<u8>, start_pos: usize) -> OnDiskCache<'sess> {
109 debug_assert!(sess.opts.incremental.is_some());
111 // Wrapping in a scope so we can borrow `data`
112 let footer: Footer = {
113 let mut decoder = opaque::Decoder::new(&data[..], start_pos);
115 // Decode the *position* of the footer which can be found in the
116 // last 8 bytes of the file.
117 decoder.set_position(data.len() - IntEncodedWithFixedSize::ENCODED_SIZE);
118 let query_result_index_pos = IntEncodedWithFixedSize::decode(&mut decoder)
119 .expect("Error while trying to decode query result index position.")
122 // Decoder the file footer which contains all the lookup tables, etc.
123 decoder.set_position(query_result_index_pos);
124 decode_tagged(&mut decoder, TAG_FILE_FOOTER)
125 .expect("Error while trying to decode query result index position.")
129 serialized_data: data,
130 file_index_to_stable_id: footer.file_index_to_stable_id,
131 file_index_to_file: Default::default(),
132 prev_cnums: footer.prev_cnums,
133 cnum_map: Once::new(),
134 source_map: sess.source_map(),
135 current_diagnostics: Default::default(),
136 query_result_index: footer.query_result_index.into_iter().collect(),
137 prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
138 synthetic_expansion_infos: Default::default(),
139 alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
143 pub fn new_empty(source_map: &'sess SourceMap) -> OnDiskCache<'sess> {
145 serialized_data: Vec::new(),
146 file_index_to_stable_id: Default::default(),
147 file_index_to_file: Default::default(),
149 cnum_map: Once::new(),
151 current_diagnostics: Default::default(),
152 query_result_index: Default::default(),
153 prev_diagnostics_index: Default::default(),
154 synthetic_expansion_infos: Default::default(),
155 alloc_decoding_state: AllocDecodingState::new(Vec::new()),
159 pub fn serialize<'a, 'tcx, E>(&self,
160 tcx: TyCtxt<'a, 'tcx, 'tcx>,
162 -> Result<(), E::Error>
163 where E: ty_codec::TyEncoder
165 // Serializing the DepGraph should not modify it:
166 tcx.dep_graph.with_ignore(|| {
167 // Allocate SourceFileIndices
168 let (file_to_file_index, file_index_to_stable_id) = {
169 let files = tcx.sess.source_map().files();
170 let mut file_to_file_index = FxHashMap::with_capacity_and_hasher(
171 files.len(), Default::default());
172 let mut file_index_to_stable_id = FxHashMap::with_capacity_and_hasher(
173 files.len(), Default::default());
175 for (index, file) in files.iter().enumerate() {
176 let index = SourceFileIndex(index as u32);
177 let file_ptr: *const SourceFile = &**file as *const _;
178 file_to_file_index.insert(file_ptr, index);
179 file_index_to_stable_id.insert(index, StableSourceFileId::new(&file));
182 (file_to_file_index, file_index_to_stable_id)
185 let mut encoder = CacheEncoder {
188 type_shorthands: Default::default(),
189 predicate_shorthands: Default::default(),
190 expn_info_shorthands: Default::default(),
191 interpret_allocs: Default::default(),
192 interpret_allocs_inverse: Vec::new(),
193 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
197 // Load everything into memory so we can write it out to the on-disk
198 // cache. The vast majority of cacheable query results should already
199 // be in memory, so this should be a cheap operation.
200 tcx.dep_graph.exec_cache_promotions(tcx);
202 // Encode query results
203 let mut query_result_index = EncodedQueryResultIndex::new();
205 time(tcx.sess, "encode query results", || {
206 use crate::ty::query::queries::*;
207 let enc = &mut encoder;
208 let qri = &mut query_result_index;
210 encode_query_results::<type_of<'_>, _>(tcx, enc, qri)?;
211 encode_query_results::<generics_of<'_>, _>(tcx, enc, qri)?;
212 encode_query_results::<predicates_of<'_>, _>(tcx, enc, qri)?;
213 encode_query_results::<used_trait_imports<'_>, _>(tcx, enc, qri)?;
214 encode_query_results::<typeck_tables_of<'_>, _>(tcx, enc, qri)?;
215 encode_query_results::<codegen_fulfill_obligation<'_>, _>(tcx, enc, qri)?;
216 encode_query_results::<optimized_mir<'_>, _>(tcx, enc, qri)?;
217 encode_query_results::<unsafety_check_result<'_>, _>(tcx, enc, qri)?;
218 encode_query_results::<borrowck<'_>, _>(tcx, enc, qri)?;
219 encode_query_results::<mir_borrowck<'_>, _>(tcx, enc, qri)?;
220 encode_query_results::<mir_const_qualif<'_>, _>(tcx, enc, qri)?;
221 encode_query_results::<def_symbol_name<'_>, _>(tcx, enc, qri)?;
222 encode_query_results::<const_is_rvalue_promotable_to_static<'_>, _>(tcx, enc, qri)?;
223 encode_query_results::<symbol_name<'_>, _>(tcx, enc, qri)?;
224 encode_query_results::<check_match<'_>, _>(tcx, enc, qri)?;
225 encode_query_results::<codegen_fn_attrs<'_>, _>(tcx, enc, qri)?;
226 encode_query_results::<specialization_graph_of<'_>, _>(tcx, enc, qri)?;
228 // const eval is special, it only encodes successfully evaluated constants
229 use crate::ty::query::QueryAccessors;
230 let cache = const_eval::query_cache(tcx).borrow();
231 assert!(cache.active.is_empty());
232 for (key, entry) in cache.results.iter() {
233 use crate::ty::query::config::QueryDescription;
234 if const_eval::cache_on_disk(tcx, key.clone()) {
235 if let Ok(ref value) = entry.value {
236 let dep_node = SerializedDepNodeIndex::new(entry.index.index());
238 // Record position of the cache entry
239 qri.push((dep_node, AbsoluteBytePos::new(enc.position())));
241 // Encode the type check tables with the SerializedDepNodeIndex
243 enc.encode_tagged(dep_node, value)?;
251 // Encode diagnostics
252 let diagnostics_index: EncodedDiagnosticsIndex = self.current_diagnostics.borrow()
254 .map(|(dep_node_index, diagnostics)|
256 let pos = AbsoluteBytePos::new(encoder.position());
257 // Let's make sure we get the expected type here:
258 let diagnostics: &EncodedDiagnostics = diagnostics;
259 let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
260 encoder.encode_tagged(dep_node_index, diagnostics)?;
262 Ok((dep_node_index, pos))
264 .collect::<Result<_, _>>()?;
266 let interpret_alloc_index = {
267 let mut interpret_alloc_index = Vec::new();
270 let new_n = encoder.interpret_allocs_inverse.len();
271 // if we have found new ids, serialize those, too
276 interpret_alloc_index.reserve(new_n - n);
277 for idx in n..new_n {
278 let id = encoder.interpret_allocs_inverse[idx];
279 let pos = encoder.position() as u32;
280 interpret_alloc_index.push(pos);
281 interpret::specialized_encode_alloc_id(
289 interpret_alloc_index
292 let sorted_cnums = sorted_cnums_including_local_crate(tcx);
293 let prev_cnums: Vec<_> = sorted_cnums.iter().map(|&cnum| {
294 let crate_name = tcx.original_crate_name(cnum).as_str().to_string();
295 let crate_disambiguator = tcx.crate_disambiguator(cnum);
296 (cnum.as_u32(), crate_name, crate_disambiguator)
299 // Encode the file footer
300 let footer_pos = encoder.position() as u64;
301 encoder.encode_tagged(TAG_FILE_FOOTER, &Footer {
302 file_index_to_stable_id,
306 interpret_alloc_index,
309 // Encode the position of the footer as the last 8 bytes of the
310 // file so we know where to look for it.
311 IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder)?;
313 // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
314 // of the footer must be the last thing in the data stream.
318 fn sorted_cnums_including_local_crate(tcx: TyCtxt<'_, '_, '_>) -> Vec<CrateNum> {
319 let mut cnums = vec![LOCAL_CRATE];
320 cnums.extend_from_slice(&tcx.crates()[..]);
321 cnums.sort_unstable();
322 // Just to be sure...
329 /// Loads a diagnostic emitted during the previous compilation session.
330 pub fn load_diagnostics<'a, 'tcx>(&self,
331 tcx: TyCtxt<'a, 'tcx, 'tcx>,
332 dep_node_index: SerializedDepNodeIndex)
334 let diagnostics: Option<EncodedDiagnostics> = self.load_indexed(
337 &self.prev_diagnostics_index,
340 diagnostics.unwrap_or_default()
343 /// Stores a diagnostic emitted during the current compilation session.
344 /// Anything stored like this will be available via `load_diagnostics` in
345 /// the next compilation session.
348 pub fn store_diagnostics(&self,
349 dep_node_index: DepNodeIndex,
350 diagnostics: ThinVec<Diagnostic>) {
351 let mut current_diagnostics = self.current_diagnostics.borrow_mut();
352 let prev = current_diagnostics.insert(dep_node_index, diagnostics.into());
353 debug_assert!(prev.is_none());
356 /// Returns the cached query result if there is something in the cache for
357 /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
358 pub fn try_load_query_result<'tcx, T>(&self,
359 tcx: TyCtxt<'_, 'tcx, 'tcx>,
360 dep_node_index: SerializedDepNodeIndex)
364 self.load_indexed(tcx,
366 &self.query_result_index,
370 /// Stores a diagnostic emitted during computation of an anonymous query.
371 /// Since many anonymous queries can share the same `DepNode`, we aggregate
372 /// them -- as opposed to regular queries where we assume that there is a
373 /// 1:1 relationship between query-key and `DepNode`.
376 pub fn store_diagnostics_for_anon_node(&self,
377 dep_node_index: DepNodeIndex,
378 diagnostics: ThinVec<Diagnostic>) {
379 let mut current_diagnostics = self.current_diagnostics.borrow_mut();
381 let x = current_diagnostics.entry(dep_node_index).or_insert(Vec::new());
383 x.extend(Into::<Vec<_>>::into(diagnostics));
386 fn load_indexed<'tcx, T>(&self,
387 tcx: TyCtxt<'_, 'tcx, 'tcx>,
388 dep_node_index: SerializedDepNodeIndex,
389 index: &FxHashMap<SerializedDepNodeIndex,
391 debug_tag: &'static str)
395 let pos = index.get(&dep_node_index).cloned()?;
397 // Initialize the cnum_map using the value from the thread which finishes the closure first
398 self.cnum_map.init_nonlocking_same(|| {
399 Self::compute_cnum_map(tcx, &self.prev_cnums[..])
402 let mut decoder = CacheDecoder {
404 opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()),
405 source_map: self.source_map,
406 cnum_map: self.cnum_map.get(),
407 file_index_to_file: &self.file_index_to_file,
408 file_index_to_stable_id: &self.file_index_to_stable_id,
409 synthetic_expansion_infos: &self.synthetic_expansion_infos,
410 alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
413 match decode_tagged(&mut decoder, dep_node_index) {
418 bug!("Could not decode cached {}: {}", debug_tag, e)
423 // This function builds mapping from previous-session-CrateNum to
424 // current-session-CrateNum. There might be CrateNums from the previous
425 // Session that don't occur in the current one. For these, the mapping
427 fn compute_cnum_map(tcx: TyCtxt<'_, '_, '_>,
428 prev_cnums: &[(u32, String, CrateDisambiguator)])
429 -> IndexVec<CrateNum, Option<CrateNum>>
431 tcx.dep_graph.with_ignore(|| {
432 let current_cnums = tcx.all_crate_nums(LOCAL_CRATE).iter().map(|&cnum| {
433 let crate_name = tcx.original_crate_name(cnum)
435 let crate_disambiguator = tcx.crate_disambiguator(cnum);
436 ((crate_name, crate_disambiguator), cnum)
437 }).collect::<FxHashMap<_,_>>();
439 let map_size = prev_cnums.iter()
440 .map(|&(cnum, ..)| cnum)
443 let mut map = IndexVec::from_elem_n(None, map_size as usize);
445 for &(prev_cnum, ref crate_name, crate_disambiguator) in prev_cnums {
446 let key = (crate_name.clone(), crate_disambiguator);
447 map[CrateNum::from_u32(prev_cnum)] = current_cnums.get(&key).cloned();
450 map[LOCAL_CRATE] = Some(LOCAL_CRATE);
456 //- DECODING -------------------------------------------------------------------
458 /// A decoder that can read the incr. comp. cache. It is similar to the one
459 /// we use for crate metadata decoding in that it can rebase spans and
460 /// eventually will also handle things that contain `Ty` instances.
461 struct CacheDecoder<'a, 'tcx: 'a, 'x> {
462 tcx: TyCtxt<'a, 'tcx, 'tcx>,
463 opaque: opaque::Decoder<'x>,
464 source_map: &'x SourceMap,
465 cnum_map: &'x IndexVec<CrateNum, Option<CrateNum>>,
466 synthetic_expansion_infos: &'x Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
467 file_index_to_file: &'x Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
468 file_index_to_stable_id: &'x FxHashMap<SourceFileIndex, StableSourceFileId>,
469 alloc_decoding_session: AllocDecodingSession<'x>,
472 impl<'a, 'tcx, 'x> CacheDecoder<'a, 'tcx, 'x> {
473 fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
475 ref file_index_to_file,
476 ref file_index_to_stable_id,
481 file_index_to_file.borrow_mut().entry(index).or_insert_with(|| {
482 let stable_id = file_index_to_stable_id[&index];
483 source_map.source_file_by_stable_id(stable_id)
484 .expect("Failed to lookup SourceFile in new context.")
489 trait DecoderWithPosition: Decoder {
490 fn position(&self) -> usize;
493 impl<'enc> DecoderWithPosition for opaque::Decoder<'enc> {
494 fn position(&self) -> usize {
499 impl<'a, 'tcx, 'x> DecoderWithPosition for CacheDecoder<'a, 'tcx, 'x> {
500 fn position(&self) -> usize {
501 self.opaque.position()
505 // Decode something that was encoded with encode_tagged() and verify that the
506 // tag matches and the correct amount of bytes was read.
507 fn decode_tagged<'a, 'tcx, D, T, V>(decoder: &mut D,
509 -> Result<V, D::Error>
510 where T: Decodable + Eq + ::std::fmt::Debug,
512 D: DecoderWithPosition,
515 let start_pos = decoder.position();
517 let actual_tag = T::decode(decoder)?;
518 assert_eq!(actual_tag, expected_tag);
519 let value = V::decode(decoder)?;
520 let end_pos = decoder.position();
522 let expected_len: u64 = Decodable::decode(decoder)?;
523 assert_eq!((end_pos - start_pos) as u64, expected_len);
529 impl<'a, 'tcx: 'a, 'x> ty_codec::TyDecoder<'a, 'tcx> for CacheDecoder<'a, 'tcx, 'x> {
532 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
537 fn position(&self) -> usize {
538 self.opaque.position()
542 fn peek_byte(&self) -> u8 {
543 self.opaque.data[self.opaque.position()]
546 fn cached_ty_for_shorthand<F>(&mut self,
549 -> Result<ty::Ty<'tcx>, Self::Error>
550 where F: FnOnce(&mut Self) -> Result<ty::Ty<'tcx>, Self::Error>
552 let tcx = self.tcx();
554 let cache_key = ty::CReaderCacheKey {
555 cnum: CrateNum::ReservedForIncrCompCache,
559 if let Some(&ty) = tcx.rcache.borrow().get(&cache_key) {
563 let ty = or_insert_with(self)?;
564 // This may overwrite the entry, but it should overwrite with the same value
565 tcx.rcache.borrow_mut().insert_same(cache_key, ty);
569 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
570 where F: FnOnce(&mut Self) -> R
572 debug_assert!(pos < self.opaque.data.len());
574 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
575 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
577 self.opaque = old_opaque;
581 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
582 self.cnum_map[cnum].unwrap_or_else(|| {
583 bug!("Could not find new CrateNum for {:?}", cnum)
588 implement_ty_decoder!( CacheDecoder<'a, 'tcx, 'x> );
590 impl<'a, 'tcx, 'x> SpecializedDecoder<interpret::AllocId> for CacheDecoder<'a, 'tcx, 'x> {
591 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
592 let alloc_decoding_session = self.alloc_decoding_session;
593 alloc_decoding_session.decode_alloc_id(self)
597 impl<'a, 'tcx, 'x> SpecializedDecoder<Span> for CacheDecoder<'a, 'tcx, 'x> {
598 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
599 let tag: u8 = Decodable::decode(self)?;
601 if tag == TAG_INVALID_SPAN {
604 debug_assert_eq!(tag, TAG_VALID_SPAN);
607 let file_lo_index = SourceFileIndex::decode(self)?;
608 let line_lo = usize::decode(self)?;
609 let col_lo = BytePos::decode(self)?;
610 let len = BytePos::decode(self)?;
612 let file_lo = self.file_index_to_file(file_lo_index);
613 let lo = file_lo.lines[line_lo - 1] + col_lo;
616 let expn_info_tag = u8::decode(self)?;
618 let ctxt = match expn_info_tag {
619 TAG_NO_EXPANSION_INFO => {
620 SyntaxContext::empty()
622 TAG_EXPANSION_INFO_INLINE => {
623 let pos = AbsoluteBytePos::new(self.opaque.position());
624 let expn_info: ExpnInfo = Decodable::decode(self)?;
625 let ctxt = SyntaxContext::allocate_directly(expn_info);
626 self.synthetic_expansion_infos.borrow_mut().insert(pos, ctxt);
629 TAG_EXPANSION_INFO_SHORTHAND => {
630 let pos = AbsoluteBytePos::decode(self)?;
631 let cached_ctxt = self.synthetic_expansion_infos
636 if let Some(ctxt) = cached_ctxt {
639 let expn_info = self.with_position(pos.to_usize(), |this| {
640 ExpnInfo::decode(this)
642 let ctxt = SyntaxContext::allocate_directly(expn_info);
643 self.synthetic_expansion_infos.borrow_mut().insert(pos, ctxt);
652 Ok(Span::new(lo, hi, ctxt))
656 // This impl makes sure that we get a runtime error when we try decode a
657 // DefIndex that is not contained in a DefId. Such a case would be problematic
658 // because we would not know how to transform the DefIndex to the current
660 impl<'a, 'tcx, 'x> SpecializedDecoder<DefIndex> for CacheDecoder<'a, 'tcx, 'x> {
661 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
662 bug!("Trying to decode DefIndex outside the context of a DefId")
666 // Both the CrateNum and the DefIndex of a DefId can change in between two
667 // compilation sessions. We use the DefPathHash, which is stable across
668 // sessions, to map the old DefId to the new one.
669 impl<'a, 'tcx, 'x> SpecializedDecoder<DefId> for CacheDecoder<'a, 'tcx, 'x> {
671 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
672 // Load the DefPathHash which is was we encoded the DefId as.
673 let def_path_hash = DefPathHash::decode(self)?;
675 // Using the DefPathHash, we can lookup the new DefId
676 Ok(self.tcx().def_path_hash_to_def_id.as_ref().unwrap()[&def_path_hash])
680 impl<'a, 'tcx, 'x> SpecializedDecoder<LocalDefId> for CacheDecoder<'a, 'tcx, 'x> {
682 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
683 Ok(LocalDefId::from_def_id(DefId::decode(self)?))
687 impl<'a, 'tcx, 'x> SpecializedDecoder<hir::HirId> for CacheDecoder<'a, 'tcx, 'x> {
688 fn specialized_decode(&mut self) -> Result<hir::HirId, Self::Error> {
689 // Load the DefPathHash which is was we encoded the DefIndex as.
690 let def_path_hash = DefPathHash::decode(self)?;
692 // Use the DefPathHash to map to the current DefId.
693 let def_id = self.tcx()
694 .def_path_hash_to_def_id
696 .unwrap()[&def_path_hash];
698 debug_assert!(def_id.is_local());
700 // The ItemLocalId needs no remapping.
701 let local_id = hir::ItemLocalId::decode(self)?;
703 // Reconstruct the HirId and look up the corresponding NodeId in the
704 // context of the current session.
712 // NodeIds are not stable across compilation sessions, so we store them in their
713 // HirId representation. This allows use to map them to the current NodeId.
714 impl<'a, 'tcx, 'x> SpecializedDecoder<NodeId> for CacheDecoder<'a, 'tcx, 'x> {
716 fn specialized_decode(&mut self) -> Result<NodeId, Self::Error> {
717 let hir_id = hir::HirId::decode(self)?;
718 Ok(self.tcx().hir().hir_to_node_id(hir_id))
722 impl<'a, 'tcx, 'x> SpecializedDecoder<Fingerprint> for CacheDecoder<'a, 'tcx, 'x> {
723 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
724 Fingerprint::decode_opaque(&mut self.opaque)
728 impl<'a, 'tcx, 'x, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
729 for CacheDecoder<'a, 'tcx, 'x> {
731 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
732 let discr = u8::decode(self)?;
735 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(mir::ClearCrossCrate::Clear),
736 TAG_CLEAR_CROSS_CRATE_SET => {
737 let val = T::decode(self)?;
738 Ok(mir::ClearCrossCrate::Set(val))
747 //- ENCODING -------------------------------------------------------------------
749 struct CacheEncoder<'enc, 'a, 'tcx, E>
750 where E: 'enc + ty_codec::TyEncoder,
753 tcx: TyCtxt<'a, 'tcx, 'tcx>,
754 encoder: &'enc mut E,
755 type_shorthands: FxHashMap<ty::Ty<'tcx>, usize>,
756 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
757 expn_info_shorthands: FxHashMap<Mark, AbsoluteBytePos>,
758 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
759 interpret_allocs_inverse: Vec<interpret::AllocId>,
760 source_map: CachingSourceMapView<'tcx>,
761 file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
764 impl<'enc, 'a, 'tcx, E> CacheEncoder<'enc, 'a, 'tcx, E>
765 where E: 'enc + ty_codec::TyEncoder
767 fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
768 self.file_to_file_index[&(&*source_file as *const SourceFile)]
771 /// Encode something with additional information that allows to do some
772 /// sanity checks when decoding the data again. This method will first
773 /// encode the specified tag, then the given value, then the number of
774 /// bytes taken up by tag and value. On decoding, we can then verify that
775 /// we get the expected tag and read the expected number of bytes.
776 fn encode_tagged<T: Encodable, V: Encodable>(&mut self,
779 -> Result<(), E::Error>
781 use crate::ty::codec::TyEncoder;
782 let start_pos = self.position();
787 let end_pos = self.position();
788 ((end_pos - start_pos) as u64).encode(self)
792 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<interpret::AllocId> for CacheEncoder<'enc, 'a, 'tcx, E>
793 where E: 'enc + ty_codec::TyEncoder
795 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
796 use std::collections::hash_map::Entry;
797 let index = match self.interpret_allocs.entry(*alloc_id) {
798 Entry::Occupied(e) => *e.get(),
799 Entry::Vacant(e) => {
800 let idx = self.interpret_allocs_inverse.len();
801 self.interpret_allocs_inverse.push(*alloc_id);
811 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<Span> for CacheEncoder<'enc, 'a, 'tcx, E>
812 where E: 'enc + ty_codec::TyEncoder
814 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
816 if *span == DUMMY_SP {
817 return TAG_INVALID_SPAN.encode(self);
820 let span_data = span.data();
822 if span_data.hi < span_data.lo {
823 return TAG_INVALID_SPAN.encode(self);
826 let (file_lo, line_lo, col_lo) = match self.source_map
827 .byte_pos_to_line_and_col(span_data.lo) {
829 None => return TAG_INVALID_SPAN.encode(self)
832 if !file_lo.contains(span_data.hi) {
833 return TAG_INVALID_SPAN.encode(self);
836 let len = span_data.hi - span_data.lo;
838 let source_file_index = self.source_file_index(file_lo);
840 TAG_VALID_SPAN.encode(self)?;
841 source_file_index.encode(self)?;
842 line_lo.encode(self)?;
843 col_lo.encode(self)?;
846 if span_data.ctxt == SyntaxContext::empty() {
847 TAG_NO_EXPANSION_INFO.encode(self)
849 let mark = span_data.ctxt.outer();
851 if let Some(expn_info) = mark.expn_info() {
852 if let Some(pos) = self.expn_info_shorthands.get(&mark).cloned() {
853 TAG_EXPANSION_INFO_SHORTHAND.encode(self)?;
856 TAG_EXPANSION_INFO_INLINE.encode(self)?;
857 let pos = AbsoluteBytePos::new(self.position());
858 self.expn_info_shorthands.insert(mark, pos);
859 expn_info.encode(self)
862 TAG_NO_EXPANSION_INFO.encode(self)
868 impl<'enc, 'a, 'tcx, E> ty_codec::TyEncoder for CacheEncoder<'enc, 'a, 'tcx, E>
869 where E: 'enc + ty_codec::TyEncoder
872 fn position(&self) -> usize {
873 self.encoder.position()
877 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<CrateNum> for CacheEncoder<'enc, 'a, 'tcx, E>
878 where E: 'enc + ty_codec::TyEncoder
881 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
882 self.emit_u32(cnum.as_u32())
886 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<ty::Ty<'tcx>> for CacheEncoder<'enc, 'a, 'tcx, E>
887 where E: 'enc + ty_codec::TyEncoder
890 fn specialized_encode(&mut self, ty: &ty::Ty<'tcx>) -> Result<(), Self::Error> {
891 ty_codec::encode_with_shorthand(self, ty,
892 |encoder| &mut encoder.type_shorthands)
896 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<ty::GenericPredicates<'tcx>>
897 for CacheEncoder<'enc, 'a, 'tcx, E>
898 where E: 'enc + ty_codec::TyEncoder
901 fn specialized_encode(&mut self,
902 predicates: &ty::GenericPredicates<'tcx>)
903 -> Result<(), Self::Error> {
904 ty_codec::encode_predicates(self, predicates,
905 |encoder| &mut encoder.predicate_shorthands)
909 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<hir::HirId> for CacheEncoder<'enc, 'a, 'tcx, E>
910 where E: 'enc + ty_codec::TyEncoder
913 fn specialized_encode(&mut self, id: &hir::HirId) -> Result<(), Self::Error> {
919 let def_path_hash = self.tcx.hir().definitions().def_path_hash(owner);
921 def_path_hash.encode(self)?;
922 local_id.encode(self)
927 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<DefId> for CacheEncoder<'enc, 'a, 'tcx, E>
928 where E: 'enc + ty_codec::TyEncoder
931 fn specialized_encode(&mut self, id: &DefId) -> Result<(), Self::Error> {
932 let def_path_hash = self.tcx.def_path_hash(*id);
933 def_path_hash.encode(self)
937 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<LocalDefId> for CacheEncoder<'enc, 'a, 'tcx, E>
938 where E: 'enc + ty_codec::TyEncoder
941 fn specialized_encode(&mut self, id: &LocalDefId) -> Result<(), Self::Error> {
942 id.to_def_id().encode(self)
946 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<DefIndex> for CacheEncoder<'enc, 'a, 'tcx, E>
947 where E: 'enc + ty_codec::TyEncoder
949 fn specialized_encode(&mut self, _: &DefIndex) -> Result<(), Self::Error> {
950 bug!("Encoding DefIndex without context.")
954 // NodeIds are not stable across compilation sessions, so we store them in their
955 // HirId representation. This allows use to map them to the current NodeId.
956 impl<'enc, 'a, 'tcx, E> SpecializedEncoder<NodeId> for CacheEncoder<'enc, 'a, 'tcx, E>
957 where E: 'enc + ty_codec::TyEncoder
960 fn specialized_encode(&mut self, node_id: &NodeId) -> Result<(), Self::Error> {
961 let hir_id = self.tcx.hir().node_to_hir_id(*node_id);
966 impl<'enc, 'a, 'tcx> SpecializedEncoder<Fingerprint>
967 for CacheEncoder<'enc, 'a, 'tcx, opaque::Encoder>
969 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
970 f.encode_opaque(&mut self.encoder)
974 impl<'enc, 'a, 'tcx, E, T> SpecializedEncoder<mir::ClearCrossCrate<T>>
975 for CacheEncoder<'enc, 'a, 'tcx, E>
976 where E: 'enc + ty_codec::TyEncoder,
980 fn specialized_encode(&mut self,
981 val: &mir::ClearCrossCrate<T>)
982 -> Result<(), Self::Error> {
984 mir::ClearCrossCrate::Clear => {
985 TAG_CLEAR_CROSS_CRATE_CLEAR.encode(self)
987 mir::ClearCrossCrate::Set(ref val) => {
988 TAG_CLEAR_CROSS_CRATE_SET.encode(self)?;
995 macro_rules! encoder_methods {
996 ($($name:ident($ty:ty);)*) => {
997 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
998 self.encoder.$name(value)
1003 impl<'enc, 'a, 'tcx, E> Encoder for CacheEncoder<'enc, 'a, 'tcx, E>
1004 where E: 'enc + ty_codec::TyEncoder
1006 type Error = E::Error;
1008 fn emit_unit(&mut self) -> Result<(), Self::Error> {
1035 // An integer that will always encode to 8 bytes.
1036 struct IntEncodedWithFixedSize(u64);
1038 impl IntEncodedWithFixedSize {
1039 pub const ENCODED_SIZE: usize = 8;
1042 impl UseSpecializedEncodable for IntEncodedWithFixedSize {}
1043 impl UseSpecializedDecodable for IntEncodedWithFixedSize {}
1045 impl SpecializedEncoder<IntEncodedWithFixedSize> for opaque::Encoder {
1046 fn specialized_encode(&mut self, x: &IntEncodedWithFixedSize) -> Result<(), Self::Error> {
1047 let start_pos = self.position();
1048 for i in 0 .. IntEncodedWithFixedSize::ENCODED_SIZE {
1049 ((x.0 >> i * 8) as u8).encode(self)?;
1051 let end_pos = self.position();
1052 assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1057 impl<'enc> SpecializedDecoder<IntEncodedWithFixedSize> for opaque::Decoder<'enc> {
1058 fn specialized_decode(&mut self) -> Result<IntEncodedWithFixedSize, Self::Error> {
1059 let mut value: u64 = 0;
1060 let start_pos = self.position();
1062 for i in 0 .. IntEncodedWithFixedSize::ENCODED_SIZE {
1063 let byte: u8 = Decodable::decode(self)?;
1064 value |= (byte as u64) << (i * 8);
1067 let end_pos = self.position();
1068 assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1070 Ok(IntEncodedWithFixedSize(value))
1074 fn encode_query_results<'enc, 'a, 'tcx, Q, E>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1075 encoder: &mut CacheEncoder<'enc, 'a, 'tcx, E>,
1076 query_result_index: &mut EncodedQueryResultIndex)
1077 -> Result<(), E::Error>
1078 where Q: super::config::QueryDescription<'tcx>,
1079 E: 'enc + TyEncoder,
1080 Q::Value: Encodable,
1082 let desc = &format!("encode_query_results for {}",
1083 unsafe { ::std::intrinsics::type_name::<Q>() });
1085 time(tcx.sess, desc, || {
1087 let map = Q::query_cache(tcx).borrow();
1088 assert!(map.active.is_empty());
1089 for (key, entry) in map.results.iter() {
1090 if Q::cache_on_disk(tcx, key.clone()) {
1091 let dep_node = SerializedDepNodeIndex::new(entry.index.index());
1093 // Record position of the cache entry
1094 query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.position())));
1096 // Encode the type check tables with the SerializedDepNodeIndex
1098 encoder.encode_tagged(dep_node, &entry.value)?;