]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/query/on_disk_cache.rs
Auto merge of #85252 - kulikjak:fix-solaris-CI, r=Mark-Simulacrum
[rust.git] / compiler / rustc_middle / src / ty / query / on_disk_cache.rs
1 use crate::dep_graph::{DepNode, DepNodeIndex, SerializedDepNodeIndex};
2 use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState};
3 use crate::mir::{self, interpret};
4 use crate::ty::codec::{RefDecodable, TyDecoder, TyEncoder};
5 use crate::ty::context::TyCtxt;
6 use crate::ty::{self, Ty};
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
8 use rustc_data_structures::sync::{HashMapExt, Lock, Lrc, OnceCell};
9 use rustc_data_structures::thin_vec::ThinVec;
10 use rustc_data_structures::unhash::UnhashMap;
11 use rustc_errors::Diagnostic;
12 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, LOCAL_CRATE};
13 use rustc_hir::definitions::{DefPathHash, DefPathTable};
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_query_system::dep_graph::DepContext;
16 use rustc_query_system::query::QueryContext;
17 use rustc_serialize::{
18     opaque::{self, FileEncodeResult, FileEncoder, IntEncodedWithFixedSize},
19     Decodable, Decoder, Encodable, Encoder,
20 };
21 use rustc_session::{CrateDisambiguator, Session};
22 use rustc_span::hygiene::{
23     ExpnDataDecodeMode, ExpnDataEncodeMode, ExpnId, HygieneDecodeContext, HygieneEncodeContext,
24     SyntaxContext, SyntaxContextData,
25 };
26 use rustc_span::source_map::{SourceMap, StableSourceFileId};
27 use rustc_span::CachingSourceMapView;
28 use rustc_span::{BytePos, ExpnData, SourceFile, Span, DUMMY_SP};
29 use std::collections::hash_map::Entry;
30 use std::iter::FromIterator;
31 use std::mem;
32
33 const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
34
35 // A normal span encoded with both location information and a `SyntaxContext`
36 const TAG_FULL_SPAN: u8 = 0;
37 // A partial span with no location information, encoded only with a `SyntaxContext`
38 const TAG_PARTIAL_SPAN: u8 = 1;
39
40 const TAG_SYNTAX_CONTEXT: u8 = 0;
41 const TAG_EXPN_DATA: u8 = 1;
42
43 /// Provides an interface to incremental compilation data cached from the
44 /// previous compilation session. This data will eventually include the results
45 /// of a few selected queries (like `typeck` and `mir_optimized`) and
46 /// any diagnostics that have been emitted during a query.
47 pub struct OnDiskCache<'sess> {
48     // The complete cache data in serialized form.
49     serialized_data: Vec<u8>,
50
51     // Collects all `Diagnostic`s emitted during the current compilation
52     // session.
53     current_diagnostics: Lock<FxHashMap<DepNodeIndex, Vec<Diagnostic>>>,
54
55     prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
56     cnum_map: OnceCell<IndexVec<CrateNum, Option<CrateNum>>>,
57
58     source_map: &'sess SourceMap,
59     file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
60
61     // Caches that are populated lazily during decoding.
62     file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
63
64     // A map from dep-node to the position of the cached query result in
65     // `serialized_data`.
66     query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
67
68     // A map from dep-node to the position of any associated diagnostics in
69     // `serialized_data`.
70     prev_diagnostics_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
71
72     alloc_decoding_state: AllocDecodingState,
73
74     // A map from syntax context ids to the position of their associated
75     // `SyntaxContextData`. We use a `u32` instead of a `SyntaxContext`
76     // to represent the fact that we are storing *encoded* ids. When we decode
77     // a `SyntaxContext`, a new id will be allocated from the global `HygieneData`,
78     // which will almost certainly be different than the serialized id.
79     syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
80     // A map from the `DefPathHash` of an `ExpnId` to the position
81     // of their associated `ExpnData`. Ideally, we would store a `DefId`,
82     // but we need to decode this before we've constructed a `TyCtxt` (which
83     // makes it difficult to decode a `DefId`).
84
85     // Note that these `DefPathHashes` correspond to both local and foreign
86     // `ExpnData` (e.g `ExpnData.krate` may not be `LOCAL_CRATE`). Alternatively,
87     // we could look up the `ExpnData` from the metadata of foreign crates,
88     // but it seemed easier to have `OnDiskCache` be independent of the `CStore`.
89     expn_data: FxHashMap<u32, AbsoluteBytePos>,
90     // Additional information used when decoding hygiene data.
91     hygiene_context: HygieneDecodeContext,
92     // Maps `DefPathHash`es to their `RawDefId`s from the *previous*
93     // compilation session. This is used as an initial 'guess' when
94     // we try to map a `DefPathHash` to its `DefId` in the current compilation
95     // session.
96     foreign_def_path_hashes: UnhashMap<DefPathHash, RawDefId>,
97
98     // The *next* compilation sessison's `foreign_def_path_hashes` - at
99     // the end of our current compilation session, this will get written
100     // out to the `foreign_def_path_hashes` field of the `Footer`, which
101     // will become `foreign_def_path_hashes` of the next compilation session.
102     // This stores any `DefPathHash` that we may need to map to a `DefId`
103     // during the next compilation session.
104     latest_foreign_def_path_hashes: Lock<UnhashMap<DefPathHash, RawDefId>>,
105
106     // Maps `DefPathHashes` to their corresponding `LocalDefId`s for all
107     // local items in the current compilation session. This is only populated
108     // when we are in incremental mode and have loaded a pre-existing cache
109     // from disk, since this map is only used when deserializing a `DefPathHash`
110     // from the incremental cache.
111     local_def_path_hash_to_def_id: UnhashMap<DefPathHash, LocalDefId>,
112     // Caches all lookups of `DefPathHashes`, both for local and foreign
113     // definitions. A definition from the previous compilation session
114     // may no longer exist in the current compilation session, so
115     // we use `Option<DefId>` so that we can cache a lookup failure.
116     def_path_hash_to_def_id_cache: Lock<UnhashMap<DefPathHash, Option<DefId>>>,
117 }
118
119 // This type is used only for serialization and deserialization.
120 #[derive(Encodable, Decodable)]
121 struct Footer {
122     file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
123     prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
124     query_result_index: EncodedQueryResultIndex,
125     diagnostics_index: EncodedQueryResultIndex,
126     // The location of all allocations.
127     interpret_alloc_index: Vec<u32>,
128     // See `OnDiskCache.syntax_contexts`
129     syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
130     // See `OnDiskCache.expn_data`
131     expn_data: FxHashMap<u32, AbsoluteBytePos>,
132     foreign_def_path_hashes: UnhashMap<DefPathHash, RawDefId>,
133 }
134
135 pub type EncodedQueryResultIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
136 type EncodedDiagnosticsIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
137 type EncodedDiagnostics = Vec<Diagnostic>;
138
139 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
140 struct SourceFileIndex(u32);
141
142 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Encodable, Decodable)]
143 pub struct AbsoluteBytePos(u32);
144
145 impl AbsoluteBytePos {
146     fn new(pos: usize) -> AbsoluteBytePos {
147         debug_assert!(pos <= u32::MAX as usize);
148         AbsoluteBytePos(pos as u32)
149     }
150
151     fn to_usize(self) -> usize {
152         self.0 as usize
153     }
154 }
155
156 /// Represents a potentially invalid `DefId`. This is used during incremental
157 /// compilation to represent a `DefId` from the *previous* compilation session,
158 /// which may no longer be valid. This is used to help map a `DefPathHash`
159 /// to a `DefId` in the current compilation session.
160 #[derive(Encodable, Decodable, Copy, Clone, Debug)]
161 crate struct RawDefId {
162     // We deliberately do not use `CrateNum` and `DefIndex`
163     // here, since a crate/index from the previous compilation
164     // session may no longer exist.
165     pub krate: u32,
166     pub index: u32,
167 }
168
169 impl<'sess> OnDiskCache<'sess> {
170     /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
171     pub fn new(
172         sess: &'sess Session,
173         data: Vec<u8>,
174         start_pos: usize,
175         def_path_table: &DefPathTable,
176     ) -> Self {
177         debug_assert!(sess.opts.incremental.is_some());
178
179         // Wrap in a scope so we can borrow `data`.
180         let footer: Footer = {
181             let mut decoder = opaque::Decoder::new(&data[..], start_pos);
182
183             // Decode the *position* of the footer, which can be found in the
184             // last 8 bytes of the file.
185             decoder.set_position(data.len() - IntEncodedWithFixedSize::ENCODED_SIZE);
186             let footer_pos = IntEncodedWithFixedSize::decode(&mut decoder)
187                 .expect("error while trying to decode footer position")
188                 .0 as usize;
189
190             // Decode the file footer, which contains all the lookup tables, etc.
191             decoder.set_position(footer_pos);
192
193             decode_tagged(&mut decoder, TAG_FILE_FOOTER)
194                 .expect("error while trying to decode footer position")
195         };
196
197         Self {
198             serialized_data: data,
199             file_index_to_stable_id: footer.file_index_to_stable_id,
200             file_index_to_file: Default::default(),
201             prev_cnums: footer.prev_cnums,
202             cnum_map: OnceCell::new(),
203             source_map: sess.source_map(),
204             current_diagnostics: Default::default(),
205             query_result_index: footer.query_result_index.into_iter().collect(),
206             prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
207             alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
208             syntax_contexts: footer.syntax_contexts,
209             expn_data: footer.expn_data,
210             hygiene_context: Default::default(),
211             foreign_def_path_hashes: footer.foreign_def_path_hashes,
212             latest_foreign_def_path_hashes: Default::default(),
213             local_def_path_hash_to_def_id: UnhashMap::from_iter(
214                 def_path_table
215                     .all_def_path_hashes_and_def_ids(LOCAL_CRATE)
216                     .map(|(hash, def_id)| (hash, def_id.as_local().unwrap())),
217             ),
218             def_path_hash_to_def_id_cache: Default::default(),
219         }
220     }
221
222     pub fn new_empty(source_map: &'sess SourceMap) -> Self {
223         Self {
224             serialized_data: Vec::new(),
225             file_index_to_stable_id: Default::default(),
226             file_index_to_file: Default::default(),
227             prev_cnums: vec![],
228             cnum_map: OnceCell::new(),
229             source_map,
230             current_diagnostics: Default::default(),
231             query_result_index: Default::default(),
232             prev_diagnostics_index: Default::default(),
233             alloc_decoding_state: AllocDecodingState::new(Vec::new()),
234             syntax_contexts: FxHashMap::default(),
235             expn_data: FxHashMap::default(),
236             hygiene_context: Default::default(),
237             foreign_def_path_hashes: Default::default(),
238             latest_foreign_def_path_hashes: Default::default(),
239             local_def_path_hash_to_def_id: Default::default(),
240             def_path_hash_to_def_id_cache: Default::default(),
241         }
242     }
243
244     pub fn serialize<'tcx>(
245         &self,
246         tcx: TyCtxt<'tcx>,
247         encoder: &mut FileEncoder,
248     ) -> FileEncodeResult {
249         // Serializing the `DepGraph` should not modify it.
250         tcx.dep_graph.with_ignore(|| {
251             // Allocate `SourceFileIndex`es.
252             let (file_to_file_index, file_index_to_stable_id) = {
253                 let files = tcx.sess.source_map().files();
254                 let mut file_to_file_index =
255                     FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
256                 let mut file_index_to_stable_id =
257                     FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
258
259                 for (index, file) in files.iter().enumerate() {
260                     let index = SourceFileIndex(index as u32);
261                     let file_ptr: *const SourceFile = &**file as *const _;
262                     file_to_file_index.insert(file_ptr, index);
263                     file_index_to_stable_id.insert(index, StableSourceFileId::new(&file));
264                 }
265
266                 (file_to_file_index, file_index_to_stable_id)
267             };
268
269             // Register any dep nodes that we reused from the previous session,
270             // but didn't `DepNode::construct` in this session. This ensures
271             // that their `DefPathHash` to `RawDefId` mappings are registered
272             // in 'latest_foreign_def_path_hashes' if necessary, since that
273             // normally happens in `DepNode::construct`.
274             tcx.dep_graph.register_reused_dep_nodes(tcx);
275
276             // Load everything into memory so we can write it out to the on-disk
277             // cache. The vast majority of cacheable query results should already
278             // be in memory, so this should be a cheap operation.
279             // Do this *before* we clone 'latest_foreign_def_path_hashes', since
280             // loading existing queries may cause us to create new DepNodes, which
281             // may in turn end up invoking `store_foreign_def_id_hash`
282             tcx.queries.exec_cache_promotions(tcx);
283
284             let latest_foreign_def_path_hashes = self.latest_foreign_def_path_hashes.lock().clone();
285             let hygiene_encode_context = HygieneEncodeContext::default();
286
287             let mut encoder = CacheEncoder {
288                 tcx,
289                 encoder,
290                 type_shorthands: Default::default(),
291                 predicate_shorthands: Default::default(),
292                 interpret_allocs: Default::default(),
293                 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
294                 file_to_file_index,
295                 hygiene_context: &hygiene_encode_context,
296                 latest_foreign_def_path_hashes,
297             };
298
299             // Encode query results.
300             let mut query_result_index = EncodedQueryResultIndex::new();
301
302             tcx.sess.time("encode_query_results", || -> FileEncodeResult {
303                 let enc = &mut encoder;
304                 let qri = &mut query_result_index;
305                 tcx.queries.encode_query_results(tcx, enc, qri)
306             })?;
307
308             // Encode diagnostics.
309             let diagnostics_index: EncodedDiagnosticsIndex = self
310                 .current_diagnostics
311                 .borrow()
312                 .iter()
313                 .map(
314                     |(dep_node_index, diagnostics)| -> Result<_, <FileEncoder as Encoder>::Error> {
315                         let pos = AbsoluteBytePos::new(encoder.position());
316                         // Let's make sure we get the expected type here.
317                         let diagnostics: &EncodedDiagnostics = diagnostics;
318                         let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
319                         encoder.encode_tagged(dep_node_index, diagnostics)?;
320
321                         Ok((dep_node_index, pos))
322                     },
323                 )
324                 .collect::<Result<_, _>>()?;
325
326             let interpret_alloc_index = {
327                 let mut interpret_alloc_index = Vec::new();
328                 let mut n = 0;
329                 loop {
330                     let new_n = encoder.interpret_allocs.len();
331                     // If we have found new IDs, serialize those too.
332                     if n == new_n {
333                         // Otherwise, abort.
334                         break;
335                     }
336                     interpret_alloc_index.reserve(new_n - n);
337                     for idx in n..new_n {
338                         let id = encoder.interpret_allocs[idx];
339                         let pos = encoder.position() as u32;
340                         interpret_alloc_index.push(pos);
341                         interpret::specialized_encode_alloc_id(&mut encoder, tcx, id)?;
342                     }
343                     n = new_n;
344                 }
345                 interpret_alloc_index
346             };
347
348             let sorted_cnums = sorted_cnums_including_local_crate(tcx);
349             let prev_cnums: Vec<_> = sorted_cnums
350                 .iter()
351                 .map(|&cnum| {
352                     let crate_name = tcx.original_crate_name(cnum).to_string();
353                     let crate_disambiguator = tcx.crate_disambiguator(cnum);
354                     (cnum.as_u32(), crate_name, crate_disambiguator)
355                 })
356                 .collect();
357
358             let mut syntax_contexts = FxHashMap::default();
359             let mut expn_ids = FxHashMap::default();
360
361             // Encode all hygiene data (`SyntaxContextData` and `ExpnData`) from the current
362             // session.
363
364             hygiene_encode_context.encode(
365                 &mut encoder,
366                 |encoder, index, ctxt_data| -> FileEncodeResult {
367                     let pos = AbsoluteBytePos::new(encoder.position());
368                     encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data)?;
369                     syntax_contexts.insert(index, pos);
370                     Ok(())
371                 },
372                 |encoder, index, expn_data| -> FileEncodeResult {
373                     let pos = AbsoluteBytePos::new(encoder.position());
374                     encoder.encode_tagged(TAG_EXPN_DATA, expn_data)?;
375                     expn_ids.insert(index, pos);
376                     Ok(())
377                 },
378             )?;
379
380             let foreign_def_path_hashes =
381                 std::mem::take(&mut encoder.latest_foreign_def_path_hashes);
382
383             // `Encode the file footer.
384             let footer_pos = encoder.position() as u64;
385             encoder.encode_tagged(
386                 TAG_FILE_FOOTER,
387                 &Footer {
388                     file_index_to_stable_id,
389                     prev_cnums,
390                     query_result_index,
391                     diagnostics_index,
392                     interpret_alloc_index,
393                     syntax_contexts,
394                     expn_data: expn_ids,
395                     foreign_def_path_hashes,
396                 },
397             )?;
398
399             // Encode the position of the footer as the last 8 bytes of the
400             // file so we know where to look for it.
401             IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder)?;
402
403             // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
404             // of the footer must be the last thing in the data stream.
405
406             return Ok(());
407
408             fn sorted_cnums_including_local_crate(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
409                 let mut cnums = vec![LOCAL_CRATE];
410                 cnums.extend_from_slice(tcx.crates());
411                 cnums.sort_unstable();
412                 // Just to be sure...
413                 cnums.dedup();
414                 cnums
415             }
416         })
417     }
418
419     /// Loads a diagnostic emitted during the previous compilation session.
420     pub fn load_diagnostics(
421         &self,
422         tcx: TyCtxt<'_>,
423         dep_node_index: SerializedDepNodeIndex,
424     ) -> Vec<Diagnostic> {
425         let diagnostics: Option<EncodedDiagnostics> =
426             self.load_indexed(tcx, dep_node_index, &self.prev_diagnostics_index, "diagnostics");
427
428         diagnostics.unwrap_or_default()
429     }
430
431     /// Stores a diagnostic emitted during the current compilation session.
432     /// Anything stored like this will be available via `load_diagnostics` in
433     /// the next compilation session.
434     #[inline(never)]
435     #[cold]
436     pub fn store_diagnostics(
437         &self,
438         dep_node_index: DepNodeIndex,
439         diagnostics: ThinVec<Diagnostic>,
440     ) {
441         let mut current_diagnostics = self.current_diagnostics.borrow_mut();
442         let prev = current_diagnostics.insert(dep_node_index, diagnostics.into());
443         debug_assert!(prev.is_none());
444     }
445
446     fn get_raw_def_id(&self, hash: &DefPathHash) -> Option<RawDefId> {
447         self.foreign_def_path_hashes.get(hash).copied()
448     }
449
450     fn try_remap_cnum(&self, tcx: TyCtxt<'_>, cnum: u32) -> Option<CrateNum> {
451         let cnum_map =
452             self.cnum_map.get_or_init(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
453         debug!("try_remap_cnum({}): cnum_map={:?}", cnum, cnum_map);
454
455         cnum_map[CrateNum::from_u32(cnum)]
456     }
457
458     pub(crate) fn store_foreign_def_id_hash(&self, def_id: DefId, hash: DefPathHash) {
459         // We may overwrite an existing entry, but it will have the same value,
460         // so it's fine
461         self.latest_foreign_def_path_hashes
462             .lock()
463             .insert(hash, RawDefId { krate: def_id.krate.as_u32(), index: def_id.index.as_u32() });
464     }
465
466     /// If the given `dep_node`'s hash still exists in the current compilation,
467     /// and its current `DefId` is foreign, calls `store_foreign_def_id` with it.
468     ///
469     /// Normally, `store_foreign_def_id_hash` can be called directly by
470     /// the dependency graph when we construct a `DepNode`. However,
471     /// when we re-use a deserialized `DepNode` from the previous compilation
472     /// session, we only have the `DefPathHash` available. This method is used
473     /// to that any `DepNode` that we re-use has a `DefPathHash` -> `RawId` written
474     /// out for usage in the next compilation session.
475     pub fn register_reused_dep_node(&self, tcx: TyCtxt<'tcx>, dep_node: &DepNode) {
476         // For reused dep nodes, we only need to store the mapping if the node
477         // is one whose query key we can reconstruct from the hash. We use the
478         // mapping to aid that reconstruction in the next session. While we also
479         // use it to decode `DefId`s we encoded in the cache as `DefPathHashes`,
480         // they're already registered during `DefId` encoding.
481         if dep_node.kind.can_reconstruct_query_key() {
482             let hash = DefPathHash(dep_node.hash.into());
483
484             // We can't simply copy the `RawDefId` from `foreign_def_path_hashes` to
485             // `latest_foreign_def_path_hashes`, since the `RawDefId` might have
486             // changed in the current compilation session (e.g. we've added/removed crates,
487             // or added/removed definitions before/after the target definition).
488             if let Some(def_id) = self.def_path_hash_to_def_id(tcx, hash) {
489                 if !def_id.is_local() {
490                     self.store_foreign_def_id_hash(def_id, hash);
491                 }
492             }
493         }
494     }
495
496     /// Returns the cached query result if there is something in the cache for
497     /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
498     pub fn try_load_query_result<'tcx, T>(
499         &self,
500         tcx: TyCtxt<'tcx>,
501         dep_node_index: SerializedDepNodeIndex,
502     ) -> Option<T>
503     where
504         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
505     {
506         self.load_indexed(tcx, dep_node_index, &self.query_result_index, "query result")
507     }
508
509     /// Stores a diagnostic emitted during computation of an anonymous query.
510     /// Since many anonymous queries can share the same `DepNode`, we aggregate
511     /// them -- as opposed to regular queries where we assume that there is a
512     /// 1:1 relationship between query-key and `DepNode`.
513     #[inline(never)]
514     #[cold]
515     pub fn store_diagnostics_for_anon_node(
516         &self,
517         dep_node_index: DepNodeIndex,
518         diagnostics: ThinVec<Diagnostic>,
519     ) {
520         let mut current_diagnostics = self.current_diagnostics.borrow_mut();
521
522         let x = current_diagnostics.entry(dep_node_index).or_default();
523
524         x.extend(Into::<Vec<_>>::into(diagnostics));
525     }
526
527     fn load_indexed<'tcx, T>(
528         &self,
529         tcx: TyCtxt<'tcx>,
530         dep_node_index: SerializedDepNodeIndex,
531         index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
532         debug_tag: &'static str,
533     ) -> Option<T>
534     where
535         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
536     {
537         let pos = index.get(&dep_node_index).cloned()?;
538
539         self.with_decoder(tcx, pos, |decoder| match decode_tagged(decoder, dep_node_index) {
540             Ok(v) => Some(v),
541             Err(e) => bug!("could not decode cached {}: {}", debug_tag, e),
542         })
543     }
544
545     fn with_decoder<'a, 'tcx, T, F: FnOnce(&mut CacheDecoder<'sess, 'tcx>) -> T>(
546         &'sess self,
547         tcx: TyCtxt<'tcx>,
548         pos: AbsoluteBytePos,
549         f: F,
550     ) -> T
551     where
552         T: Decodable<CacheDecoder<'a, 'tcx>>,
553     {
554         let cnum_map =
555             self.cnum_map.get_or_init(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
556
557         let mut decoder = CacheDecoder {
558             tcx,
559             opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()),
560             source_map: self.source_map,
561             cnum_map,
562             file_index_to_file: &self.file_index_to_file,
563             file_index_to_stable_id: &self.file_index_to_stable_id,
564             alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
565             syntax_contexts: &self.syntax_contexts,
566             expn_data: &self.expn_data,
567             hygiene_context: &self.hygiene_context,
568         };
569         f(&mut decoder)
570     }
571
572     // This function builds mapping from previous-session-`CrateNum` to
573     // current-session-`CrateNum`. There might be `CrateNum`s from the previous
574     // `Session` that don't occur in the current one. For these, the mapping
575     // maps to None.
576     fn compute_cnum_map(
577         tcx: TyCtxt<'_>,
578         prev_cnums: &[(u32, String, CrateDisambiguator)],
579     ) -> IndexVec<CrateNum, Option<CrateNum>> {
580         tcx.dep_graph.with_ignore(|| {
581             let current_cnums = tcx
582                 .all_crate_nums(())
583                 .iter()
584                 .map(|&cnum| {
585                     let crate_name = tcx.original_crate_name(cnum).to_string();
586                     let crate_disambiguator = tcx.crate_disambiguator(cnum);
587                     ((crate_name, crate_disambiguator), cnum)
588                 })
589                 .collect::<FxHashMap<_, _>>();
590
591             let map_size = prev_cnums.iter().map(|&(cnum, ..)| cnum).max().unwrap_or(0) + 1;
592             let mut map = IndexVec::from_elem_n(None, map_size as usize);
593
594             for &(prev_cnum, ref crate_name, crate_disambiguator) in prev_cnums {
595                 let key = (crate_name.clone(), crate_disambiguator);
596                 map[CrateNum::from_u32(prev_cnum)] = current_cnums.get(&key).cloned();
597             }
598
599             map[LOCAL_CRATE] = Some(LOCAL_CRATE);
600             map
601         })
602     }
603
604     /// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
605     /// session, if it still exists. This is used during incremental compilation to
606     /// turn a deserialized `DefPathHash` into its current `DefId`.
607     pub(crate) fn def_path_hash_to_def_id(
608         &self,
609         tcx: TyCtxt<'tcx>,
610         hash: DefPathHash,
611     ) -> Option<DefId> {
612         let mut cache = self.def_path_hash_to_def_id_cache.lock();
613         match cache.entry(hash) {
614             Entry::Occupied(e) => *e.get(),
615             Entry::Vacant(e) => {
616                 debug!("def_path_hash_to_def_id({:?})", hash);
617                 // Check if the `DefPathHash` corresponds to a definition in the current
618                 // crate
619                 if let Some(def_id) = self.local_def_path_hash_to_def_id.get(&hash).cloned() {
620                     let def_id = def_id.to_def_id();
621                     e.insert(Some(def_id));
622                     return Some(def_id);
623                 }
624                 // This `raw_def_id` represents the `DefId` of this `DefPathHash` in
625                 // the *previous* compliation session. The `DefPathHash` includes the
626                 // owning crate, so if the corresponding definition still exists in the
627                 // current compilation session, the crate is guaranteed to be the same
628                 // (otherwise, we would compute a different `DefPathHash`).
629                 let raw_def_id = self.get_raw_def_id(&hash)?;
630                 debug!("def_path_hash_to_def_id({:?}): raw_def_id = {:?}", hash, raw_def_id);
631                 // If the owning crate no longer exists, the corresponding definition definitely
632                 // no longer exists.
633                 let krate = self.try_remap_cnum(tcx, raw_def_id.krate)?;
634                 debug!("def_path_hash_to_def_id({:?}): krate = {:?}", hash, krate);
635                 // If our `DefPathHash` corresponded to a definition in the local crate,
636                 // we should have either found it in `local_def_path_hash_to_def_id`, or
637                 // never attempted to load it in the first place. Any query result or `DepNode`
638                 // that references a local `DefId` should depend on some HIR-related `DepNode`.
639                 // If a local definition is removed/modified such that its old `DefPathHash`
640                 // no longer has a corresponding definition, that HIR-related `DepNode` should
641                 // end up red. This should prevent us from ever calling
642                 // `tcx.def_path_hash_to_def_id`, since we'll end up recomputing any
643                 // queries involved.
644                 debug_assert_ne!(krate, LOCAL_CRATE);
645                 // Try to find a definition in the current session, using the previous `DefIndex`
646                 // as an initial guess.
647                 let opt_def_id = tcx.cstore.def_path_hash_to_def_id(krate, raw_def_id.index, hash);
648                 debug!("def_path_to_def_id({:?}): opt_def_id = {:?}", hash, opt_def_id);
649                 e.insert(opt_def_id);
650                 opt_def_id
651             }
652         }
653     }
654 }
655
656 //- DECODING -------------------------------------------------------------------
657
658 /// A decoder that can read from the incremental compilation cache. It is similar to the one
659 /// we use for crate metadata decoding in that it can rebase spans and eventually
660 /// will also handle things that contain `Ty` instances.
661 pub struct CacheDecoder<'a, 'tcx> {
662     tcx: TyCtxt<'tcx>,
663     opaque: opaque::Decoder<'a>,
664     source_map: &'a SourceMap,
665     cnum_map: &'a IndexVec<CrateNum, Option<CrateNum>>,
666     file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
667     file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, StableSourceFileId>,
668     alloc_decoding_session: AllocDecodingSession<'a>,
669     syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
670     expn_data: &'a FxHashMap<u32, AbsoluteBytePos>,
671     hygiene_context: &'a HygieneDecodeContext,
672 }
673
674 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
675     fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
676         let CacheDecoder {
677             ref file_index_to_file,
678             ref file_index_to_stable_id,
679             ref source_map,
680             ..
681         } = *self;
682
683         file_index_to_file
684             .borrow_mut()
685             .entry(index)
686             .or_insert_with(|| {
687                 let stable_id = file_index_to_stable_id[&index];
688                 source_map
689                     .source_file_by_stable_id(stable_id)
690                     .expect("failed to lookup `SourceFile` in new context")
691             })
692             .clone()
693     }
694 }
695
696 trait DecoderWithPosition: Decoder {
697     fn position(&self) -> usize;
698 }
699
700 impl<'a> DecoderWithPosition for opaque::Decoder<'a> {
701     fn position(&self) -> usize {
702         self.position()
703     }
704 }
705
706 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
707     fn position(&self) -> usize {
708         self.opaque.position()
709     }
710 }
711
712 // Decodes something that was encoded with `encode_tagged()` and verify that the
713 // tag matches and the correct amount of bytes was read.
714 fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> Result<V, D::Error>
715 where
716     T: Decodable<D> + Eq + std::fmt::Debug,
717     V: Decodable<D>,
718     D: DecoderWithPosition,
719 {
720     let start_pos = decoder.position();
721
722     let actual_tag = T::decode(decoder)?;
723     assert_eq!(actual_tag, expected_tag);
724     let value = V::decode(decoder)?;
725     let end_pos = decoder.position();
726
727     let expected_len: u64 = Decodable::decode(decoder)?;
728     assert_eq!((end_pos - start_pos) as u64, expected_len);
729
730     Ok(value)
731 }
732
733 impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
734     const CLEAR_CROSS_CRATE: bool = false;
735
736     #[inline]
737     fn tcx(&self) -> TyCtxt<'tcx> {
738         self.tcx
739     }
740
741     #[inline]
742     fn position(&self) -> usize {
743         self.opaque.position()
744     }
745
746     #[inline]
747     fn peek_byte(&self) -> u8 {
748         self.opaque.data[self.opaque.position()]
749     }
750
751     fn cached_ty_for_shorthand<F>(
752         &mut self,
753         shorthand: usize,
754         or_insert_with: F,
755     ) -> Result<Ty<'tcx>, Self::Error>
756     where
757         F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
758     {
759         let tcx = self.tcx();
760
761         let cache_key =
762             ty::CReaderCacheKey { cnum: CrateNum::ReservedForIncrCompCache, pos: shorthand };
763
764         if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
765             return Ok(ty);
766         }
767
768         let ty = or_insert_with(self)?;
769         // This may overwrite the entry, but it should overwrite with the same value.
770         tcx.ty_rcache.borrow_mut().insert_same(cache_key, ty);
771         Ok(ty)
772     }
773
774     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
775     where
776         F: FnOnce(&mut Self) -> R,
777     {
778         debug_assert!(pos < self.opaque.data.len());
779
780         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
781         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
782         let r = f(self);
783         self.opaque = old_opaque;
784         r
785     }
786
787     fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
788         self.cnum_map[cnum].unwrap_or_else(|| bug!("could not find new `CrateNum` for {:?}", cnum))
789     }
790
791     fn decode_alloc_id(&mut self) -> Result<interpret::AllocId, Self::Error> {
792         let alloc_decoding_session = self.alloc_decoding_session;
793         alloc_decoding_session.decode_alloc_id(self)
794     }
795 }
796
797 crate::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
798
799 // This ensures that the `Decodable<opaque::Decoder>::decode` specialization for `Vec<u8>` is used
800 // when a `CacheDecoder` is passed to `Decodable::decode`. Unfortunately, we have to manually opt
801 // into specializations this way, given how `CacheDecoder` and the decoding traits currently work.
802 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Vec<u8> {
803     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
804         Decodable::decode(&mut d.opaque)
805     }
806 }
807
808 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for SyntaxContext {
809     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
810         let syntax_contexts = decoder.syntax_contexts;
811         rustc_span::hygiene::decode_syntax_context(decoder, decoder.hygiene_context, |this, id| {
812             // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
813             // We look up the position of the associated `SyntaxData` and decode it.
814             let pos = syntax_contexts.get(&id).unwrap();
815             this.with_position(pos.to_usize(), |decoder| {
816                 let data: SyntaxContextData = decode_tagged(decoder, TAG_SYNTAX_CONTEXT)?;
817                 Ok(data)
818             })
819         })
820     }
821 }
822
823 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for ExpnId {
824     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
825         let expn_data = decoder.expn_data;
826         rustc_span::hygiene::decode_expn_id(
827             decoder,
828             ExpnDataDecodeMode::incr_comp(decoder.hygiene_context),
829             |this, index| {
830                 // This closure is invoked if we haven't already decoded the data for the `ExpnId` we are deserializing.
831                 // We look up the position of the associated `ExpnData` and decode it.
832                 let pos = expn_data
833                     .get(&index)
834                     .unwrap_or_else(|| panic!("Bad index {:?} (map {:?})", index, expn_data));
835
836                 this.with_position(pos.to_usize(), |decoder| {
837                     let data: ExpnData = decode_tagged(decoder, TAG_EXPN_DATA)?;
838                     Ok(data)
839                 })
840             },
841         )
842     }
843 }
844
845 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Span {
846     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
847         let tag: u8 = Decodable::decode(decoder)?;
848
849         if tag == TAG_PARTIAL_SPAN {
850             let ctxt = SyntaxContext::decode(decoder)?;
851             return Ok(DUMMY_SP.with_ctxt(ctxt));
852         } else {
853             debug_assert_eq!(tag, TAG_FULL_SPAN);
854         }
855
856         let file_lo_index = SourceFileIndex::decode(decoder)?;
857         let line_lo = usize::decode(decoder)?;
858         let col_lo = BytePos::decode(decoder)?;
859         let len = BytePos::decode(decoder)?;
860         let ctxt = SyntaxContext::decode(decoder)?;
861
862         let file_lo = decoder.file_index_to_file(file_lo_index);
863         let lo = file_lo.lines[line_lo - 1] + col_lo;
864         let hi = lo + len;
865
866         Ok(Span::new(lo, hi, ctxt))
867     }
868 }
869
870 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for CrateNum {
871     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
872         let cnum = CrateNum::from_u32(u32::decode(d)?);
873         Ok(d.map_encoded_cnum_to_current(cnum))
874     }
875 }
876
877 // This impl makes sure that we get a runtime error when we try decode a
878 // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
879 // because we would not know how to transform the `DefIndex` to the current
880 // context.
881 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefIndex {
882     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<DefIndex, String> {
883         Err(d.error("trying to decode `DefIndex` outside the context of a `DefId`"))
884     }
885 }
886
887 // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
888 // compilation sessions. We use the `DefPathHash`, which is stable across
889 // sessions, to map the old `DefId` to the new one.
890 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefId {
891     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
892         // Load the `DefPathHash` which is was we encoded the `DefId` as.
893         let def_path_hash = DefPathHash::decode(d)?;
894
895         // Using the `DefPathHash`, we can lookup the new `DefId`.
896         // Subtle: We only encode a `DefId` as part of a query result.
897         // If we get to this point, then all of the query inputs were green,
898         // which means that the definition with this hash is guaranteed to
899         // still exist in the current compilation session.
900         Ok(d.tcx()
901             .on_disk_cache
902             .as_ref()
903             .unwrap()
904             .def_path_hash_to_def_id(d.tcx(), def_path_hash)
905             .unwrap())
906     }
907 }
908
909 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx FxHashSet<LocalDefId> {
910     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
911         RefDecodable::decode(d)
912     }
913 }
914
915 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
916     for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
917 {
918     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
919         RefDecodable::decode(d)
920     }
921 }
922
923 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] {
924     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
925         RefDecodable::decode(d)
926     }
927 }
928
929 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
930     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
931         RefDecodable::decode(d)
932     }
933 }
934
935 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_ast::InlineAsmTemplatePiece] {
936     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
937         RefDecodable::decode(d)
938     }
939 }
940
941 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Span] {
942     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
943         RefDecodable::decode(d)
944     }
945 }
946
947 //- ENCODING -------------------------------------------------------------------
948
949 pub trait OpaqueEncoder: Encoder {
950     fn position(&self) -> usize;
951 }
952
953 impl OpaqueEncoder for FileEncoder {
954     #[inline]
955     fn position(&self) -> usize {
956         FileEncoder::position(self)
957     }
958 }
959
960 /// An encoder that can write to the incremental compilation cache.
961 pub struct CacheEncoder<'a, 'tcx, E: OpaqueEncoder> {
962     tcx: TyCtxt<'tcx>,
963     encoder: &'a mut E,
964     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
965     predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
966     interpret_allocs: FxIndexSet<interpret::AllocId>,
967     source_map: CachingSourceMapView<'tcx>,
968     file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
969     hygiene_context: &'a HygieneEncodeContext,
970     latest_foreign_def_path_hashes: UnhashMap<DefPathHash, RawDefId>,
971 }
972
973 impl<'a, 'tcx, E> CacheEncoder<'a, 'tcx, E>
974 where
975     E: 'a + OpaqueEncoder,
976 {
977     fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
978         self.file_to_file_index[&(&*source_file as *const SourceFile)]
979     }
980
981     /// Encode something with additional information that allows to do some
982     /// sanity checks when decoding the data again. This method will first
983     /// encode the specified tag, then the given value, then the number of
984     /// bytes taken up by tag and value. On decoding, we can then verify that
985     /// we get the expected tag and read the expected number of bytes.
986     fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(
987         &mut self,
988         tag: T,
989         value: &V,
990     ) -> Result<(), E::Error> {
991         let start_pos = self.position();
992
993         tag.encode(self)?;
994         value.encode(self)?;
995
996         let end_pos = self.position();
997         ((end_pos - start_pos) as u64).encode(self)
998     }
999 }
1000
1001 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for SyntaxContext
1002 where
1003     E: 'a + OpaqueEncoder,
1004 {
1005     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1006         rustc_span::hygiene::raw_encode_syntax_context(*self, s.hygiene_context, s)
1007     }
1008 }
1009
1010 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for ExpnId
1011 where
1012     E: 'a + OpaqueEncoder,
1013 {
1014     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1015         rustc_span::hygiene::raw_encode_expn_id(
1016             *self,
1017             s.hygiene_context,
1018             ExpnDataEncodeMode::IncrComp,
1019             s,
1020         )
1021     }
1022 }
1023
1024 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for Span
1025 where
1026     E: 'a + OpaqueEncoder,
1027 {
1028     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1029         let span_data = self.data();
1030         if self.is_dummy() {
1031             TAG_PARTIAL_SPAN.encode(s)?;
1032             return span_data.ctxt.encode(s);
1033         }
1034
1035         let pos = s.source_map.byte_pos_to_line_and_col(span_data.lo);
1036         let partial_span = match &pos {
1037             Some((file_lo, _, _)) => !file_lo.contains(span_data.hi),
1038             None => true,
1039         };
1040
1041         if partial_span {
1042             TAG_PARTIAL_SPAN.encode(s)?;
1043             return span_data.ctxt.encode(s);
1044         }
1045
1046         let (file_lo, line_lo, col_lo) = pos.unwrap();
1047
1048         let len = span_data.hi - span_data.lo;
1049
1050         let source_file_index = s.source_file_index(file_lo);
1051
1052         TAG_FULL_SPAN.encode(s)?;
1053         source_file_index.encode(s)?;
1054         line_lo.encode(s)?;
1055         col_lo.encode(s)?;
1056         len.encode(s)?;
1057         span_data.ctxt.encode(s)
1058     }
1059 }
1060
1061 impl<'a, 'tcx, E> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx, E>
1062 where
1063     E: 'a + OpaqueEncoder,
1064 {
1065     const CLEAR_CROSS_CRATE: bool = false;
1066
1067     fn position(&self) -> usize {
1068         self.encoder.position()
1069     }
1070     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
1071         &mut self.type_shorthands
1072     }
1073     fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
1074         &mut self.predicate_shorthands
1075     }
1076     fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
1077         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
1078
1079         index.encode(self)
1080     }
1081 }
1082
1083 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefId
1084 where
1085     E: 'a + OpaqueEncoder,
1086 {
1087     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1088         let def_path_hash = s.tcx.def_path_hash(*self);
1089         // Store additional information when we encode a foreign `DefId`,
1090         // so that we can map its `DefPathHash` back to a `DefId` in the next
1091         // compilation session.
1092         if !self.is_local() {
1093             s.latest_foreign_def_path_hashes.insert(
1094                 def_path_hash,
1095                 RawDefId { krate: self.krate.as_u32(), index: self.index.as_u32() },
1096             );
1097         }
1098         def_path_hash.encode(s)
1099     }
1100 }
1101
1102 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefIndex
1103 where
1104     E: 'a + OpaqueEncoder,
1105 {
1106     fn encode(&self, _: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1107         bug!("encoding `DefIndex` without context");
1108     }
1109 }
1110
1111 macro_rules! encoder_methods {
1112     ($($name:ident($ty:ty);)*) => {
1113         #[inline]
1114         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
1115             self.encoder.$name(value)
1116         })*
1117     }
1118 }
1119
1120 impl<'a, 'tcx, E> Encoder for CacheEncoder<'a, 'tcx, E>
1121 where
1122     E: 'a + OpaqueEncoder,
1123 {
1124     type Error = E::Error;
1125
1126     #[inline]
1127     fn emit_unit(&mut self) -> Result<(), Self::Error> {
1128         Ok(())
1129     }
1130
1131     encoder_methods! {
1132         emit_usize(usize);
1133         emit_u128(u128);
1134         emit_u64(u64);
1135         emit_u32(u32);
1136         emit_u16(u16);
1137         emit_u8(u8);
1138
1139         emit_isize(isize);
1140         emit_i128(i128);
1141         emit_i64(i64);
1142         emit_i32(i32);
1143         emit_i16(i16);
1144         emit_i8(i8);
1145
1146         emit_bool(bool);
1147         emit_f64(f64);
1148         emit_f32(f32);
1149         emit_char(char);
1150         emit_str(&str);
1151         emit_raw_bytes(&[u8]);
1152     }
1153 }
1154
1155 // This ensures that the `Encodable<opaque::FileEncoder>::encode` specialization for byte slices
1156 // is used when a `CacheEncoder` having an `opaque::FileEncoder` is passed to `Encodable::encode`.
1157 // Unfortunately, we have to manually opt into specializations this way, given how `CacheEncoder`
1158 // and the encoding traits currently work.
1159 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx, FileEncoder>> for [u8] {
1160     fn encode(&self, e: &mut CacheEncoder<'a, 'tcx, FileEncoder>) -> FileEncodeResult {
1161         self.encode(e.encoder)
1162     }
1163 }
1164
1165 pub fn encode_query_results<'a, 'tcx, CTX, Q>(
1166     tcx: CTX,
1167     encoder: &mut CacheEncoder<'a, 'tcx, FileEncoder>,
1168     query_result_index: &mut EncodedQueryResultIndex,
1169 ) -> FileEncodeResult
1170 where
1171     CTX: QueryContext + 'tcx,
1172     Q: super::QueryDescription<CTX> + super::QueryAccessors<CTX>,
1173     Q::Value: Encodable<CacheEncoder<'a, 'tcx, FileEncoder>>,
1174 {
1175     let _timer = tcx
1176         .dep_context()
1177         .profiler()
1178         .extra_verbose_generic_activity("encode_query_results_for", std::any::type_name::<Q>());
1179
1180     assert!(Q::query_state(tcx).all_inactive());
1181     let cache = Q::query_cache(tcx);
1182     let mut res = Ok(());
1183     cache.iter_results(&mut |key, value, dep_node| {
1184         if res.is_err() {
1185             return;
1186         }
1187         if Q::cache_on_disk(tcx, &key, Some(value)) {
1188             let dep_node = SerializedDepNodeIndex::new(dep_node.index());
1189
1190             // Record position of the cache entry.
1191             query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.encoder.position())));
1192
1193             // Encode the type check tables with the `SerializedDepNodeIndex`
1194             // as tag.
1195             match encoder.encode_tagged(dep_node, value) {
1196                 Ok(()) => {}
1197                 Err(e) => {
1198                     res = Err(e);
1199                 }
1200             }
1201         }
1202     });
1203
1204     res
1205 }