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