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