1 use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
2 use crate::hir::map::definitions::DefPathHash;
3 use crate::ich::{CachingSourceMapView, Fingerprint};
4 use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState};
5 use crate::mir::{self, interpret};
6 use crate::session::{CrateDisambiguator, Session};
7 use crate::ty::codec::{self as ty_codec, TyDecoder, TyEncoder};
8 use crate::ty::context::TyCtxt;
9 use crate::ty::{self, Ty};
10 use rustc_ast::ast::Ident;
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::sync::{HashMapExt, Lock, Lrc, Once};
13 use rustc_data_structures::thin_vec::ThinVec;
14 use rustc_errors::Diagnostic;
16 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, LOCAL_CRATE};
17 use rustc_index::vec::{Idx, IndexVec};
18 use rustc_serialize::{
19 opaque, Decodable, Decoder, Encodable, Encoder, SpecializedDecoder, SpecializedEncoder,
20 UseSpecializedDecodable, UseSpecializedEncodable,
22 use rustc_span::hygiene::{ExpnId, SyntaxContext};
23 use rustc_span::source_map::{SourceMap, StableSourceFileId};
24 use rustc_span::{BytePos, SourceFile, Span, DUMMY_SP};
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_EXPN_DATA: u8 = 0;
33 const TAG_EXPN_DATA_SHORTHAND: u8 = 1;
34 const TAG_EXPN_DATA_INLINE: u8 = 2;
36 const TAG_VALID_SPAN: u8 = 0;
37 const TAG_INVALID_SPAN: u8 = 1;
39 /// Provides an interface to incremental compilation 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> {
44 // The complete cache data in serialized form.
45 serialized_data: Vec<u8>,
47 // Collects all `Diagnostic`s emitted during the current compilation
49 current_diagnostics: Lock<FxHashMap<DepNodeIndex, Vec<Diagnostic>>>,
51 prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
52 cnum_map: Once<IndexVec<CrateNum, Option<CrateNum>>>,
54 source_map: &'sess SourceMap,
55 file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
57 // Caches that are populated lazily during decoding.
58 file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
59 synthetic_syntax_contexts: Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
61 // A map from dep-node to the position of the cached query result in
63 query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
65 // A map from dep-node to the position of any associated diagnostics in
67 prev_diagnostics_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
69 alloc_decoding_state: AllocDecodingState,
72 // This type is used only for (de-)serialization.
73 #[derive(RustcEncodable, RustcDecodable)]
75 file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
76 prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
77 query_result_index: EncodedQueryResultIndex,
78 diagnostics_index: EncodedQueryResultIndex,
79 // The location of all allocations.
80 interpret_alloc_index: Vec<u32>,
83 type EncodedQueryResultIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
84 type EncodedDiagnosticsIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
85 type EncodedDiagnostics = Vec<Diagnostic>;
87 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
88 struct SourceFileIndex(u32);
90 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, RustcEncodable, RustcDecodable)]
91 struct AbsoluteBytePos(u32);
93 impl AbsoluteBytePos {
94 fn new(pos: usize) -> AbsoluteBytePos {
95 debug_assert!(pos <= ::std::u32::MAX as usize);
96 AbsoluteBytePos(pos as u32)
99 fn to_usize(self) -> usize {
104 impl<'sess> OnDiskCache<'sess> {
105 /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
106 pub fn new(sess: &'sess Session, data: Vec<u8>, start_pos: usize) -> Self {
107 debug_assert!(sess.opts.incremental.is_some());
109 // Wrap in a scope so we can borrow `data`.
110 let footer: Footer = {
111 let mut decoder = opaque::Decoder::new(&data[..], start_pos);
113 // Decode the *position* of the footer, which can be found in the
114 // last 8 bytes of the file.
115 decoder.set_position(data.len() - IntEncodedWithFixedSize::ENCODED_SIZE);
116 let footer_pos = IntEncodedWithFixedSize::decode(&mut decoder)
117 .expect("error while trying to decode footer position")
120 // Decode the file footer, which contains all the lookup tables, etc.
121 decoder.set_position(footer_pos);
122 decode_tagged(&mut decoder, TAG_FILE_FOOTER)
123 .expect("error while trying to decode footer position")
127 serialized_data: data,
128 file_index_to_stable_id: footer.file_index_to_stable_id,
129 file_index_to_file: Default::default(),
130 prev_cnums: footer.prev_cnums,
131 cnum_map: Once::new(),
132 source_map: sess.source_map(),
133 current_diagnostics: Default::default(),
134 query_result_index: footer.query_result_index.into_iter().collect(),
135 prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
136 synthetic_syntax_contexts: Default::default(),
137 alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
141 pub fn new_empty(source_map: &'sess SourceMap) -> Self {
143 serialized_data: Vec::new(),
144 file_index_to_stable_id: Default::default(),
145 file_index_to_file: Default::default(),
147 cnum_map: Once::new(),
149 current_diagnostics: Default::default(),
150 query_result_index: Default::default(),
151 prev_diagnostics_index: Default::default(),
152 synthetic_syntax_contexts: Default::default(),
153 alloc_decoding_state: AllocDecodingState::new(Vec::new()),
157 pub fn serialize<'tcx, E>(&self, tcx: TyCtxt<'tcx>, encoder: &mut E) -> Result<(), E::Error>
161 // Serializing the `DepGraph` should not modify it.
162 tcx.dep_graph.with_ignore(|| {
163 // Allocate `SourceFileIndex`es.
164 let (file_to_file_index, file_index_to_stable_id) = {
165 let files = tcx.sess.source_map().files();
166 let mut file_to_file_index =
167 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
168 let mut file_index_to_stable_id =
169 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
171 for (index, file) in files.iter().enumerate() {
172 let index = SourceFileIndex(index as u32);
173 let file_ptr: *const SourceFile = &**file as *const _;
174 file_to_file_index.insert(file_ptr, index);
175 file_index_to_stable_id.insert(index, StableSourceFileId::new(&file));
178 (file_to_file_index, file_index_to_stable_id)
181 let mut encoder = CacheEncoder {
184 type_shorthands: Default::default(),
185 predicate_shorthands: Default::default(),
186 expn_data_shorthands: Default::default(),
187 interpret_allocs: Default::default(),
188 interpret_allocs_inverse: Vec::new(),
189 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
193 // Load everything into memory so we can write it out to the on-disk
194 // cache. The vast majority of cacheable query results should already
195 // be in memory, so this should be a cheap operation.
196 tcx.dep_graph.exec_cache_promotions(tcx);
198 // Encode query results.
199 let mut query_result_index = EncodedQueryResultIndex::new();
201 tcx.sess.time("encode_query_results", || {
202 let enc = &mut encoder;
203 let qri = &mut query_result_index;
205 macro_rules! encode_queries {
206 ($($query:ident,)*) => {
208 encode_query_results::<ty::query::queries::$query<'_>, _>(
217 rustc_cached_queries!(encode_queries!);
222 // Encode diagnostics.
223 let diagnostics_index: EncodedDiagnosticsIndex = self
227 .map(|(dep_node_index, diagnostics)| {
228 let pos = AbsoluteBytePos::new(encoder.position());
229 // Let's make sure we get the expected type here.
230 let diagnostics: &EncodedDiagnostics = diagnostics;
231 let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
232 encoder.encode_tagged(dep_node_index, diagnostics)?;
234 Ok((dep_node_index, pos))
236 .collect::<Result<_, _>>()?;
238 let interpret_alloc_index = {
239 let mut interpret_alloc_index = Vec::new();
242 let new_n = encoder.interpret_allocs_inverse.len();
243 // If we have found new IDs, serialize those too.
248 interpret_alloc_index.reserve(new_n - n);
249 for idx in n..new_n {
250 let id = encoder.interpret_allocs_inverse[idx];
251 let pos = encoder.position() as u32;
252 interpret_alloc_index.push(pos);
253 interpret::specialized_encode_alloc_id(&mut encoder, tcx, id)?;
257 interpret_alloc_index
260 let sorted_cnums = sorted_cnums_including_local_crate(tcx);
261 let prev_cnums: Vec<_> = sorted_cnums
264 let crate_name = tcx.original_crate_name(cnum).to_string();
265 let crate_disambiguator = tcx.crate_disambiguator(cnum);
266 (cnum.as_u32(), crate_name, crate_disambiguator)
270 // Encode the file footer.
271 let footer_pos = encoder.position() as u64;
272 encoder.encode_tagged(
275 file_index_to_stable_id,
279 interpret_alloc_index,
283 // Encode the position of the footer as the last 8 bytes of the
284 // file so we know where to look for it.
285 IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder)?;
287 // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
288 // of the footer must be the last thing in the data stream.
292 fn sorted_cnums_including_local_crate(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
293 let mut cnums = vec![LOCAL_CRATE];
294 cnums.extend_from_slice(&tcx.crates()[..]);
295 cnums.sort_unstable();
296 // Just to be sure...
303 /// Loads a diagnostic emitted during the previous compilation session.
304 pub fn load_diagnostics(
307 dep_node_index: SerializedDepNodeIndex,
308 ) -> Vec<Diagnostic> {
309 let diagnostics: Option<EncodedDiagnostics> =
310 self.load_indexed(tcx, dep_node_index, &self.prev_diagnostics_index, "diagnostics");
312 diagnostics.unwrap_or_default()
315 /// Stores a diagnostic emitted during the current compilation session.
316 /// Anything stored like this will be available via `load_diagnostics` in
317 /// the next compilation session.
320 pub fn store_diagnostics(
322 dep_node_index: DepNodeIndex,
323 diagnostics: ThinVec<Diagnostic>,
325 let mut current_diagnostics = self.current_diagnostics.borrow_mut();
326 let prev = current_diagnostics.insert(dep_node_index, diagnostics.into());
327 debug_assert!(prev.is_none());
330 /// Returns the cached query result if there is something in the cache for
331 /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
332 pub fn try_load_query_result<T>(
335 dep_node_index: SerializedDepNodeIndex,
340 self.load_indexed(tcx, dep_node_index, &self.query_result_index, "query result")
343 /// Stores a diagnostic emitted during computation of an anonymous query.
344 /// Since many anonymous queries can share the same `DepNode`, we aggregate
345 /// them -- as opposed to regular queries where we assume that there is a
346 /// 1:1 relationship between query-key and `DepNode`.
349 pub fn store_diagnostics_for_anon_node(
351 dep_node_index: DepNodeIndex,
352 diagnostics: ThinVec<Diagnostic>,
354 let mut current_diagnostics = self.current_diagnostics.borrow_mut();
356 let x = current_diagnostics.entry(dep_node_index).or_insert(Vec::new());
358 x.extend(Into::<Vec<_>>::into(diagnostics));
361 fn load_indexed<'tcx, T>(
364 dep_node_index: SerializedDepNodeIndex,
365 index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
366 debug_tag: &'static str,
371 let pos = index.get(&dep_node_index).cloned()?;
373 // Initialize `cnum_map` using the value from the thread that finishes the closure first.
374 self.cnum_map.init_nonlocking_same(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
376 let mut decoder = CacheDecoder {
378 opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()),
379 source_map: self.source_map,
380 cnum_map: self.cnum_map.get(),
381 synthetic_syntax_contexts: &self.synthetic_syntax_contexts,
382 file_index_to_file: &self.file_index_to_file,
383 file_index_to_stable_id: &self.file_index_to_stable_id,
384 alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
387 match decode_tagged(&mut decoder, dep_node_index) {
389 Err(e) => bug!("could not decode cached {}: {}", debug_tag, e),
393 // This function builds mapping from previous-session-`CrateNum` to
394 // current-session-`CrateNum`. There might be `CrateNum`s from the previous
395 // `Session` that don't occur in the current one. For these, the mapping
399 prev_cnums: &[(u32, String, CrateDisambiguator)],
400 ) -> IndexVec<CrateNum, Option<CrateNum>> {
401 tcx.dep_graph.with_ignore(|| {
402 let current_cnums = tcx
403 .all_crate_nums(LOCAL_CRATE)
406 let crate_name = tcx.original_crate_name(cnum).to_string();
407 let crate_disambiguator = tcx.crate_disambiguator(cnum);
408 ((crate_name, crate_disambiguator), cnum)
410 .collect::<FxHashMap<_, _>>();
412 let map_size = prev_cnums.iter().map(|&(cnum, ..)| cnum).max().unwrap_or(0) + 1;
413 let mut map = IndexVec::from_elem_n(None, map_size as usize);
415 for &(prev_cnum, ref crate_name, crate_disambiguator) in prev_cnums {
416 let key = (crate_name.clone(), crate_disambiguator);
417 map[CrateNum::from_u32(prev_cnum)] = current_cnums.get(&key).cloned();
420 map[LOCAL_CRATE] = Some(LOCAL_CRATE);
426 //- DECODING -------------------------------------------------------------------
428 /// A decoder that can read fro the incr. comp. cache. It is similar to the one
429 /// we use for crate metadata decoding in that it can rebase spans and eventually
430 /// will also handle things that contain `Ty` instances.
431 struct CacheDecoder<'a, 'tcx> {
433 opaque: opaque::Decoder<'a>,
434 source_map: &'a SourceMap,
435 cnum_map: &'a IndexVec<CrateNum, Option<CrateNum>>,
436 synthetic_syntax_contexts: &'a Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
437 file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
438 file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, StableSourceFileId>,
439 alloc_decoding_session: AllocDecodingSession<'a>,
442 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
443 fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
445 ref file_index_to_file,
446 ref file_index_to_stable_id,
455 let stable_id = file_index_to_stable_id[&index];
457 .source_file_by_stable_id(stable_id)
458 .expect("failed to lookup `SourceFile` in new context")
464 trait DecoderWithPosition: Decoder {
465 fn position(&self) -> usize;
468 impl<'a> DecoderWithPosition for opaque::Decoder<'a> {
469 fn position(&self) -> usize {
474 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
475 fn position(&self) -> usize {
476 self.opaque.position()
480 // Decodes something that was encoded with `encode_tagged()` and verify that the
481 // tag matches and the correct amount of bytes was read.
482 fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> Result<V, D::Error>
484 T: Decodable + Eq + ::std::fmt::Debug,
486 D: DecoderWithPosition,
488 let start_pos = decoder.position();
490 let actual_tag = T::decode(decoder)?;
491 assert_eq!(actual_tag, expected_tag);
492 let value = V::decode(decoder)?;
493 let end_pos = decoder.position();
495 let expected_len: u64 = Decodable::decode(decoder)?;
496 assert_eq!((end_pos - start_pos) as u64, expected_len);
501 impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
503 fn tcx(&self) -> TyCtxt<'tcx> {
508 fn position(&self) -> usize {
509 self.opaque.position()
513 fn peek_byte(&self) -> u8 {
514 self.opaque.data[self.opaque.position()]
517 fn cached_ty_for_shorthand<F>(
521 ) -> Result<Ty<'tcx>, Self::Error>
523 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
525 let tcx = self.tcx();
528 ty::CReaderCacheKey { cnum: CrateNum::ReservedForIncrCompCache, pos: shorthand };
530 if let Some(&ty) = tcx.rcache.borrow().get(&cache_key) {
534 let ty = or_insert_with(self)?;
535 // This may overwrite the entry, but it should overwrite with the same value.
536 tcx.rcache.borrow_mut().insert_same(cache_key, ty);
540 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
542 F: FnOnce(&mut Self) -> R,
544 debug_assert!(pos < self.opaque.data.len());
546 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
547 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
549 self.opaque = old_opaque;
553 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
554 self.cnum_map[cnum].unwrap_or_else(|| bug!("could not find new `CrateNum` for {:?}", cnum))
558 implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
560 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for CacheDecoder<'a, 'tcx> {
561 fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
562 let alloc_decoding_session = self.alloc_decoding_session;
563 alloc_decoding_session.decode_alloc_id(self)
567 impl<'a, 'tcx> SpecializedDecoder<Span> for CacheDecoder<'a, 'tcx> {
568 fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
569 let tag: u8 = Decodable::decode(self)?;
571 if tag == TAG_INVALID_SPAN {
574 debug_assert_eq!(tag, TAG_VALID_SPAN);
577 let file_lo_index = SourceFileIndex::decode(self)?;
578 let line_lo = usize::decode(self)?;
579 let col_lo = BytePos::decode(self)?;
580 let len = BytePos::decode(self)?;
582 let file_lo = self.file_index_to_file(file_lo_index);
583 let lo = file_lo.lines[line_lo - 1] + col_lo;
586 let expn_data_tag = u8::decode(self)?;
588 // FIXME(mw): This method does not restore `ExpnData::parent` or
589 // `SyntaxContextData::prev_ctxt` or `SyntaxContextData::opaque`. These things
590 // don't seem to be used after HIR lowering, so everything should be fine
591 // until we want incremental compilation to serialize Spans that we need
592 // full hygiene information for.
593 let location = || Span::with_root_ctxt(lo, hi);
594 let recover_from_expn_data = |this: &Self, expn_data, transparency, pos| {
595 let span = location().fresh_expansion_with_transparency(expn_data, transparency);
596 this.synthetic_syntax_contexts.borrow_mut().insert(pos, span.ctxt());
599 Ok(match expn_data_tag {
600 TAG_NO_EXPN_DATA => location(),
601 TAG_EXPN_DATA_INLINE => {
602 let (expn_data, transparency) = Decodable::decode(self)?;
603 recover_from_expn_data(
607 AbsoluteBytePos::new(self.opaque.position()),
610 TAG_EXPN_DATA_SHORTHAND => {
611 let pos = AbsoluteBytePos::decode(self)?;
612 let cached_ctxt = self.synthetic_syntax_contexts.borrow().get(&pos).cloned();
613 if let Some(ctxt) = cached_ctxt {
614 Span::new(lo, hi, ctxt)
616 let (expn_data, transparency) =
617 self.with_position(pos.to_usize(), |this| Decodable::decode(this))?;
618 recover_from_expn_data(self, expn_data, transparency, pos)
626 impl<'a, 'tcx> SpecializedDecoder<Ident> for CacheDecoder<'a, 'tcx> {
627 fn specialized_decode(&mut self) -> Result<Ident, Self::Error> {
628 // FIXME: Handle hygiene in incremental
629 bug!("Trying to decode Ident for incremental");
633 // This impl makes sure that we get a runtime error when we try decode a
634 // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
635 // because we would not know how to transform the `DefIndex` to the current
637 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for CacheDecoder<'a, 'tcx> {
638 fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
639 bug!("trying to decode `DefIndex` outside the context of a `DefId`")
643 // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
644 // compilation sessions. We use the `DefPathHash`, which is stable across
645 // sessions, to map the old `DefId` to the new one.
646 impl<'a, 'tcx> SpecializedDecoder<DefId> for CacheDecoder<'a, 'tcx> {
648 fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
649 // Load the `DefPathHash` which is was we encoded the `DefId` as.
650 let def_path_hash = DefPathHash::decode(self)?;
652 // Using the `DefPathHash`, we can lookup the new `DefId`.
653 Ok(self.tcx().def_path_hash_to_def_id.as_ref().unwrap()[&def_path_hash])
657 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for CacheDecoder<'a, 'tcx> {
659 fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
660 Ok(LocalDefId::from_def_id(DefId::decode(self)?))
664 impl<'a, 'tcx> SpecializedDecoder<hir::HirId> for CacheDecoder<'a, 'tcx> {
665 fn specialized_decode(&mut self) -> Result<hir::HirId, Self::Error> {
666 // Load the `DefPathHash` which is what we encoded the `DefIndex` as.
667 let def_path_hash = DefPathHash::decode(self)?;
669 // Use the `DefPathHash` to map to the current `DefId`.
670 let def_id = self.tcx().def_path_hash_to_def_id.as_ref().unwrap()[&def_path_hash];
672 debug_assert!(def_id.is_local());
674 // The `ItemLocalId` needs no remapping.
675 let local_id = hir::ItemLocalId::decode(self)?;
677 // Reconstruct the `HirId` and look up the corresponding `NodeId` in the
678 // context of the current session.
679 Ok(hir::HirId { owner: def_id.index, local_id })
683 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for CacheDecoder<'a, 'tcx> {
684 fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
685 Fingerprint::decode_opaque(&mut self.opaque)
689 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
690 for CacheDecoder<'a, 'tcx>
693 fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
694 let discr = u8::decode(self)?;
697 TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(mir::ClearCrossCrate::Clear),
698 TAG_CLEAR_CROSS_CRATE_SET => {
699 let val = T::decode(self)?;
700 Ok(mir::ClearCrossCrate::Set(val))
707 //- ENCODING -------------------------------------------------------------------
709 /// An encoder that can write the incr. comp. cache.
710 struct CacheEncoder<'a, 'tcx, E: ty_codec::TyEncoder> {
713 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
714 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
715 expn_data_shorthands: FxHashMap<ExpnId, AbsoluteBytePos>,
716 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
717 interpret_allocs_inverse: Vec<interpret::AllocId>,
718 source_map: CachingSourceMapView<'tcx>,
719 file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
722 impl<'a, 'tcx, E> CacheEncoder<'a, 'tcx, E>
726 fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
727 self.file_to_file_index[&(&*source_file as *const SourceFile)]
730 /// Encode something with additional information that allows to do some
731 /// sanity checks when decoding the data again. This method will first
732 /// encode the specified tag, then the given value, then the number of
733 /// bytes taken up by tag and value. On decoding, we can then verify that
734 /// we get the expected tag and read the expected number of bytes.
735 fn encode_tagged<T: Encodable, V: Encodable>(
739 ) -> Result<(), E::Error> {
740 let start_pos = self.position();
745 let end_pos = self.position();
746 ((end_pos - start_pos) as u64).encode(self)
750 impl<'a, 'tcx, E> SpecializedEncoder<interpret::AllocId> for CacheEncoder<'a, 'tcx, E>
754 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
755 use std::collections::hash_map::Entry;
756 let index = match self.interpret_allocs.entry(*alloc_id) {
757 Entry::Occupied(e) => *e.get(),
758 Entry::Vacant(e) => {
759 let idx = self.interpret_allocs_inverse.len();
760 self.interpret_allocs_inverse.push(*alloc_id);
770 impl<'a, 'tcx, E> SpecializedEncoder<Span> for CacheEncoder<'a, 'tcx, E>
774 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
775 if *span == DUMMY_SP {
776 return TAG_INVALID_SPAN.encode(self);
779 let span_data = span.data();
780 let (file_lo, line_lo, col_lo) =
781 match self.source_map.byte_pos_to_line_and_col(span_data.lo) {
783 None => return TAG_INVALID_SPAN.encode(self),
786 if !file_lo.contains(span_data.hi) {
787 return TAG_INVALID_SPAN.encode(self);
790 let len = span_data.hi - span_data.lo;
792 let source_file_index = self.source_file_index(file_lo);
794 TAG_VALID_SPAN.encode(self)?;
795 source_file_index.encode(self)?;
796 line_lo.encode(self)?;
797 col_lo.encode(self)?;
800 if span_data.ctxt == SyntaxContext::root() {
801 TAG_NO_EXPN_DATA.encode(self)
803 let (expn_id, transparency, expn_data) = span_data.ctxt.outer_mark_with_data();
804 if let Some(pos) = self.expn_data_shorthands.get(&expn_id).cloned() {
805 TAG_EXPN_DATA_SHORTHAND.encode(self)?;
808 TAG_EXPN_DATA_INLINE.encode(self)?;
809 let pos = AbsoluteBytePos::new(self.position());
810 self.expn_data_shorthands.insert(expn_id, pos);
811 (expn_data, transparency).encode(self)
817 impl<'a, 'tcx, E> SpecializedEncoder<Ident> for CacheEncoder<'a, 'tcx, E>
819 E: 'a + ty_codec::TyEncoder,
821 fn specialized_encode(&mut self, _: &Ident) -> Result<(), Self::Error> {
822 // We don't currently encode enough information to ensure hygiene works
823 // with incremental, so panic rather than risk incremental bugs.
825 // FIXME: handle hygiene in incremental.
826 bug!("trying to encode `Ident` for incremental");
830 impl<'a, 'tcx, E> ty_codec::TyEncoder for CacheEncoder<'a, 'tcx, E>
835 fn position(&self) -> usize {
836 self.encoder.position()
840 impl<'a, 'tcx, E> SpecializedEncoder<CrateNum> for CacheEncoder<'a, 'tcx, E>
845 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
846 self.emit_u32(cnum.as_u32())
850 impl<'a, 'tcx, E> SpecializedEncoder<Ty<'tcx>> for CacheEncoder<'a, 'tcx, E>
855 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
856 ty_codec::encode_with_shorthand(self, ty, |encoder| &mut encoder.type_shorthands)
860 impl<'a, 'tcx, E> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]>
861 for CacheEncoder<'a, 'tcx, E>
866 fn specialized_encode(
868 predicates: &&'tcx [(ty::Predicate<'tcx>, Span)],
869 ) -> Result<(), Self::Error> {
870 ty_codec::encode_spanned_predicates(self, predicates, |encoder| {
871 &mut encoder.predicate_shorthands
876 impl<'a, 'tcx, E> SpecializedEncoder<hir::HirId> for CacheEncoder<'a, 'tcx, E>
881 fn specialized_encode(&mut self, id: &hir::HirId) -> Result<(), Self::Error> {
882 let hir::HirId { owner, local_id } = *id;
884 let def_path_hash = self.tcx.hir().definitions().def_path_hash(owner);
886 def_path_hash.encode(self)?;
887 local_id.encode(self)
891 impl<'a, 'tcx, E> SpecializedEncoder<DefId> for CacheEncoder<'a, 'tcx, E>
896 fn specialized_encode(&mut self, id: &DefId) -> Result<(), Self::Error> {
897 let def_path_hash = self.tcx.def_path_hash(*id);
898 def_path_hash.encode(self)
902 impl<'a, 'tcx, E> SpecializedEncoder<LocalDefId> for CacheEncoder<'a, 'tcx, E>
907 fn specialized_encode(&mut self, id: &LocalDefId) -> Result<(), Self::Error> {
908 id.to_def_id().encode(self)
912 impl<'a, 'tcx, E> SpecializedEncoder<DefIndex> for CacheEncoder<'a, 'tcx, E>
916 fn specialized_encode(&mut self, _: &DefIndex) -> Result<(), Self::Error> {
917 bug!("encoding `DefIndex` without context");
921 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for CacheEncoder<'a, 'tcx, opaque::Encoder> {
922 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
923 f.encode_opaque(&mut self.encoder)
927 impl<'a, 'tcx, E, T> SpecializedEncoder<mir::ClearCrossCrate<T>> for CacheEncoder<'a, 'tcx, E>
933 fn specialized_encode(&mut self, val: &mir::ClearCrossCrate<T>) -> Result<(), Self::Error> {
935 mir::ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(self),
936 mir::ClearCrossCrate::Set(ref val) => {
937 TAG_CLEAR_CROSS_CRATE_SET.encode(self)?;
944 macro_rules! encoder_methods {
945 ($($name:ident($ty:ty);)*) => {
947 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
948 self.encoder.$name(value)
953 impl<'a, 'tcx, E> Encoder for CacheEncoder<'a, 'tcx, E>
957 type Error = E::Error;
959 fn emit_unit(&mut self) -> Result<(), Self::Error> {
986 // An integer that will always encode to 8 bytes.
987 struct IntEncodedWithFixedSize(u64);
989 impl IntEncodedWithFixedSize {
990 pub const ENCODED_SIZE: usize = 8;
993 impl UseSpecializedEncodable for IntEncodedWithFixedSize {}
994 impl UseSpecializedDecodable for IntEncodedWithFixedSize {}
996 impl SpecializedEncoder<IntEncodedWithFixedSize> for opaque::Encoder {
997 fn specialized_encode(&mut self, x: &IntEncodedWithFixedSize) -> Result<(), Self::Error> {
998 let start_pos = self.position();
999 for i in 0..IntEncodedWithFixedSize::ENCODED_SIZE {
1000 ((x.0 >> (i * 8)) as u8).encode(self)?;
1002 let end_pos = self.position();
1003 assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1008 impl<'a> SpecializedDecoder<IntEncodedWithFixedSize> for opaque::Decoder<'a> {
1009 fn specialized_decode(&mut self) -> Result<IntEncodedWithFixedSize, Self::Error> {
1010 let mut value: u64 = 0;
1011 let start_pos = self.position();
1013 for i in 0..IntEncodedWithFixedSize::ENCODED_SIZE {
1014 let byte: u8 = Decodable::decode(self)?;
1015 value |= (byte as u64) << (i * 8);
1018 let end_pos = self.position();
1019 assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1021 Ok(IntEncodedWithFixedSize(value))
1025 fn encode_query_results<'a, 'tcx, Q, E>(
1027 encoder: &mut CacheEncoder<'a, 'tcx, E>,
1028 query_result_index: &mut EncodedQueryResultIndex,
1029 ) -> Result<(), E::Error>
1031 Q: super::config::QueryDescription<'tcx, Value: Encodable>,
1037 .extra_verbose_generic_activity("encode_query_results_for", ::std::any::type_name::<Q>());
1039 let state = Q::query_state(tcx);
1040 assert!(state.all_inactive());
1042 state.iter_results(|results| {
1043 for (key, value, dep_node) in results {
1044 if Q::cache_on_disk(tcx, key.clone(), Some(&value)) {
1045 let dep_node = SerializedDepNodeIndex::new(dep_node.index());
1047 // Record position of the cache entry.
1048 query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.position())));
1050 // Encode the type check tables with the `SerializedDepNodeIndex`
1052 encoder.encode_tagged(dep_node, &value)?;