]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/query/on_disk_cache.rs
Auto merge of #85905 - cjgillot:one-trait-map, r=Aaron1011
[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::{Session, StableCrateId};
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, StableCrateId)>,
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, StableCrateId)>,
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 stable_crate_id = tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
353                     (cnum.as_u32(), stable_crate_id)
354                 })
355                 .collect();
356
357             let mut syntax_contexts = FxHashMap::default();
358             let mut expn_ids = FxHashMap::default();
359
360             // Encode all hygiene data (`SyntaxContextData` and `ExpnData`) from the current
361             // session.
362
363             hygiene_encode_context.encode(
364                 &mut encoder,
365                 |encoder, index, ctxt_data| -> FileEncodeResult {
366                     let pos = AbsoluteBytePos::new(encoder.position());
367                     encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data)?;
368                     syntax_contexts.insert(index, pos);
369                     Ok(())
370                 },
371                 |encoder, index, expn_data| -> FileEncodeResult {
372                     let pos = AbsoluteBytePos::new(encoder.position());
373                     encoder.encode_tagged(TAG_EXPN_DATA, expn_data)?;
374                     expn_ids.insert(index, pos);
375                     Ok(())
376                 },
377             )?;
378
379             let foreign_def_path_hashes =
380                 std::mem::take(&mut encoder.latest_foreign_def_path_hashes);
381
382             // `Encode the file footer.
383             let footer_pos = encoder.position() as u64;
384             encoder.encode_tagged(
385                 TAG_FILE_FOOTER,
386                 &Footer {
387                     file_index_to_stable_id,
388                     prev_cnums,
389                     query_result_index,
390                     diagnostics_index,
391                     interpret_alloc_index,
392                     syntax_contexts,
393                     expn_data: expn_ids,
394                     foreign_def_path_hashes,
395                 },
396             )?;
397
398             // Encode the position of the footer as the last 8 bytes of the
399             // file so we know where to look for it.
400             IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder)?;
401
402             // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
403             // of the footer must be the last thing in the data stream.
404
405             return Ok(());
406
407             fn sorted_cnums_including_local_crate(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
408                 let mut cnums = vec![LOCAL_CRATE];
409                 cnums.extend_from_slice(tcx.crates());
410                 cnums.sort_unstable();
411                 // Just to be sure...
412                 cnums.dedup();
413                 cnums
414             }
415         })
416     }
417
418     /// Loads a diagnostic emitted during the previous compilation session.
419     pub fn load_diagnostics(
420         &self,
421         tcx: TyCtxt<'_>,
422         dep_node_index: SerializedDepNodeIndex,
423     ) -> Vec<Diagnostic> {
424         let diagnostics: Option<EncodedDiagnostics> =
425             self.load_indexed(tcx, dep_node_index, &self.prev_diagnostics_index, "diagnostics");
426
427         diagnostics.unwrap_or_default()
428     }
429
430     /// Stores a diagnostic emitted during the current compilation session.
431     /// Anything stored like this will be available via `load_diagnostics` in
432     /// the next compilation session.
433     #[inline(never)]
434     #[cold]
435     pub fn store_diagnostics(
436         &self,
437         dep_node_index: DepNodeIndex,
438         diagnostics: ThinVec<Diagnostic>,
439     ) {
440         let mut current_diagnostics = self.current_diagnostics.borrow_mut();
441         let prev = current_diagnostics.insert(dep_node_index, diagnostics.into());
442         debug_assert!(prev.is_none());
443     }
444
445     fn get_raw_def_id(&self, hash: &DefPathHash) -> Option<RawDefId> {
446         self.foreign_def_path_hashes.get(hash).copied()
447     }
448
449     fn try_remap_cnum(&self, tcx: TyCtxt<'_>, cnum: u32) -> Option<CrateNum> {
450         let cnum_map =
451             self.cnum_map.get_or_init(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
452         debug!("try_remap_cnum({}): cnum_map={:?}", cnum, cnum_map);
453
454         cnum_map[CrateNum::from_u32(cnum)]
455     }
456
457     pub(crate) fn store_foreign_def_id_hash(&self, def_id: DefId, hash: DefPathHash) {
458         // We may overwrite an existing entry, but it will have the same value,
459         // so it's fine
460         self.latest_foreign_def_path_hashes
461             .lock()
462             .insert(hash, RawDefId { krate: def_id.krate.as_u32(), index: def_id.index.as_u32() });
463     }
464
465     /// If the given `dep_node`'s hash still exists in the current compilation,
466     /// and its current `DefId` is foreign, calls `store_foreign_def_id` with it.
467     ///
468     /// Normally, `store_foreign_def_id_hash` can be called directly by
469     /// the dependency graph when we construct a `DepNode`. However,
470     /// when we re-use a deserialized `DepNode` from the previous compilation
471     /// session, we only have the `DefPathHash` available. This method is used
472     /// to that any `DepNode` that we re-use has a `DefPathHash` -> `RawId` written
473     /// out for usage in the next compilation session.
474     pub fn register_reused_dep_node(&self, tcx: TyCtxt<'tcx>, dep_node: &DepNode) {
475         // For reused dep nodes, we only need to store the mapping if the node
476         // is one whose query key we can reconstruct from the hash. We use the
477         // mapping to aid that reconstruction in the next session. While we also
478         // use it to decode `DefId`s we encoded in the cache as `DefPathHashes`,
479         // they're already registered during `DefId` encoding.
480         if dep_node.kind.can_reconstruct_query_key() {
481             let hash = DefPathHash(dep_node.hash.into());
482
483             // We can't simply copy the `RawDefId` from `foreign_def_path_hashes` to
484             // `latest_foreign_def_path_hashes`, since the `RawDefId` might have
485             // changed in the current compilation session (e.g. we've added/removed crates,
486             // or added/removed definitions before/after the target definition).
487             if let Some(def_id) = self.def_path_hash_to_def_id(tcx, hash) {
488                 if !def_id.is_local() {
489                     self.store_foreign_def_id_hash(def_id, hash);
490                 }
491             }
492         }
493     }
494
495     /// Returns the cached query result if there is something in the cache for
496     /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
497     pub fn try_load_query_result<'tcx, T>(
498         &self,
499         tcx: TyCtxt<'tcx>,
500         dep_node_index: SerializedDepNodeIndex,
501     ) -> Option<T>
502     where
503         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
504     {
505         self.load_indexed(tcx, dep_node_index, &self.query_result_index, "query result")
506     }
507
508     /// Stores a diagnostic emitted during computation of an anonymous query.
509     /// Since many anonymous queries can share the same `DepNode`, we aggregate
510     /// them -- as opposed to regular queries where we assume that there is a
511     /// 1:1 relationship between query-key and `DepNode`.
512     #[inline(never)]
513     #[cold]
514     pub fn store_diagnostics_for_anon_node(
515         &self,
516         dep_node_index: DepNodeIndex,
517         diagnostics: ThinVec<Diagnostic>,
518     ) {
519         let mut current_diagnostics = self.current_diagnostics.borrow_mut();
520
521         let x = current_diagnostics.entry(dep_node_index).or_default();
522
523         x.extend(Into::<Vec<_>>::into(diagnostics));
524     }
525
526     fn load_indexed<'tcx, T>(
527         &self,
528         tcx: TyCtxt<'tcx>,
529         dep_node_index: SerializedDepNodeIndex,
530         index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
531         debug_tag: &'static str,
532     ) -> Option<T>
533     where
534         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
535     {
536         let pos = index.get(&dep_node_index).cloned()?;
537
538         self.with_decoder(tcx, pos, |decoder| match decode_tagged(decoder, dep_node_index) {
539             Ok(v) => Some(v),
540             Err(e) => bug!("could not decode cached {}: {}", debug_tag, e),
541         })
542     }
543
544     fn with_decoder<'a, 'tcx, T, F: FnOnce(&mut CacheDecoder<'sess, 'tcx>) -> T>(
545         &'sess self,
546         tcx: TyCtxt<'tcx>,
547         pos: AbsoluteBytePos,
548         f: F,
549     ) -> T
550     where
551         T: Decodable<CacheDecoder<'a, 'tcx>>,
552     {
553         let cnum_map =
554             self.cnum_map.get_or_init(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
555
556         let mut decoder = CacheDecoder {
557             tcx,
558             opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()),
559             source_map: self.source_map,
560             cnum_map,
561             file_index_to_file: &self.file_index_to_file,
562             file_index_to_stable_id: &self.file_index_to_stable_id,
563             alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
564             syntax_contexts: &self.syntax_contexts,
565             expn_data: &self.expn_data,
566             hygiene_context: &self.hygiene_context,
567         };
568         f(&mut decoder)
569     }
570
571     // This function builds mapping from previous-session-`CrateNum` to
572     // current-session-`CrateNum`. There might be `CrateNum`s from the previous
573     // `Session` that don't occur in the current one. For these, the mapping
574     // maps to None.
575     fn compute_cnum_map(
576         tcx: TyCtxt<'_>,
577         prev_cnums: &[(u32, StableCrateId)],
578     ) -> IndexVec<CrateNum, Option<CrateNum>> {
579         tcx.dep_graph.with_ignore(|| {
580             let current_cnums = tcx
581                 .all_crate_nums(())
582                 .iter()
583                 .map(|&cnum| {
584                     let stable_crate_id = tcx.def_path_hash(cnum.as_def_id()).stable_crate_id();
585                     (stable_crate_id, cnum)
586                 })
587                 .collect::<FxHashMap<_, _>>();
588
589             let map_size = prev_cnums.iter().map(|&(cnum, ..)| cnum).max().unwrap_or(0) + 1;
590             let mut map = IndexVec::from_elem_n(None, map_size as usize);
591
592             for &(prev_cnum, stable_crate_id) in prev_cnums {
593                 map[CrateNum::from_u32(prev_cnum)] = current_cnums.get(&stable_crate_id).cloned();
594             }
595
596             map[LOCAL_CRATE] = Some(LOCAL_CRATE);
597             map
598         })
599     }
600
601     /// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
602     /// session, if it still exists. This is used during incremental compilation to
603     /// turn a deserialized `DefPathHash` into its current `DefId`.
604     pub(crate) fn def_path_hash_to_def_id(
605         &self,
606         tcx: TyCtxt<'tcx>,
607         hash: DefPathHash,
608     ) -> Option<DefId> {
609         let mut cache = self.def_path_hash_to_def_id_cache.lock();
610         match cache.entry(hash) {
611             Entry::Occupied(e) => *e.get(),
612             Entry::Vacant(e) => {
613                 debug!("def_path_hash_to_def_id({:?})", hash);
614                 // Check if the `DefPathHash` corresponds to a definition in the current
615                 // crate
616                 if let Some(def_id) = self.local_def_path_hash_to_def_id.get(&hash).cloned() {
617                     let def_id = def_id.to_def_id();
618                     e.insert(Some(def_id));
619                     return Some(def_id);
620                 }
621                 // This `raw_def_id` represents the `DefId` of this `DefPathHash` in
622                 // the *previous* compliation session. The `DefPathHash` includes the
623                 // owning crate, so if the corresponding definition still exists in the
624                 // current compilation session, the crate is guaranteed to be the same
625                 // (otherwise, we would compute a different `DefPathHash`).
626                 let raw_def_id = self.get_raw_def_id(&hash)?;
627                 debug!("def_path_hash_to_def_id({:?}): raw_def_id = {:?}", hash, raw_def_id);
628                 // If the owning crate no longer exists, the corresponding definition definitely
629                 // no longer exists.
630                 let krate = self.try_remap_cnum(tcx, raw_def_id.krate)?;
631                 debug!("def_path_hash_to_def_id({:?}): krate = {:?}", hash, krate);
632                 // If our `DefPathHash` corresponded to a definition in the local crate,
633                 // we should have either found it in `local_def_path_hash_to_def_id`, or
634                 // never attempted to load it in the first place. Any query result or `DepNode`
635                 // that references a local `DefId` should depend on some HIR-related `DepNode`.
636                 // If a local definition is removed/modified such that its old `DefPathHash`
637                 // no longer has a corresponding definition, that HIR-related `DepNode` should
638                 // end up red. This should prevent us from ever calling
639                 // `tcx.def_path_hash_to_def_id`, since we'll end up recomputing any
640                 // queries involved.
641                 debug_assert_ne!(krate, LOCAL_CRATE);
642                 // Try to find a definition in the current session, using the previous `DefIndex`
643                 // as an initial guess.
644                 let opt_def_id = tcx.cstore.def_path_hash_to_def_id(krate, raw_def_id.index, hash);
645                 debug!("def_path_to_def_id({:?}): opt_def_id = {:?}", hash, opt_def_id);
646                 e.insert(opt_def_id);
647                 opt_def_id
648             }
649         }
650     }
651 }
652
653 //- DECODING -------------------------------------------------------------------
654
655 /// A decoder that can read from the incremental compilation cache. It is similar to the one
656 /// we use for crate metadata decoding in that it can rebase spans and eventually
657 /// will also handle things that contain `Ty` instances.
658 pub struct CacheDecoder<'a, 'tcx> {
659     tcx: TyCtxt<'tcx>,
660     opaque: opaque::Decoder<'a>,
661     source_map: &'a SourceMap,
662     cnum_map: &'a IndexVec<CrateNum, Option<CrateNum>>,
663     file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
664     file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, StableSourceFileId>,
665     alloc_decoding_session: AllocDecodingSession<'a>,
666     syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
667     expn_data: &'a FxHashMap<u32, AbsoluteBytePos>,
668     hygiene_context: &'a HygieneDecodeContext,
669 }
670
671 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
672     fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
673         let CacheDecoder {
674             ref file_index_to_file,
675             ref file_index_to_stable_id,
676             ref source_map,
677             ..
678         } = *self;
679
680         file_index_to_file
681             .borrow_mut()
682             .entry(index)
683             .or_insert_with(|| {
684                 let stable_id = file_index_to_stable_id[&index];
685                 source_map
686                     .source_file_by_stable_id(stable_id)
687                     .expect("failed to lookup `SourceFile` in new context")
688             })
689             .clone()
690     }
691 }
692
693 trait DecoderWithPosition: Decoder {
694     fn position(&self) -> usize;
695 }
696
697 impl<'a> DecoderWithPosition for opaque::Decoder<'a> {
698     fn position(&self) -> usize {
699         self.position()
700     }
701 }
702
703 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
704     fn position(&self) -> usize {
705         self.opaque.position()
706     }
707 }
708
709 // Decodes something that was encoded with `encode_tagged()` and verify that the
710 // tag matches and the correct amount of bytes was read.
711 fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> Result<V, D::Error>
712 where
713     T: Decodable<D> + Eq + std::fmt::Debug,
714     V: Decodable<D>,
715     D: DecoderWithPosition,
716 {
717     let start_pos = decoder.position();
718
719     let actual_tag = T::decode(decoder)?;
720     assert_eq!(actual_tag, expected_tag);
721     let value = V::decode(decoder)?;
722     let end_pos = decoder.position();
723
724     let expected_len: u64 = Decodable::decode(decoder)?;
725     assert_eq!((end_pos - start_pos) as u64, expected_len);
726
727     Ok(value)
728 }
729
730 impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
731     const CLEAR_CROSS_CRATE: bool = false;
732
733     #[inline]
734     fn tcx(&self) -> TyCtxt<'tcx> {
735         self.tcx
736     }
737
738     #[inline]
739     fn position(&self) -> usize {
740         self.opaque.position()
741     }
742
743     #[inline]
744     fn peek_byte(&self) -> u8 {
745         self.opaque.data[self.opaque.position()]
746     }
747
748     fn cached_ty_for_shorthand<F>(
749         &mut self,
750         shorthand: usize,
751         or_insert_with: F,
752     ) -> Result<Ty<'tcx>, Self::Error>
753     where
754         F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
755     {
756         let tcx = self.tcx();
757
758         let cache_key = ty::CReaderCacheKey { cnum: None, pos: shorthand };
759
760         if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
761             return Ok(ty);
762         }
763
764         let ty = or_insert_with(self)?;
765         // This may overwrite the entry, but it should overwrite with the same value.
766         tcx.ty_rcache.borrow_mut().insert_same(cache_key, ty);
767         Ok(ty)
768     }
769
770     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
771     where
772         F: FnOnce(&mut Self) -> R,
773     {
774         debug_assert!(pos < self.opaque.data.len());
775
776         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
777         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
778         let r = f(self);
779         self.opaque = old_opaque;
780         r
781     }
782
783     fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
784         self.cnum_map[cnum].unwrap_or_else(|| bug!("could not find new `CrateNum` for {:?}", cnum))
785     }
786
787     fn decode_alloc_id(&mut self) -> Result<interpret::AllocId, Self::Error> {
788         let alloc_decoding_session = self.alloc_decoding_session;
789         alloc_decoding_session.decode_alloc_id(self)
790     }
791 }
792
793 crate::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
794
795 // This ensures that the `Decodable<opaque::Decoder>::decode` specialization for `Vec<u8>` is used
796 // when a `CacheDecoder` is passed to `Decodable::decode`. Unfortunately, we have to manually opt
797 // into specializations this way, given how `CacheDecoder` and the decoding traits currently work.
798 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Vec<u8> {
799     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
800         Decodable::decode(&mut d.opaque)
801     }
802 }
803
804 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for SyntaxContext {
805     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
806         let syntax_contexts = decoder.syntax_contexts;
807         rustc_span::hygiene::decode_syntax_context(decoder, decoder.hygiene_context, |this, id| {
808             // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
809             // We look up the position of the associated `SyntaxData` and decode it.
810             let pos = syntax_contexts.get(&id).unwrap();
811             this.with_position(pos.to_usize(), |decoder| {
812                 let data: SyntaxContextData = decode_tagged(decoder, TAG_SYNTAX_CONTEXT)?;
813                 Ok(data)
814             })
815         })
816     }
817 }
818
819 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for ExpnId {
820     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
821         let expn_data = decoder.expn_data;
822         rustc_span::hygiene::decode_expn_id(
823             decoder,
824             ExpnDataDecodeMode::incr_comp(decoder.hygiene_context),
825             |this, index| {
826                 // This closure is invoked if we haven't already decoded the data for the `ExpnId` we are deserializing.
827                 // We look up the position of the associated `ExpnData` and decode it.
828                 let pos = expn_data
829                     .get(&index)
830                     .unwrap_or_else(|| panic!("Bad index {:?} (map {:?})", index, expn_data));
831
832                 this.with_position(pos.to_usize(), |decoder| {
833                     let data: ExpnData = decode_tagged(decoder, TAG_EXPN_DATA)?;
834                     Ok(data)
835                 })
836             },
837         )
838     }
839 }
840
841 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Span {
842     fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
843         let tag: u8 = Decodable::decode(decoder)?;
844
845         if tag == TAG_PARTIAL_SPAN {
846             let ctxt = SyntaxContext::decode(decoder)?;
847             return Ok(DUMMY_SP.with_ctxt(ctxt));
848         } else {
849             debug_assert_eq!(tag, TAG_FULL_SPAN);
850         }
851
852         let file_lo_index = SourceFileIndex::decode(decoder)?;
853         let line_lo = usize::decode(decoder)?;
854         let col_lo = BytePos::decode(decoder)?;
855         let len = BytePos::decode(decoder)?;
856         let ctxt = SyntaxContext::decode(decoder)?;
857
858         let file_lo = decoder.file_index_to_file(file_lo_index);
859         let lo = file_lo.lines[line_lo - 1] + col_lo;
860         let hi = lo + len;
861
862         Ok(Span::new(lo, hi, ctxt))
863     }
864 }
865
866 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for CrateNum {
867     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
868         let cnum = CrateNum::from_u32(u32::decode(d)?);
869         Ok(d.map_encoded_cnum_to_current(cnum))
870     }
871 }
872
873 // This impl makes sure that we get a runtime error when we try decode a
874 // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
875 // because we would not know how to transform the `DefIndex` to the current
876 // context.
877 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefIndex {
878     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<DefIndex, String> {
879         Err(d.error("trying to decode `DefIndex` outside the context of a `DefId`"))
880     }
881 }
882
883 // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
884 // compilation sessions. We use the `DefPathHash`, which is stable across
885 // sessions, to map the old `DefId` to the new one.
886 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefId {
887     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
888         // Load the `DefPathHash` which is was we encoded the `DefId` as.
889         let def_path_hash = DefPathHash::decode(d)?;
890
891         // Using the `DefPathHash`, we can lookup the new `DefId`.
892         // Subtle: We only encode a `DefId` as part of a query result.
893         // If we get to this point, then all of the query inputs were green,
894         // which means that the definition with this hash is guaranteed to
895         // still exist in the current compilation session.
896         Ok(d.tcx()
897             .on_disk_cache
898             .as_ref()
899             .unwrap()
900             .def_path_hash_to_def_id(d.tcx(), def_path_hash)
901             .unwrap())
902     }
903 }
904
905 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx FxHashSet<LocalDefId> {
906     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
907         RefDecodable::decode(d)
908     }
909 }
910
911 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
912     for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
913 {
914     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
915         RefDecodable::decode(d)
916     }
917 }
918
919 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] {
920     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
921         RefDecodable::decode(d)
922     }
923 }
924
925 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
926     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
927         RefDecodable::decode(d)
928     }
929 }
930
931 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_ast::InlineAsmTemplatePiece] {
932     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
933         RefDecodable::decode(d)
934     }
935 }
936
937 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Span] {
938     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
939         RefDecodable::decode(d)
940     }
941 }
942
943 //- ENCODING -------------------------------------------------------------------
944
945 pub trait OpaqueEncoder: Encoder {
946     fn position(&self) -> usize;
947 }
948
949 impl OpaqueEncoder for FileEncoder {
950     #[inline]
951     fn position(&self) -> usize {
952         FileEncoder::position(self)
953     }
954 }
955
956 /// An encoder that can write to the incremental compilation cache.
957 pub struct CacheEncoder<'a, 'tcx, E: OpaqueEncoder> {
958     tcx: TyCtxt<'tcx>,
959     encoder: &'a mut E,
960     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
961     predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
962     interpret_allocs: FxIndexSet<interpret::AllocId>,
963     source_map: CachingSourceMapView<'tcx>,
964     file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
965     hygiene_context: &'a HygieneEncodeContext,
966     latest_foreign_def_path_hashes: UnhashMap<DefPathHash, RawDefId>,
967 }
968
969 impl<'a, 'tcx, E> CacheEncoder<'a, 'tcx, E>
970 where
971     E: 'a + OpaqueEncoder,
972 {
973     fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
974         self.file_to_file_index[&(&*source_file as *const SourceFile)]
975     }
976
977     /// Encode something with additional information that allows to do some
978     /// sanity checks when decoding the data again. This method will first
979     /// encode the specified tag, then the given value, then the number of
980     /// bytes taken up by tag and value. On decoding, we can then verify that
981     /// we get the expected tag and read the expected number of bytes.
982     fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(
983         &mut self,
984         tag: T,
985         value: &V,
986     ) -> Result<(), E::Error> {
987         let start_pos = self.position();
988
989         tag.encode(self)?;
990         value.encode(self)?;
991
992         let end_pos = self.position();
993         ((end_pos - start_pos) as u64).encode(self)
994     }
995 }
996
997 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for SyntaxContext
998 where
999     E: 'a + OpaqueEncoder,
1000 {
1001     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1002         rustc_span::hygiene::raw_encode_syntax_context(*self, s.hygiene_context, s)
1003     }
1004 }
1005
1006 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for ExpnId
1007 where
1008     E: 'a + OpaqueEncoder,
1009 {
1010     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1011         rustc_span::hygiene::raw_encode_expn_id(
1012             *self,
1013             s.hygiene_context,
1014             ExpnDataEncodeMode::IncrComp,
1015             s,
1016         )
1017     }
1018 }
1019
1020 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for Span
1021 where
1022     E: 'a + OpaqueEncoder,
1023 {
1024     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1025         let span_data = self.data();
1026         if self.is_dummy() {
1027             TAG_PARTIAL_SPAN.encode(s)?;
1028             return span_data.ctxt.encode(s);
1029         }
1030
1031         let pos = s.source_map.byte_pos_to_line_and_col(span_data.lo);
1032         let partial_span = match &pos {
1033             Some((file_lo, _, _)) => !file_lo.contains(span_data.hi),
1034             None => true,
1035         };
1036
1037         if partial_span {
1038             TAG_PARTIAL_SPAN.encode(s)?;
1039             return span_data.ctxt.encode(s);
1040         }
1041
1042         let (file_lo, line_lo, col_lo) = pos.unwrap();
1043
1044         let len = span_data.hi - span_data.lo;
1045
1046         let source_file_index = s.source_file_index(file_lo);
1047
1048         TAG_FULL_SPAN.encode(s)?;
1049         source_file_index.encode(s)?;
1050         line_lo.encode(s)?;
1051         col_lo.encode(s)?;
1052         len.encode(s)?;
1053         span_data.ctxt.encode(s)
1054     }
1055 }
1056
1057 impl<'a, 'tcx, E> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx, E>
1058 where
1059     E: 'a + OpaqueEncoder,
1060 {
1061     const CLEAR_CROSS_CRATE: bool = false;
1062
1063     fn position(&self) -> usize {
1064         self.encoder.position()
1065     }
1066     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
1067         &mut self.type_shorthands
1068     }
1069     fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
1070         &mut self.predicate_shorthands
1071     }
1072     fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
1073         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
1074
1075         index.encode(self)
1076     }
1077 }
1078
1079 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefId
1080 where
1081     E: 'a + OpaqueEncoder,
1082 {
1083     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1084         let def_path_hash = s.tcx.def_path_hash(*self);
1085         // Store additional information when we encode a foreign `DefId`,
1086         // so that we can map its `DefPathHash` back to a `DefId` in the next
1087         // compilation session.
1088         if !self.is_local() {
1089             s.latest_foreign_def_path_hashes.insert(
1090                 def_path_hash,
1091                 RawDefId { krate: self.krate.as_u32(), index: self.index.as_u32() },
1092             );
1093         }
1094         def_path_hash.encode(s)
1095     }
1096 }
1097
1098 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefIndex
1099 where
1100     E: 'a + OpaqueEncoder,
1101 {
1102     fn encode(&self, _: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1103         bug!("encoding `DefIndex` without context");
1104     }
1105 }
1106
1107 macro_rules! encoder_methods {
1108     ($($name:ident($ty:ty);)*) => {
1109         #[inline]
1110         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
1111             self.encoder.$name(value)
1112         })*
1113     }
1114 }
1115
1116 impl<'a, 'tcx, E> Encoder for CacheEncoder<'a, 'tcx, E>
1117 where
1118     E: 'a + OpaqueEncoder,
1119 {
1120     type Error = E::Error;
1121
1122     #[inline]
1123     fn emit_unit(&mut self) -> Result<(), Self::Error> {
1124         Ok(())
1125     }
1126
1127     encoder_methods! {
1128         emit_usize(usize);
1129         emit_u128(u128);
1130         emit_u64(u64);
1131         emit_u32(u32);
1132         emit_u16(u16);
1133         emit_u8(u8);
1134
1135         emit_isize(isize);
1136         emit_i128(i128);
1137         emit_i64(i64);
1138         emit_i32(i32);
1139         emit_i16(i16);
1140         emit_i8(i8);
1141
1142         emit_bool(bool);
1143         emit_f64(f64);
1144         emit_f32(f32);
1145         emit_char(char);
1146         emit_str(&str);
1147         emit_raw_bytes(&[u8]);
1148     }
1149 }
1150
1151 // This ensures that the `Encodable<opaque::FileEncoder>::encode` specialization for byte slices
1152 // is used when a `CacheEncoder` having an `opaque::FileEncoder` is passed to `Encodable::encode`.
1153 // Unfortunately, we have to manually opt into specializations this way, given how `CacheEncoder`
1154 // and the encoding traits currently work.
1155 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx, FileEncoder>> for [u8] {
1156     fn encode(&self, e: &mut CacheEncoder<'a, 'tcx, FileEncoder>) -> FileEncodeResult {
1157         self.encode(e.encoder)
1158     }
1159 }
1160
1161 pub fn encode_query_results<'a, 'tcx, CTX, Q>(
1162     tcx: CTX,
1163     encoder: &mut CacheEncoder<'a, 'tcx, FileEncoder>,
1164     query_result_index: &mut EncodedQueryResultIndex,
1165 ) -> FileEncodeResult
1166 where
1167     CTX: QueryContext + 'tcx,
1168     Q: super::QueryDescription<CTX> + super::QueryAccessors<CTX>,
1169     Q::Value: Encodable<CacheEncoder<'a, 'tcx, FileEncoder>>,
1170 {
1171     let _timer = tcx
1172         .dep_context()
1173         .profiler()
1174         .extra_verbose_generic_activity("encode_query_results_for", std::any::type_name::<Q>());
1175
1176     assert!(Q::query_state(tcx).all_inactive());
1177     let cache = Q::query_cache(tcx);
1178     let mut res = Ok(());
1179     cache.iter_results(&mut |key, value, dep_node| {
1180         if res.is_err() {
1181             return;
1182         }
1183         if Q::cache_on_disk(tcx, &key, Some(value)) {
1184             let dep_node = SerializedDepNodeIndex::new(dep_node.index());
1185
1186             // Record position of the cache entry.
1187             query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.encoder.position())));
1188
1189             // Encode the type check tables with the `SerializedDepNodeIndex`
1190             // as tag.
1191             match encoder.encode_tagged(dep_node, value) {
1192                 Ok(()) => {}
1193                 Err(e) => {
1194                     res = Err(e);
1195                 }
1196             }
1197         }
1198     });
1199
1200     res
1201 }