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