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