]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_query_impl/src/on_disk_cache.rs
Rollup merge of #92242 - compiler-errors:layout-modulo-regions, r=matthewjasper
[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::thir;
13 use rustc_middle::ty::codec::{RefDecodable, TyDecoder, TyEncoder};
14 use rustc_middle::ty::{self, Ty, TyCtxt};
15 use rustc_query_system::dep_graph::DepContext;
16 use rustc_query_system::query::{QueryContext, QuerySideEffects};
17 use rustc_serialize::{
18     opaque::{self, FileEncodeResult, FileEncoder, IntEncodedWithFixedSize},
19     Decodable, Decoder, Encodable, Encoder,
20 };
21 use rustc_session::Session;
22 use rustc_span::hygiene::{
23     ExpnId, HygieneDecodeContext, HygieneEncodeContext, SyntaxContext, SyntaxContextData,
24 };
25 use rustc_span::source_map::{SourceMap, StableSourceFileId};
26 use rustc_span::CachingSourceMapView;
27 use rustc_span::{BytePos, ExpnData, ExpnHash, Pos, SourceFile, Span};
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 = opaque::Decoder::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: &mut 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", || -> FileEncodeResult {
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(
274                     |(dep_node_index, side_effects)| -> Result<_, <FileEncoder as Encoder>::Error> {
275                         let pos = AbsoluteBytePos::new(encoder.position());
276                         let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
277                         encoder.encode_tagged(dep_node_index, side_effects)?;
278
279                         Ok((dep_node_index, pos))
280                     },
281                 )
282                 .collect::<Result<_, _>>()?;
283
284             let interpret_alloc_index = {
285                 let mut interpret_alloc_index = Vec::new();
286                 let mut n = 0;
287                 loop {
288                     let new_n = encoder.interpret_allocs.len();
289                     // If we have found new IDs, serialize those too.
290                     if n == new_n {
291                         // Otherwise, abort.
292                         break;
293                     }
294                     interpret_alloc_index.reserve(new_n - n);
295                     for idx in n..new_n {
296                         let id = encoder.interpret_allocs[idx];
297                         let pos = encoder.position() as u32;
298                         interpret_alloc_index.push(pos);
299                         interpret::specialized_encode_alloc_id(&mut encoder, tcx, id)?;
300                     }
301                     n = new_n;
302                 }
303                 interpret_alloc_index
304             };
305
306             let mut syntax_contexts = FxHashMap::default();
307             let mut expn_data = UnhashMap::default();
308             let mut foreign_expn_data = UnhashMap::default();
309
310             // Encode all hygiene data (`SyntaxContextData` and `ExpnData`) from the current
311             // session.
312
313             hygiene_encode_context.encode(
314                 &mut encoder,
315                 |encoder, index, ctxt_data| -> FileEncodeResult {
316                     let pos = AbsoluteBytePos::new(encoder.position());
317                     encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data)?;
318                     syntax_contexts.insert(index, pos);
319                     Ok(())
320                 },
321                 |encoder, expn_id, data, hash| -> FileEncodeResult {
322                     if expn_id.krate == LOCAL_CRATE {
323                         let pos = AbsoluteBytePos::new(encoder.position());
324                         encoder.encode_tagged(TAG_EXPN_DATA, data)?;
325                         expn_data.insert(hash, pos);
326                     } else {
327                         foreign_expn_data.insert(hash, expn_id.local_id.as_u32());
328                     }
329                     Ok(())
330                 },
331             )?;
332
333             // `Encode the file footer.
334             let footer_pos = encoder.position() as u64;
335             encoder.encode_tagged(
336                 TAG_FILE_FOOTER,
337                 &Footer {
338                     file_index_to_stable_id,
339                     query_result_index,
340                     side_effects_index,
341                     interpret_alloc_index,
342                     syntax_contexts,
343                     expn_data,
344                     foreign_expn_data,
345                 },
346             )?;
347
348             // Encode the position of the footer as the last 8 bytes of the
349             // file so we know where to look for it.
350             IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder)?;
351
352             // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
353             // of the footer must be the last thing in the data stream.
354
355             Ok(())
356         })
357     }
358 }
359
360 impl<'sess> OnDiskCache<'sess> {
361     pub fn as_dyn(&self) -> &dyn rustc_middle::ty::OnDiskCache<'sess> {
362         self as _
363     }
364
365     /// Loads a `QuerySideEffects` created during the previous compilation session.
366     pub fn load_side_effects(
367         &self,
368         tcx: TyCtxt<'_>,
369         dep_node_index: SerializedDepNodeIndex,
370     ) -> QuerySideEffects {
371         let side_effects: Option<QuerySideEffects> =
372             self.load_indexed(tcx, dep_node_index, &self.prev_side_effects_index);
373
374         side_effects.unwrap_or_default()
375     }
376
377     /// Stores a `QuerySideEffects` emitted during the current compilation session.
378     /// Anything stored like this will be available via `load_side_effects` in
379     /// the next compilation session.
380     #[inline(never)]
381     #[cold]
382     pub fn store_side_effects(&self, dep_node_index: DepNodeIndex, side_effects: QuerySideEffects) {
383         let mut current_side_effects = self.current_side_effects.borrow_mut();
384         let prev = current_side_effects.insert(dep_node_index, side_effects);
385         debug_assert!(prev.is_none());
386     }
387
388     /// Returns the cached query result if there is something in the cache for
389     /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
390     pub fn try_load_query_result<'tcx, T>(
391         &self,
392         tcx: TyCtxt<'tcx>,
393         dep_node_index: SerializedDepNodeIndex,
394     ) -> Option<T>
395     where
396         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
397     {
398         self.load_indexed(tcx, dep_node_index, &self.query_result_index)
399     }
400
401     /// Stores side effect emitted during computation of an anonymous query.
402     /// Since many anonymous queries can share the same `DepNode`, we aggregate
403     /// them -- as opposed to regular queries where we assume that there is a
404     /// 1:1 relationship between query-key and `DepNode`.
405     #[inline(never)]
406     #[cold]
407     pub fn store_side_effects_for_anon_node(
408         &self,
409         dep_node_index: DepNodeIndex,
410         side_effects: QuerySideEffects,
411     ) {
412         let mut current_side_effects = self.current_side_effects.borrow_mut();
413
414         let x = current_side_effects.entry(dep_node_index).or_default();
415         x.append(side_effects);
416     }
417
418     fn load_indexed<'tcx, T>(
419         &self,
420         tcx: TyCtxt<'tcx>,
421         dep_node_index: SerializedDepNodeIndex,
422         index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
423     ) -> Option<T>
424     where
425         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
426     {
427         let pos = index.get(&dep_node_index).cloned()?;
428
429         self.with_decoder(tcx, pos, |decoder| Some(decode_tagged(decoder, dep_node_index)))
430     }
431
432     fn with_decoder<'a, 'tcx, T, F: for<'s> FnOnce(&mut CacheDecoder<'s, 'tcx>) -> T>(
433         &'sess self,
434         tcx: TyCtxt<'tcx>,
435         pos: AbsoluteBytePos,
436         f: F,
437     ) -> T
438     where
439         T: Decodable<CacheDecoder<'a, 'tcx>>,
440     {
441         let serialized_data = self.serialized_data.read();
442         let mut decoder = CacheDecoder {
443             tcx,
444             opaque: opaque::Decoder::new(serialized_data.as_deref().unwrap_or(&[]), pos.to_usize()),
445             source_map: self.source_map,
446             file_index_to_file: &self.file_index_to_file,
447             file_index_to_stable_id: &self.file_index_to_stable_id,
448             alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
449             syntax_contexts: &self.syntax_contexts,
450             expn_data: &self.expn_data,
451             foreign_expn_data: &self.foreign_expn_data,
452             hygiene_context: &self.hygiene_context,
453         };
454         f(&mut decoder)
455     }
456 }
457
458 //- DECODING -------------------------------------------------------------------
459
460 /// A decoder that can read from the incremental compilation cache. It is similar to the one
461 /// we use for crate metadata decoding in that it can rebase spans and eventually
462 /// will also handle things that contain `Ty` instances.
463 pub struct CacheDecoder<'a, 'tcx> {
464     tcx: TyCtxt<'tcx>,
465     opaque: opaque::Decoder<'a>,
466     source_map: &'a SourceMap,
467     file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
468     file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, EncodedSourceFileId>,
469     alloc_decoding_session: AllocDecodingSession<'a>,
470     syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
471     expn_data: &'a UnhashMap<ExpnHash, AbsoluteBytePos>,
472     foreign_expn_data: &'a UnhashMap<ExpnHash, u32>,
473     hygiene_context: &'a HygieneDecodeContext,
474 }
475
476 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
477     fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
478         let CacheDecoder {
479             tcx,
480             ref file_index_to_file,
481             ref file_index_to_stable_id,
482             ref source_map,
483             ..
484         } = *self;
485
486         file_index_to_file
487             .borrow_mut()
488             .entry(index)
489             .or_insert_with(|| {
490                 let stable_id = file_index_to_stable_id[&index].translate(tcx);
491
492                 // If this `SourceFile` is from a foreign crate, then make sure
493                 // that we've imported all of the source files from that crate.
494                 // This has usually already been done during macro invocation.
495                 // However, when encoding query results like `TypeckResults`,
496                 // we might encode an `AdtDef` for a foreign type (because it
497                 // was referenced in the body of the function). There is no guarantee
498                 // that we will load the source files from that crate during macro
499                 // expansion, so we use `import_source_files` to ensure that the foreign
500                 // source files are actually imported before we call `source_file_by_stable_id`.
501                 if stable_id.cnum != LOCAL_CRATE {
502                     self.tcx.cstore_untracked().import_source_files(self.tcx.sess, stable_id.cnum);
503                 }
504
505                 source_map
506                     .source_file_by_stable_id(stable_id)
507                     .expect("failed to lookup `SourceFile` in new context")
508             })
509             .clone()
510     }
511 }
512
513 trait DecoderWithPosition: Decoder {
514     fn position(&self) -> usize;
515 }
516
517 impl<'a> DecoderWithPosition for opaque::Decoder<'a> {
518     fn position(&self) -> usize {
519         self.position()
520     }
521 }
522
523 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
524     fn position(&self) -> usize {
525         self.opaque.position()
526     }
527 }
528
529 // Decodes something that was encoded with `encode_tagged()` and verify that the
530 // tag matches and the correct amount of bytes was read.
531 fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> V
532 where
533     T: Decodable<D> + Eq + std::fmt::Debug,
534     V: Decodable<D>,
535     D: DecoderWithPosition,
536 {
537     let start_pos = decoder.position();
538
539     let actual_tag = T::decode(decoder);
540     assert_eq!(actual_tag, expected_tag);
541     let value = V::decode(decoder);
542     let end_pos = decoder.position();
543
544     let expected_len: u64 = Decodable::decode(decoder);
545     assert_eq!((end_pos - start_pos) as u64, expected_len);
546
547     value
548 }
549
550 impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
551     const CLEAR_CROSS_CRATE: bool = false;
552
553     #[inline]
554     fn tcx(&self) -> TyCtxt<'tcx> {
555         self.tcx
556     }
557
558     #[inline]
559     fn position(&self) -> usize {
560         self.opaque.position()
561     }
562
563     #[inline]
564     fn peek_byte(&self) -> u8 {
565         self.opaque.data[self.opaque.position()]
566     }
567
568     fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
569     where
570         F: FnOnce(&mut Self) -> Ty<'tcx>,
571     {
572         let tcx = self.tcx();
573
574         let cache_key = ty::CReaderCacheKey { cnum: None, pos: shorthand };
575
576         if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
577             return ty;
578         }
579
580         let ty = or_insert_with(self);
581         // This may overwrite the entry, but it should overwrite with the same value.
582         tcx.ty_rcache.borrow_mut().insert_same(cache_key, ty);
583         ty
584     }
585
586     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
587     where
588         F: FnOnce(&mut Self) -> R,
589     {
590         debug_assert!(pos < self.opaque.data.len());
591
592         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
593         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
594         let r = f(self);
595         self.opaque = old_opaque;
596         r
597     }
598
599     fn decode_alloc_id(&mut self) -> interpret::AllocId {
600         let alloc_decoding_session = self.alloc_decoding_session;
601         alloc_decoding_session.decode_alloc_id(self)
602     }
603 }
604
605 rustc_middle::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
606
607 // This ensures that the `Decodable<opaque::Decoder>::decode` specialization for `Vec<u8>` is used
608 // when a `CacheDecoder` is passed to `Decodable::decode`. Unfortunately, we have to manually opt
609 // into specializations this way, given how `CacheDecoder` and the decoding traits currently work.
610 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Vec<u8> {
611     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
612         Decodable::decode(&mut d.opaque)
613     }
614 }
615
616 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for SyntaxContext {
617     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Self {
618         let syntax_contexts = decoder.syntax_contexts;
619         rustc_span::hygiene::decode_syntax_context(decoder, decoder.hygiene_context, |this, id| {
620             // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
621             // We look up the position of the associated `SyntaxData` and decode it.
622             let pos = syntax_contexts.get(&id).unwrap();
623             this.with_position(pos.to_usize(), |decoder| {
624                 let data: SyntaxContextData = decode_tagged(decoder, TAG_SYNTAX_CONTEXT);
625                 data
626             })
627         })
628     }
629 }
630
631 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for ExpnId {
632     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Self {
633         let hash = ExpnHash::decode(decoder);
634         if hash.is_root() {
635             return ExpnId::root();
636         }
637
638         if let Some(expn_id) = ExpnId::from_hash(hash) {
639             return expn_id;
640         }
641
642         let krate = decoder.tcx.stable_crate_id_to_crate_num(hash.stable_crate_id());
643
644         let expn_id = if krate == LOCAL_CRATE {
645             // We look up the position of the associated `ExpnData` and decode it.
646             let pos = decoder
647                 .expn_data
648                 .get(&hash)
649                 .unwrap_or_else(|| panic!("Bad hash {:?} (map {:?})", hash, decoder.expn_data));
650
651             let data: ExpnData = decoder
652                 .with_position(pos.to_usize(), |decoder| decode_tagged(decoder, TAG_EXPN_DATA));
653             let expn_id = rustc_span::hygiene::register_local_expn_id(data, hash);
654
655             #[cfg(debug_assertions)]
656             {
657                 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
658                 let mut hcx = decoder.tcx.create_stable_hashing_context();
659                 let mut hasher = StableHasher::new();
660                 hcx.while_hashing_spans(true, |hcx| {
661                     expn_id.expn_data().hash_stable(hcx, &mut hasher)
662                 });
663                 let local_hash: u64 = hasher.finish();
664                 debug_assert_eq!(hash.local_hash(), local_hash);
665             }
666
667             expn_id
668         } else {
669             let index_guess = decoder.foreign_expn_data[&hash];
670             decoder.tcx.cstore_untracked().expn_hash_to_expn_id(
671                 decoder.tcx.sess,
672                 krate,
673                 index_guess,
674                 hash,
675             )
676         };
677
678         debug_assert_eq!(expn_id.krate, krate);
679         expn_id
680     }
681 }
682
683 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Span {
684     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Self {
685         let ctxt = SyntaxContext::decode(decoder);
686         let parent = Option::<LocalDefId>::decode(decoder);
687         let tag: u8 = Decodable::decode(decoder);
688
689         if tag == TAG_PARTIAL_SPAN {
690             return Span::new(BytePos(0), BytePos(0), ctxt, parent);
691         } else if tag == TAG_RELATIVE_SPAN {
692             let dlo = u32::decode(decoder);
693             let dto = u32::decode(decoder);
694
695             let enclosing =
696                 decoder.tcx.definitions_untracked().def_span(parent.unwrap()).data_untracked();
697             let span = Span::new(
698                 enclosing.lo + BytePos::from_u32(dlo),
699                 enclosing.lo + BytePos::from_u32(dto),
700                 ctxt,
701                 parent,
702             );
703
704             return span;
705         } else {
706             debug_assert_eq!(tag, TAG_FULL_SPAN);
707         }
708
709         let file_lo_index = SourceFileIndex::decode(decoder);
710         let line_lo = usize::decode(decoder);
711         let col_lo = BytePos::decode(decoder);
712         let len = BytePos::decode(decoder);
713
714         let file_lo = decoder.file_index_to_file(file_lo_index);
715         let lo = file_lo.lines[line_lo - 1] + col_lo;
716         let hi = lo + len;
717
718         Span::new(lo, hi, ctxt, parent)
719     }
720 }
721
722 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for CrateNum {
723     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
724         let stable_id = StableCrateId::decode(d);
725         let cnum = d.tcx.stable_crate_id_to_crate_num(stable_id);
726         cnum
727     }
728 }
729
730 // This impl makes sure that we get a runtime error when we try decode a
731 // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
732 // because we would not know how to transform the `DefIndex` to the current
733 // context.
734 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefIndex {
735     fn decode(_d: &mut CacheDecoder<'a, 'tcx>) -> DefIndex {
736         panic!("trying to decode `DefIndex` outside the context of a `DefId`")
737     }
738 }
739
740 // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
741 // compilation sessions. We use the `DefPathHash`, which is stable across
742 // sessions, to map the old `DefId` to the new one.
743 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefId {
744     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
745         // Load the `DefPathHash` which is was we encoded the `DefId` as.
746         let def_path_hash = DefPathHash::decode(d);
747
748         // Using the `DefPathHash`, we can lookup the new `DefId`.
749         // Subtle: We only encode a `DefId` as part of a query result.
750         // If we get to this point, then all of the query inputs were green,
751         // which means that the definition with this hash is guaranteed to
752         // still exist in the current compilation session.
753         d.tcx().def_path_hash_to_def_id(def_path_hash, &mut || {
754             panic!("Failed to convert DefPathHash {:?}", def_path_hash)
755         })
756     }
757 }
758
759 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx FxHashSet<LocalDefId> {
760     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
761         RefDecodable::decode(d)
762     }
763 }
764
765 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
766     for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
767 {
768     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
769         RefDecodable::decode(d)
770     }
771 }
772
773 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [thir::abstract_const::Node<'tcx>] {
774     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
775         RefDecodable::decode(d)
776     }
777 }
778
779 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
780     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
781         RefDecodable::decode(d)
782     }
783 }
784
785 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_ast::InlineAsmTemplatePiece] {
786     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
787         RefDecodable::decode(d)
788     }
789 }
790
791 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Span] {
792     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
793         RefDecodable::decode(d)
794     }
795 }
796
797 //- ENCODING -------------------------------------------------------------------
798
799 pub trait OpaqueEncoder: Encoder {
800     fn position(&self) -> usize;
801 }
802
803 impl OpaqueEncoder for FileEncoder {
804     #[inline]
805     fn position(&self) -> usize {
806         FileEncoder::position(self)
807     }
808 }
809
810 /// An encoder that can write to the incremental compilation cache.
811 pub struct CacheEncoder<'a, 'tcx, E: OpaqueEncoder> {
812     tcx: TyCtxt<'tcx>,
813     encoder: &'a mut E,
814     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
815     predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
816     interpret_allocs: FxIndexSet<interpret::AllocId>,
817     source_map: CachingSourceMapView<'tcx>,
818     file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
819     hygiene_context: &'a HygieneEncodeContext,
820 }
821
822 impl<'a, 'tcx, E> CacheEncoder<'a, 'tcx, E>
823 where
824     E: 'a + OpaqueEncoder,
825 {
826     fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
827         self.file_to_file_index[&(&*source_file as *const SourceFile)]
828     }
829
830     /// Encode something with additional information that allows to do some
831     /// sanity checks when decoding the data again. This method will first
832     /// encode the specified tag, then the given value, then the number of
833     /// bytes taken up by tag and value. On decoding, we can then verify that
834     /// we get the expected tag and read the expected number of bytes.
835     fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(
836         &mut self,
837         tag: T,
838         value: &V,
839     ) -> Result<(), E::Error> {
840         let start_pos = self.position();
841
842         tag.encode(self)?;
843         value.encode(self)?;
844
845         let end_pos = self.position();
846         ((end_pos - start_pos) as u64).encode(self)
847     }
848 }
849
850 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for SyntaxContext
851 where
852     E: 'a + OpaqueEncoder,
853 {
854     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
855         rustc_span::hygiene::raw_encode_syntax_context(*self, s.hygiene_context, s)
856     }
857 }
858
859 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for ExpnId
860 where
861     E: 'a + OpaqueEncoder,
862 {
863     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
864         s.hygiene_context.schedule_expn_data_for_encoding(*self);
865         self.expn_hash().encode(s)
866     }
867 }
868
869 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for Span
870 where
871     E: 'a + OpaqueEncoder,
872 {
873     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
874         let span_data = self.data_untracked();
875         span_data.ctxt.encode(s)?;
876         span_data.parent.encode(s)?;
877
878         if span_data.is_dummy() {
879             return TAG_PARTIAL_SPAN.encode(s);
880         }
881
882         if let Some(parent) = span_data.parent {
883             let enclosing = s.tcx.definitions_untracked().def_span(parent).data_untracked();
884             if enclosing.contains(span_data) {
885                 TAG_RELATIVE_SPAN.encode(s)?;
886                 (span_data.lo - enclosing.lo).to_u32().encode(s)?;
887                 (span_data.hi - enclosing.lo).to_u32().encode(s)?;
888                 return Ok(());
889             }
890         }
891
892         let pos = s.source_map.byte_pos_to_line_and_col(span_data.lo);
893         let partial_span = match &pos {
894             Some((file_lo, _, _)) => !file_lo.contains(span_data.hi),
895             None => true,
896         };
897
898         if partial_span {
899             return TAG_PARTIAL_SPAN.encode(s);
900         }
901
902         let (file_lo, line_lo, col_lo) = pos.unwrap();
903
904         let len = span_data.hi - span_data.lo;
905
906         let source_file_index = s.source_file_index(file_lo);
907
908         TAG_FULL_SPAN.encode(s)?;
909         source_file_index.encode(s)?;
910         line_lo.encode(s)?;
911         col_lo.encode(s)?;
912         len.encode(s)
913     }
914 }
915
916 impl<'a, 'tcx, E> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx, E>
917 where
918     E: 'a + OpaqueEncoder,
919 {
920     const CLEAR_CROSS_CRATE: bool = false;
921
922     fn position(&self) -> usize {
923         self.encoder.position()
924     }
925     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
926         &mut self.type_shorthands
927     }
928     fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
929         &mut self.predicate_shorthands
930     }
931     fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
932         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
933
934         index.encode(self)
935     }
936 }
937
938 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for CrateNum
939 where
940     E: 'a + OpaqueEncoder,
941 {
942     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
943         s.tcx.stable_crate_id(*self).encode(s)
944     }
945 }
946
947 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefId
948 where
949     E: 'a + OpaqueEncoder,
950 {
951     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
952         s.tcx.def_path_hash(*self).encode(s)
953     }
954 }
955
956 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefIndex
957 where
958     E: 'a + OpaqueEncoder,
959 {
960     fn encode(&self, _: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
961         bug!("encoding `DefIndex` without context");
962     }
963 }
964
965 macro_rules! encoder_methods {
966     ($($name:ident($ty:ty);)*) => {
967         #[inline]
968         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
969             self.encoder.$name(value)
970         })*
971     }
972 }
973
974 impl<'a, 'tcx, E> Encoder for CacheEncoder<'a, 'tcx, E>
975 where
976     E: 'a + OpaqueEncoder,
977 {
978     type Error = E::Error;
979
980     #[inline]
981     fn emit_unit(&mut self) -> Result<(), Self::Error> {
982         Ok(())
983     }
984
985     encoder_methods! {
986         emit_usize(usize);
987         emit_u128(u128);
988         emit_u64(u64);
989         emit_u32(u32);
990         emit_u16(u16);
991         emit_u8(u8);
992
993         emit_isize(isize);
994         emit_i128(i128);
995         emit_i64(i64);
996         emit_i32(i32);
997         emit_i16(i16);
998         emit_i8(i8);
999
1000         emit_bool(bool);
1001         emit_f64(f64);
1002         emit_f32(f32);
1003         emit_char(char);
1004         emit_str(&str);
1005         emit_raw_bytes(&[u8]);
1006     }
1007 }
1008
1009 // This ensures that the `Encodable<opaque::FileEncoder>::encode` specialization for byte slices
1010 // is used when a `CacheEncoder` having an `opaque::FileEncoder` is passed to `Encodable::encode`.
1011 // Unfortunately, we have to manually opt into specializations this way, given how `CacheEncoder`
1012 // and the encoding traits currently work.
1013 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx, FileEncoder>> for [u8] {
1014     fn encode(&self, e: &mut CacheEncoder<'a, 'tcx, FileEncoder>) -> FileEncodeResult {
1015         self.encode(e.encoder)
1016     }
1017 }
1018
1019 pub fn encode_query_results<'a, 'tcx, CTX, Q>(
1020     tcx: CTX,
1021     encoder: &mut CacheEncoder<'a, 'tcx, FileEncoder>,
1022     query_result_index: &mut EncodedDepNodeIndex,
1023 ) -> FileEncodeResult
1024 where
1025     CTX: QueryContext + 'tcx,
1026     Q: super::QueryDescription<CTX>,
1027     Q::Value: Encodable<CacheEncoder<'a, 'tcx, FileEncoder>>,
1028 {
1029     let _timer = tcx
1030         .dep_context()
1031         .profiler()
1032         .extra_verbose_generic_activity("encode_query_results_for", std::any::type_name::<Q>());
1033
1034     assert!(Q::query_state(tcx).all_inactive());
1035     let cache = Q::query_cache(tcx);
1036     let mut res = Ok(());
1037     cache.iter_results(&mut |key, value, dep_node| {
1038         if res.is_err() {
1039             return;
1040         }
1041         if Q::cache_on_disk(*tcx.dep_context(), &key) {
1042             let dep_node = SerializedDepNodeIndex::new(dep_node.index());
1043
1044             // Record position of the cache entry.
1045             query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.encoder.position())));
1046
1047             // Encode the type check tables with the `SerializedDepNodeIndex`
1048             // as tag.
1049             match encoder.encode_tagged(dep_node, value) {
1050                 Ok(()) => {}
1051                 Err(e) => {
1052                     res = Err(e);
1053                 }
1054             }
1055         }
1056     });
1057
1058     res
1059 }