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