]> git.lizzy.rs Git - rust.git/blob - src/librustc_middle/ty/query/on_disk_cache.rs
Rework `rustc_serialize`
[rust.git] / src / librustc_middle / ty / query / on_disk_cache.rs
1 use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
2 use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState};
3 use crate::mir::{self, interpret};
4 use crate::ty::codec::{OpaqueEncoder, RefDecodable, TyDecoder, TyEncoder};
5 use crate::ty::context::TyCtxt;
6 use crate::ty::{self, Ty};
7 use rustc_data_structures::fingerprint::{Fingerprint, FingerprintDecoder, FingerprintEncoder};
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
9 use rustc_data_structures::sync::{HashMapExt, Lock, Lrc, OnceCell};
10 use rustc_data_structures::thin_vec::ThinVec;
11 use rustc_errors::Diagnostic;
12 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, LOCAL_CRATE};
13 use rustc_hir::definitions::DefPathHash;
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder};
16 use rustc_session::{CrateDisambiguator, Session};
17 use rustc_span::hygiene::{
18     ExpnDataDecodeMode, ExpnDataEncodeMode, ExpnId, HygieneDecodeContext, HygieneEncodeContext,
19     SyntaxContext, SyntaxContextData,
20 };
21 use rustc_span::source_map::{SourceMap, StableSourceFileId};
22 use rustc_span::CachingSourceMapView;
23 use rustc_span::{BytePos, ExpnData, SourceFile, Span, DUMMY_SP};
24 use std::mem;
25
26 const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
27
28 const TAG_VALID_SPAN: u8 = 0;
29 const TAG_INVALID_SPAN: u8 = 1;
30
31 const TAG_SYNTAX_CONTEXT: u8 = 0;
32 const TAG_EXPN_DATA: u8 = 1;
33
34 /// Provides an interface to incremental compilation data cached from the
35 /// previous compilation session. This data will eventually include the results
36 /// of a few selected queries (like `typeck` and `mir_optimized`) and
37 /// any diagnostics that have been emitted during a query.
38 pub struct OnDiskCache<'sess> {
39     // The complete cache data in serialized form.
40     serialized_data: Vec<u8>,
41
42     // Collects all `Diagnostic`s emitted during the current compilation
43     // session.
44     current_diagnostics: Lock<FxHashMap<DepNodeIndex, Vec<Diagnostic>>>,
45
46     prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
47     cnum_map: OnceCell<IndexVec<CrateNum, Option<CrateNum>>>,
48
49     source_map: &'sess SourceMap,
50     file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
51
52     // Caches that are populated lazily during decoding.
53     file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
54
55     // A map from dep-node to the position of the cached query result in
56     // `serialized_data`.
57     query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
58
59     // A map from dep-node to the position of any associated diagnostics in
60     // `serialized_data`.
61     prev_diagnostics_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
62
63     alloc_decoding_state: AllocDecodingState,
64
65     // A map from syntax context ids to the position of their associated
66     // `SyntaxContextData`. We use a `u32` instead of a `SyntaxContext`
67     // to represent the fact that we are storing *encoded* ids. When we decode
68     // a `SyntaxContext`, a new id will be allocated from the global `HygieneData`,
69     // which will almost certainly be different than the serialized id.
70     syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
71     // A map from the `DefPathHash` of an `ExpnId` to the position
72     // of their associated `ExpnData`. Ideally, we would store a `DefId`,
73     // but we need to decode this before we've constructed a `TyCtxt` (which
74     // makes it difficult to decode a `DefId`).
75
76     // Note that these `DefPathHashes` correspond to both local and foreign
77     // `ExpnData` (e.g `ExpnData.krate` may not be `LOCAL_CRATE`). Alternatively,
78     // we could look up the `ExpnData` from the metadata of foreign crates,
79     // but it seemed easier to have `OnDiskCache` be independent of the `CStore`.
80     expn_data: FxHashMap<u32, AbsoluteBytePos>,
81     // Additional information used when decoding hygiene data.
82     hygiene_context: HygieneDecodeContext,
83 }
84
85 // This type is used only for serialization and deserialization.
86 #[derive(Encodable, Decodable)]
87 struct Footer {
88     file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
89     prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
90     query_result_index: EncodedQueryResultIndex,
91     diagnostics_index: EncodedQueryResultIndex,
92     // The location of all allocations.
93     interpret_alloc_index: Vec<u32>,
94     // See `OnDiskCache.syntax_contexts`
95     syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
96     // See `OnDiskCache.expn_data`
97     expn_data: FxHashMap<u32, AbsoluteBytePos>,
98 }
99
100 type EncodedQueryResultIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
101 type EncodedDiagnosticsIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
102 type EncodedDiagnostics = Vec<Diagnostic>;
103
104 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
105 struct SourceFileIndex(u32);
106
107 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Encodable, Decodable)]
108 struct AbsoluteBytePos(u32);
109
110 impl AbsoluteBytePos {
111     fn new(pos: usize) -> AbsoluteBytePos {
112         debug_assert!(pos <= u32::MAX as usize);
113         AbsoluteBytePos(pos as u32)
114     }
115
116     fn to_usize(self) -> usize {
117         self.0 as usize
118     }
119 }
120
121 impl<'sess> OnDiskCache<'sess> {
122     /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
123     pub fn new(sess: &'sess Session, data: Vec<u8>, start_pos: usize) -> Self {
124         debug_assert!(sess.opts.incremental.is_some());
125
126         // Wrap in a scope so we can borrow `data`.
127         let footer: Footer = {
128             let mut decoder = opaque::Decoder::new(&data[..], start_pos);
129
130             // Decode the *position* of the footer, which can be found in the
131             // last 8 bytes of the file.
132             decoder.set_position(data.len() - IntEncodedWithFixedSize::ENCODED_SIZE);
133             let footer_pos = IntEncodedWithFixedSize::decode(&mut decoder)
134                 .expect("error while trying to decode footer position")
135                 .0 as usize;
136
137             // Decode the file footer, which contains all the lookup tables, etc.
138             decoder.set_position(footer_pos);
139
140             decode_tagged(&mut decoder, TAG_FILE_FOOTER)
141                 .expect("error while trying to decode footer position")
142         };
143
144         Self {
145             serialized_data: data,
146             file_index_to_stable_id: footer.file_index_to_stable_id,
147             file_index_to_file: Default::default(),
148             prev_cnums: footer.prev_cnums,
149             cnum_map: OnceCell::new(),
150             source_map: sess.source_map(),
151             current_diagnostics: Default::default(),
152             query_result_index: footer.query_result_index.into_iter().collect(),
153             prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
154             alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
155             syntax_contexts: footer.syntax_contexts,
156             expn_data: footer.expn_data,
157             hygiene_context: Default::default(),
158         }
159     }
160
161     pub fn new_empty(source_map: &'sess SourceMap) -> Self {
162         Self {
163             serialized_data: Vec::new(),
164             file_index_to_stable_id: Default::default(),
165             file_index_to_file: Default::default(),
166             prev_cnums: vec![],
167             cnum_map: OnceCell::new(),
168             source_map,
169             current_diagnostics: Default::default(),
170             query_result_index: Default::default(),
171             prev_diagnostics_index: Default::default(),
172             alloc_decoding_state: AllocDecodingState::new(Vec::new()),
173             syntax_contexts: FxHashMap::default(),
174             expn_data: FxHashMap::default(),
175             hygiene_context: Default::default(),
176         }
177     }
178
179     pub fn serialize<'tcx, E>(&self, tcx: TyCtxt<'tcx>, encoder: &mut E) -> Result<(), E::Error>
180     where
181         E: OpaqueEncoder,
182     {
183         // Serializing the `DepGraph` should not modify it.
184         tcx.dep_graph.with_ignore(|| {
185             // Allocate `SourceFileIndex`es.
186             let (file_to_file_index, file_index_to_stable_id) = {
187                 let files = tcx.sess.source_map().files();
188                 let mut file_to_file_index =
189                     FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
190                 let mut file_index_to_stable_id =
191                     FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
192
193                 for (index, file) in files.iter().enumerate() {
194                     let index = SourceFileIndex(index as u32);
195                     let file_ptr: *const SourceFile = &**file as *const _;
196                     file_to_file_index.insert(file_ptr, index);
197                     file_index_to_stable_id.insert(index, StableSourceFileId::new(&file));
198                 }
199
200                 (file_to_file_index, file_index_to_stable_id)
201             };
202
203             let hygiene_encode_context = HygieneEncodeContext::default();
204
205             let mut encoder = CacheEncoder {
206                 tcx,
207                 encoder,
208                 type_shorthands: Default::default(),
209                 predicate_shorthands: Default::default(),
210                 interpret_allocs: Default::default(),
211                 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
212                 file_to_file_index,
213                 hygiene_context: &hygiene_encode_context,
214             };
215
216             // Load everything into memory so we can write it out to the on-disk
217             // cache. The vast majority of cacheable query results should already
218             // be in memory, so this should be a cheap operation.
219             tcx.dep_graph.exec_cache_promotions(tcx);
220
221             // Encode query results.
222             let mut query_result_index = EncodedQueryResultIndex::new();
223
224             tcx.sess.time("encode_query_results", || {
225                 let enc = &mut encoder;
226                 let qri = &mut query_result_index;
227
228                 macro_rules! encode_queries {
229                     ($($query:ident,)*) => {
230                         $(
231                             encode_query_results::<ty::query::queries::$query<'_>, _>(
232                                 tcx,
233                                 enc,
234                                 qri
235                             )?;
236                         )*
237                     }
238                 }
239
240                 rustc_cached_queries!(encode_queries!);
241
242                 Ok(())
243             })?;
244
245             // Encode diagnostics.
246             let diagnostics_index: EncodedDiagnosticsIndex = self
247                 .current_diagnostics
248                 .borrow()
249                 .iter()
250                 .map(|(dep_node_index, diagnostics)| {
251                     let pos = AbsoluteBytePos::new(encoder.position());
252                     // Let's make sure we get the expected type here.
253                     let diagnostics: &EncodedDiagnostics = diagnostics;
254                     let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
255                     encoder.encode_tagged(dep_node_index, diagnostics)?;
256
257                     Ok((dep_node_index, pos))
258                 })
259                 .collect::<Result<_, _>>()?;
260
261             let interpret_alloc_index = {
262                 let mut interpret_alloc_index = Vec::new();
263                 let mut n = 0;
264                 loop {
265                     let new_n = encoder.interpret_allocs.len();
266                     // If we have found new IDs, serialize those too.
267                     if n == new_n {
268                         // Otherwise, abort.
269                         break;
270                     }
271                     interpret_alloc_index.reserve(new_n - n);
272                     for idx in n..new_n {
273                         let id = encoder.interpret_allocs[idx];
274                         let pos = encoder.position() as u32;
275                         interpret_alloc_index.push(pos);
276                         interpret::specialized_encode_alloc_id(&mut encoder, tcx, id)?;
277                     }
278                     n = new_n;
279                 }
280                 interpret_alloc_index
281             };
282
283             let sorted_cnums = sorted_cnums_including_local_crate(tcx);
284             let prev_cnums: Vec<_> = sorted_cnums
285                 .iter()
286                 .map(|&cnum| {
287                     let crate_name = tcx.original_crate_name(cnum).to_string();
288                     let crate_disambiguator = tcx.crate_disambiguator(cnum);
289                     (cnum.as_u32(), crate_name, crate_disambiguator)
290                 })
291                 .collect();
292
293             let mut syntax_contexts = FxHashMap::default();
294             let mut expn_ids = FxHashMap::default();
295
296             // Encode all hygiene data (`SyntaxContextData` and `ExpnData`) from the current
297             // session.
298
299             hygiene_encode_context.encode(
300                 &mut encoder,
301                 |encoder, index, ctxt_data| {
302                     let pos = AbsoluteBytePos::new(encoder.position());
303                     encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data)?;
304                     syntax_contexts.insert(index, pos);
305                     Ok(())
306                 },
307                 |encoder, index, expn_data| {
308                     let pos = AbsoluteBytePos::new(encoder.position());
309                     encoder.encode_tagged(TAG_EXPN_DATA, expn_data)?;
310                     expn_ids.insert(index, pos);
311                     Ok(())
312                 },
313             )?;
314
315             // `Encode the file footer.
316             let footer_pos = encoder.position() as u64;
317             encoder.encode_tagged(
318                 TAG_FILE_FOOTER,
319                 &Footer {
320                     file_index_to_stable_id,
321                     prev_cnums,
322                     query_result_index,
323                     diagnostics_index,
324                     interpret_alloc_index,
325                     syntax_contexts,
326                     expn_data: expn_ids,
327                 },
328             )?;
329
330             // Encode the position of the footer as the last 8 bytes of the
331             // file so we know where to look for it.
332             IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder.opaque())?;
333
334             // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
335             // of the footer must be the last thing in the data stream.
336
337             return Ok(());
338
339             fn sorted_cnums_including_local_crate(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
340                 let mut cnums = vec![LOCAL_CRATE];
341                 cnums.extend_from_slice(&tcx.crates()[..]);
342                 cnums.sort_unstable();
343                 // Just to be sure...
344                 cnums.dedup();
345                 cnums
346             }
347         })
348     }
349
350     /// Loads a diagnostic emitted during the previous compilation session.
351     pub fn load_diagnostics(
352         &self,
353         tcx: TyCtxt<'_>,
354         dep_node_index: SerializedDepNodeIndex,
355     ) -> Vec<Diagnostic> {
356         let diagnostics: Option<EncodedDiagnostics> =
357             self.load_indexed(tcx, dep_node_index, &self.prev_diagnostics_index, "diagnostics");
358
359         diagnostics.unwrap_or_default()
360     }
361
362     /// Stores a diagnostic emitted during the current compilation session.
363     /// Anything stored like this will be available via `load_diagnostics` in
364     /// the next compilation session.
365     #[inline(never)]
366     #[cold]
367     pub fn store_diagnostics(
368         &self,
369         dep_node_index: DepNodeIndex,
370         diagnostics: ThinVec<Diagnostic>,
371     ) {
372         let mut current_diagnostics = self.current_diagnostics.borrow_mut();
373         let prev = current_diagnostics.insert(dep_node_index, diagnostics.into());
374         debug_assert!(prev.is_none());
375     }
376
377     /// Returns the cached query result if there is something in the cache for
378     /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
379     crate fn try_load_query_result<'tcx, T>(
380         &self,
381         tcx: TyCtxt<'tcx>,
382         dep_node_index: SerializedDepNodeIndex,
383     ) -> Option<T>
384     where
385         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
386     {
387         self.load_indexed(tcx, dep_node_index, &self.query_result_index, "query result")
388     }
389
390     /// Stores a diagnostic emitted during computation of an anonymous query.
391     /// Since many anonymous queries can share the same `DepNode`, we aggregate
392     /// them -- as opposed to regular queries where we assume that there is a
393     /// 1:1 relationship between query-key and `DepNode`.
394     #[inline(never)]
395     #[cold]
396     pub fn store_diagnostics_for_anon_node(
397         &self,
398         dep_node_index: DepNodeIndex,
399         diagnostics: ThinVec<Diagnostic>,
400     ) {
401         let mut current_diagnostics = self.current_diagnostics.borrow_mut();
402
403         let x = current_diagnostics.entry(dep_node_index).or_insert(Vec::new());
404
405         x.extend(Into::<Vec<_>>::into(diagnostics));
406     }
407
408     fn load_indexed<'tcx, T>(
409         &self,
410         tcx: TyCtxt<'tcx>,
411         dep_node_index: SerializedDepNodeIndex,
412         index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
413         debug_tag: &'static str,
414     ) -> Option<T>
415     where
416         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
417     {
418         let pos = index.get(&dep_node_index).cloned()?;
419
420         self.with_decoder(tcx, pos, |decoder| match decode_tagged(decoder, dep_node_index) {
421             Ok(v) => Some(v),
422             Err(e) => bug!("could not decode cached {}: {}", debug_tag, e),
423         })
424     }
425
426     fn with_decoder<'a, 'tcx, T, F: FnOnce(&mut CacheDecoder<'sess, 'tcx>) -> T>(
427         &'sess self,
428         tcx: TyCtxt<'tcx>,
429         pos: AbsoluteBytePos,
430         f: F,
431     ) -> T
432     where
433         T: Decodable<CacheDecoder<'a, 'tcx>>,
434     {
435         let cnum_map =
436             self.cnum_map.get_or_init(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
437
438         let mut decoder = CacheDecoder {
439             tcx,
440             opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()),
441             source_map: self.source_map,
442             cnum_map,
443             file_index_to_file: &self.file_index_to_file,
444             file_index_to_stable_id: &self.file_index_to_stable_id,
445             alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
446             syntax_contexts: &self.syntax_contexts,
447             expn_data: &self.expn_data,
448             hygiene_context: &self.hygiene_context,
449         };
450         f(&mut decoder)
451     }
452
453     // This function builds mapping from previous-session-`CrateNum` to
454     // current-session-`CrateNum`. There might be `CrateNum`s from the previous
455     // `Session` that don't occur in the current one. For these, the mapping
456     // maps to None.
457     fn compute_cnum_map(
458         tcx: TyCtxt<'_>,
459         prev_cnums: &[(u32, String, CrateDisambiguator)],
460     ) -> IndexVec<CrateNum, Option<CrateNum>> {
461         tcx.dep_graph.with_ignore(|| {
462             let current_cnums = tcx
463                 .all_crate_nums(LOCAL_CRATE)
464                 .iter()
465                 .map(|&cnum| {
466                     let crate_name = tcx.original_crate_name(cnum).to_string();
467                     let crate_disambiguator = tcx.crate_disambiguator(cnum);
468                     ((crate_name, crate_disambiguator), cnum)
469                 })
470                 .collect::<FxHashMap<_, _>>();
471
472             let map_size = prev_cnums.iter().map(|&(cnum, ..)| cnum).max().unwrap_or(0) + 1;
473             let mut map = IndexVec::from_elem_n(None, map_size as usize);
474
475             for &(prev_cnum, ref crate_name, crate_disambiguator) in prev_cnums {
476                 let key = (crate_name.clone(), crate_disambiguator);
477                 map[CrateNum::from_u32(prev_cnum)] = current_cnums.get(&key).cloned();
478             }
479
480             map[LOCAL_CRATE] = Some(LOCAL_CRATE);
481             map
482         })
483     }
484 }
485
486 //- DECODING -------------------------------------------------------------------
487
488 /// A decoder that can read from the incr. comp. cache. It is similar to the one
489 /// we use for crate metadata decoding in that it can rebase spans and eventually
490 /// will also handle things that contain `Ty` instances.
491 crate struct CacheDecoder<'a, 'tcx> {
492     tcx: TyCtxt<'tcx>,
493     opaque: opaque::Decoder<'a>,
494     source_map: &'a SourceMap,
495     cnum_map: &'a IndexVec<CrateNum, Option<CrateNum>>,
496     file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
497     file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, StableSourceFileId>,
498     alloc_decoding_session: AllocDecodingSession<'a>,
499     syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
500     expn_data: &'a FxHashMap<u32, AbsoluteBytePos>,
501     hygiene_context: &'a HygieneDecodeContext,
502 }
503
504 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
505     fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
506         let CacheDecoder {
507             ref file_index_to_file,
508             ref file_index_to_stable_id,
509             ref source_map,
510             ..
511         } = *self;
512
513         file_index_to_file
514             .borrow_mut()
515             .entry(index)
516             .or_insert_with(|| {
517                 let stable_id = file_index_to_stable_id[&index];
518                 source_map
519                     .source_file_by_stable_id(stable_id)
520                     .expect("failed to lookup `SourceFile` in new context")
521             })
522             .clone()
523     }
524 }
525
526 trait DecoderWithPosition: Decoder {
527     fn position(&self) -> usize;
528 }
529
530 impl<'a> DecoderWithPosition for opaque::Decoder<'a> {
531     fn position(&self) -> usize {
532         self.position()
533     }
534 }
535
536 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
537     fn position(&self) -> usize {
538         self.opaque.position()
539     }
540 }
541
542 // Decodes something that was encoded with `encode_tagged()` and verify that the
543 // tag matches and the correct amount of bytes was read.
544 fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> Result<V, D::Error>
545 where
546     T: Decodable<D> + Eq + ::std::fmt::Debug,
547     V: Decodable<D>,
548     D: DecoderWithPosition,
549 {
550     let start_pos = decoder.position();
551
552     let actual_tag = T::decode(decoder)?;
553     assert_eq!(actual_tag, expected_tag);
554     let value = V::decode(decoder)?;
555     let end_pos = decoder.position();
556
557     let expected_len: u64 = Decodable::decode(decoder)?;
558     assert_eq!((end_pos - start_pos) as u64, expected_len);
559
560     Ok(value)
561 }
562
563 impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
564     const CLEAR_CROSS_CRATE: bool = false;
565
566     #[inline]
567     fn tcx(&self) -> TyCtxt<'tcx> {
568         self.tcx
569     }
570
571     #[inline]
572     fn position(&self) -> usize {
573         self.opaque.position()
574     }
575
576     #[inline]
577     fn peek_byte(&self) -> u8 {
578         self.opaque.data[self.opaque.position()]
579     }
580
581     fn cached_ty_for_shorthand<F>(
582         &mut self,
583         shorthand: usize,
584         or_insert_with: F,
585     ) -> Result<Ty<'tcx>, Self::Error>
586     where
587         F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
588     {
589         let tcx = self.tcx();
590
591         let cache_key =
592             ty::CReaderCacheKey { cnum: CrateNum::ReservedForIncrCompCache, pos: shorthand };
593
594         if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
595             return Ok(ty);
596         }
597
598         let ty = or_insert_with(self)?;
599         // This may overwrite the entry, but it should overwrite with the same value.
600         tcx.ty_rcache.borrow_mut().insert_same(cache_key, ty);
601         Ok(ty)
602     }
603
604     fn cached_predicate_for_shorthand<F>(
605         &mut self,
606         shorthand: usize,
607         or_insert_with: F,
608     ) -> Result<ty::Predicate<'tcx>, Self::Error>
609     where
610         F: FnOnce(&mut Self) -> Result<ty::Predicate<'tcx>, Self::Error>,
611     {
612         let tcx = self.tcx();
613
614         let cache_key =
615             ty::CReaderCacheKey { cnum: CrateNum::ReservedForIncrCompCache, pos: shorthand };
616
617         if let Some(&pred) = tcx.pred_rcache.borrow().get(&cache_key) {
618             return Ok(pred);
619         }
620
621         let pred = or_insert_with(self)?;
622         // This may overwrite the entry, but it should overwrite with the same value.
623         tcx.pred_rcache.borrow_mut().insert_same(cache_key, pred);
624         Ok(pred)
625     }
626
627     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
628     where
629         F: FnOnce(&mut Self) -> R,
630     {
631         debug_assert!(pos < self.opaque.data.len());
632
633         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
634         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
635         let r = f(self);
636         self.opaque = old_opaque;
637         r
638     }
639
640     fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
641         self.cnum_map[cnum].unwrap_or_else(|| bug!("could not find new `CrateNum` for {:?}", cnum))
642     }
643
644     fn decode_alloc_id(&mut self) -> Result<interpret::AllocId, Self::Error> {
645         let alloc_decoding_session = self.alloc_decoding_session;
646         alloc_decoding_session.decode_alloc_id(self)
647     }
648 }
649
650 crate::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
651
652 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for SyntaxContext {
653     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
654         let syntax_contexts = decoder.syntax_contexts;
655         rustc_span::hygiene::decode_syntax_context(decoder, decoder.hygiene_context, |this, id| {
656             // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
657             // We look up the position of the associated `SyntaxData` and decode it.
658             let pos = syntax_contexts.get(&id).unwrap();
659             this.with_position(pos.to_usize(), |decoder| {
660                 let data: SyntaxContextData = decode_tagged(decoder, TAG_SYNTAX_CONTEXT)?;
661                 Ok(data)
662             })
663         })
664     }
665 }
666
667 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for ExpnId {
668     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
669         let expn_data = decoder.expn_data;
670         rustc_span::hygiene::decode_expn_id(
671             decoder,
672             ExpnDataDecodeMode::incr_comp(decoder.hygiene_context),
673             |this, index| {
674                 // This closure is invoked if we haven't already decoded the data for the `ExpnId` we are deserializing.
675                 // We look up the position of the associated `ExpnData` and decode it.
676                 let pos = expn_data
677                     .get(&index)
678                     .unwrap_or_else(|| panic!("Bad index {:?} (map {:?})", index, expn_data));
679
680                 this.with_position(pos.to_usize(), |decoder| {
681                     let data: ExpnData = decode_tagged(decoder, TAG_EXPN_DATA)?;
682                     Ok(data)
683                 })
684             },
685         )
686     }
687 }
688
689 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Span {
690     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
691         let tag: u8 = Decodable::decode(decoder)?;
692
693         if tag == TAG_INVALID_SPAN {
694             return Ok(DUMMY_SP);
695         } else {
696             debug_assert_eq!(tag, TAG_VALID_SPAN);
697         }
698
699         let file_lo_index = SourceFileIndex::decode(decoder)?;
700         let line_lo = usize::decode(decoder)?;
701         let col_lo = BytePos::decode(decoder)?;
702         let len = BytePos::decode(decoder)?;
703         let ctxt = SyntaxContext::decode(decoder)?;
704
705         let file_lo = decoder.file_index_to_file(file_lo_index);
706         let lo = file_lo.lines[line_lo - 1] + col_lo;
707         let hi = lo + len;
708
709         Ok(Span::new(lo, hi, ctxt))
710     }
711 }
712
713 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for CrateNum {
714     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
715         let cnum = CrateNum::from_u32(u32::decode(d)?);
716         Ok(d.map_encoded_cnum_to_current(cnum))
717     }
718 }
719
720 // This impl makes sure that we get a runtime error when we try decode a
721 // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
722 // because we would not know how to transform the `DefIndex` to the current
723 // context.
724 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefIndex {
725     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<DefIndex, String> {
726         Err(d.error("trying to decode `DefIndex` outside the context of a `DefId`"))
727     }
728 }
729
730 // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
731 // compilation sessions. We use the `DefPathHash`, which is stable across
732 // sessions, to map the old `DefId` to the new one.
733 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefId {
734     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
735         // Load the `DefPathHash` which is was we encoded the `DefId` as.
736         let def_path_hash = DefPathHash::decode(d)?;
737
738         // Using the `DefPathHash`, we can lookup the new `DefId`.
739         Ok(d.tcx().def_path_hash_to_def_id.as_ref().unwrap()[&def_path_hash])
740     }
741 }
742
743 impl<'a, 'tcx> FingerprintDecoder for CacheDecoder<'a, 'tcx> {
744     fn decode_fingerprint(&mut self) -> Result<Fingerprint, Self::Error> {
745         Fingerprint::decode_opaque(&mut self.opaque)
746     }
747 }
748
749 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx FxHashSet<LocalDefId> {
750     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
751         RefDecodable::decode(d)
752     }
753 }
754
755 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
756     for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
757 {
758     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
759         RefDecodable::decode(d)
760     }
761 }
762
763 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
764     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
765         RefDecodable::decode(d)
766     }
767 }
768
769 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
770     for &'tcx [rustc_ast::ast::InlineAsmTemplatePiece]
771 {
772     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
773         RefDecodable::decode(d)
774     }
775 }
776
777 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Span] {
778     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
779         RefDecodable::decode(d)
780     }
781 }
782
783 //- ENCODING -------------------------------------------------------------------
784
785 /// An encoder that can write the incr. comp. cache.
786 struct CacheEncoder<'a, 'tcx, E: OpaqueEncoder> {
787     tcx: TyCtxt<'tcx>,
788     encoder: &'a mut E,
789     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
790     predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
791     interpret_allocs: FxIndexSet<interpret::AllocId>,
792     source_map: CachingSourceMapView<'tcx>,
793     file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
794     hygiene_context: &'a HygieneEncodeContext,
795 }
796
797 impl<'a, 'tcx, E> CacheEncoder<'a, 'tcx, E>
798 where
799     E: 'a + OpaqueEncoder,
800 {
801     fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
802         self.file_to_file_index[&(&*source_file as *const SourceFile)]
803     }
804
805     /// Encode something with additional information that allows to do some
806     /// sanity checks when decoding the data again. This method will first
807     /// encode the specified tag, then the given value, then the number of
808     /// bytes taken up by tag and value. On decoding, we can then verify that
809     /// we get the expected tag and read the expected number of bytes.
810     fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(
811         &mut self,
812         tag: T,
813         value: &V,
814     ) -> Result<(), E::Error> {
815         let start_pos = self.position();
816
817         tag.encode(self)?;
818         value.encode(self)?;
819
820         let end_pos = self.position();
821         ((end_pos - start_pos) as u64).encode(self)
822     }
823 }
824
825 impl<'a, 'tcx> FingerprintEncoder for CacheEncoder<'a, 'tcx, rustc_serialize::opaque::Encoder> {
826     fn encode_fingerprint(&mut self, f: &Fingerprint) -> opaque::EncodeResult {
827         f.encode_opaque(self.encoder)
828     }
829 }
830
831 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for SyntaxContext
832 where
833     E: 'a + OpaqueEncoder,
834 {
835     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
836         rustc_span::hygiene::raw_encode_syntax_context(*self, s.hygiene_context, s)
837     }
838 }
839
840 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for ExpnId
841 where
842     E: 'a + OpaqueEncoder,
843 {
844     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
845         rustc_span::hygiene::raw_encode_expn_id(
846             *self,
847             s.hygiene_context,
848             ExpnDataEncodeMode::IncrComp,
849             s,
850         )
851     }
852 }
853
854 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for Span
855 where
856     E: 'a + OpaqueEncoder,
857 {
858     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
859         if *self == DUMMY_SP {
860             return TAG_INVALID_SPAN.encode(s);
861         }
862
863         let span_data = self.data();
864         let (file_lo, line_lo, col_lo) = match s.source_map.byte_pos_to_line_and_col(span_data.lo) {
865             Some(pos) => pos,
866             None => return TAG_INVALID_SPAN.encode(s),
867         };
868
869         if !file_lo.contains(span_data.hi) {
870             return TAG_INVALID_SPAN.encode(s);
871         }
872
873         let len = span_data.hi - span_data.lo;
874
875         let source_file_index = s.source_file_index(file_lo);
876
877         TAG_VALID_SPAN.encode(s)?;
878         source_file_index.encode(s)?;
879         line_lo.encode(s)?;
880         col_lo.encode(s)?;
881         len.encode(s)?;
882         span_data.ctxt.encode(s)
883     }
884 }
885
886 impl<'a, 'tcx, E> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx, E>
887 where
888     E: 'a + OpaqueEncoder,
889 {
890     const CLEAR_CROSS_CRATE: bool = false;
891
892     fn tcx(&self) -> TyCtxt<'tcx> {
893         self.tcx
894     }
895     fn position(&self) -> usize {
896         self.encoder.encoder_position()
897     }
898     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
899         &mut self.type_shorthands
900     }
901     fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::Predicate<'tcx>, usize> {
902         &mut self.predicate_shorthands
903     }
904     fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
905         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
906
907         index.encode(self)
908     }
909 }
910
911 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefId
912 where
913     E: 'a + OpaqueEncoder,
914 {
915     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
916         let def_path_hash = s.tcx.def_path_hash(*self);
917         def_path_hash.encode(s)
918     }
919 }
920
921 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefIndex
922 where
923     E: 'a + OpaqueEncoder,
924 {
925     fn encode(&self, _: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
926         bug!("encoding `DefIndex` without context");
927     }
928 }
929
930 macro_rules! encoder_methods {
931     ($($name:ident($ty:ty);)*) => {
932         #[inline]
933         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
934             self.encoder.$name(value)
935         })*
936     }
937 }
938
939 impl<'a, 'tcx, E> Encoder for CacheEncoder<'a, 'tcx, E>
940 where
941     E: 'a + OpaqueEncoder,
942 {
943     type Error = E::Error;
944
945     #[inline]
946     fn emit_unit(&mut self) -> Result<(), Self::Error> {
947         Ok(())
948     }
949
950     encoder_methods! {
951         emit_usize(usize);
952         emit_u128(u128);
953         emit_u64(u64);
954         emit_u32(u32);
955         emit_u16(u16);
956         emit_u8(u8);
957
958         emit_isize(isize);
959         emit_i128(i128);
960         emit_i64(i64);
961         emit_i32(i32);
962         emit_i16(i16);
963         emit_i8(i8);
964
965         emit_bool(bool);
966         emit_f64(f64);
967         emit_f32(f32);
968         emit_char(char);
969         emit_str(&str);
970     }
971 }
972
973 // An integer that will always encode to 8 bytes.
974 struct IntEncodedWithFixedSize(u64);
975
976 impl IntEncodedWithFixedSize {
977     pub const ENCODED_SIZE: usize = 8;
978 }
979
980 impl Encodable<opaque::Encoder> for IntEncodedWithFixedSize {
981     fn encode(&self, e: &mut opaque::Encoder) -> Result<(), !> {
982         let start_pos = e.position();
983         for i in 0..IntEncodedWithFixedSize::ENCODED_SIZE {
984             ((self.0 >> (i * 8)) as u8).encode(e)?;
985         }
986         let end_pos = e.position();
987         assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
988         Ok(())
989     }
990 }
991
992 impl<'a> Decodable<opaque::Decoder<'a>> for IntEncodedWithFixedSize {
993     fn decode(decoder: &mut opaque::Decoder<'a>) -> Result<IntEncodedWithFixedSize, String> {
994         let mut value: u64 = 0;
995         let start_pos = decoder.position();
996
997         for i in 0..IntEncodedWithFixedSize::ENCODED_SIZE {
998             let byte: u8 = Decodable::decode(decoder)?;
999             value |= (byte as u64) << (i * 8);
1000         }
1001
1002         let end_pos = decoder.position();
1003         assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1004
1005         Ok(IntEncodedWithFixedSize(value))
1006     }
1007 }
1008
1009 fn encode_query_results<'a, 'tcx, Q, E>(
1010     tcx: TyCtxt<'tcx>,
1011     encoder: &mut CacheEncoder<'a, 'tcx, E>,
1012     query_result_index: &mut EncodedQueryResultIndex,
1013 ) -> Result<(), E::Error>
1014 where
1015     Q: super::QueryDescription<TyCtxt<'tcx>> + super::QueryAccessors<TyCtxt<'tcx>>,
1016     Q::Value: Encodable<CacheEncoder<'a, 'tcx, E>>,
1017     E: 'a + OpaqueEncoder,
1018 {
1019     let _timer = tcx
1020         .sess
1021         .prof
1022         .extra_verbose_generic_activity("encode_query_results_for", ::std::any::type_name::<Q>());
1023
1024     let state = Q::query_state(tcx);
1025     assert!(state.all_inactive());
1026
1027     state.iter_results(|results| {
1028         for (key, value, dep_node) in results {
1029             if Q::cache_on_disk(tcx, &key, Some(value)) {
1030                 let dep_node = SerializedDepNodeIndex::new(dep_node.index());
1031
1032                 // Record position of the cache entry.
1033                 query_result_index
1034                     .push((dep_node, AbsoluteBytePos::new(encoder.encoder.opaque().position())));
1035
1036                 // Encode the type check tables with the `SerializedDepNodeIndex`
1037                 // as tag.
1038                 encoder.encode_tagged(dep_node, value)?;
1039             }
1040         }
1041         Ok(())
1042     })
1043 }