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