2 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
3 use rustc_data_structures::memmap::Mmap;
4 use rustc_data_structures::sync::{HashMapExt, Lock, Lrc, RwLock};
5 use rustc_data_structures::unhash::UnhashMap;
6 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, StableCrateId, LOCAL_CRATE};
7 use rustc_hir::definitions::DefPathHash;
8 use rustc_index::vec::{Idx, IndexVec};
9 use rustc_middle::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
10 use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
11 use rustc_middle::mir::{self, interpret};
12 use rustc_middle::thir;
13 use rustc_middle::ty::codec::{RefDecodable, TyDecoder, TyEncoder};
14 use rustc_middle::ty::{self, Ty, TyCtxt};
15 use rustc_query_system::dep_graph::DepContext;
16 use rustc_query_system::query::{QueryContext, QuerySideEffects};
17 use rustc_serialize::{
18 opaque::{self, FileEncodeResult, FileEncoder, IntEncodedWithFixedSize},
19 Decodable, Decoder, Encodable, Encoder,
21 use rustc_session::Session;
22 use rustc_span::hygiene::{
23 ExpnId, HygieneDecodeContext, HygieneEncodeContext, SyntaxContext, SyntaxContextData,
25 use rustc_span::source_map::{SourceMap, StableSourceFileId};
26 use rustc_span::CachingSourceMapView;
27 use rustc_span::{BytePos, ExpnData, ExpnHash, Pos, SourceFile, Span};
30 const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
32 // A normal span encoded with both location information and a `SyntaxContext`
33 const TAG_FULL_SPAN: u8 = 0;
34 // A partial span with no location information, encoded only with a `SyntaxContext`
35 const TAG_PARTIAL_SPAN: u8 = 1;
36 const TAG_RELATIVE_SPAN: u8 = 2;
38 const TAG_SYNTAX_CONTEXT: u8 = 0;
39 const TAG_EXPN_DATA: u8 = 1;
41 /// Provides an interface to incremental compilation data cached from the
42 /// previous compilation session. This data will eventually include the results
43 /// of a few selected queries (like `typeck` and `mir_optimized`) and
44 /// any side effects that have been emitted during a query.
45 pub struct OnDiskCache<'sess> {
46 // The complete cache data in serialized form.
47 serialized_data: RwLock<Option<Mmap>>,
49 // Collects all `QuerySideEffects` created during the current compilation
51 current_side_effects: Lock<FxHashMap<DepNodeIndex, QuerySideEffects>>,
53 source_map: &'sess SourceMap,
54 file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
56 // Caches that are populated lazily during decoding.
57 file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
59 // A map from dep-node to the position of the cached query result in
61 query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
63 // A map from dep-node to the position of any associated `QuerySideEffects` in
65 prev_side_effects_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
67 alloc_decoding_state: AllocDecodingState,
69 // A map from syntax context ids to the position of their associated
70 // `SyntaxContextData`. We use a `u32` instead of a `SyntaxContext`
71 // to represent the fact that we are storing *encoded* ids. When we decode
72 // a `SyntaxContext`, a new id will be allocated from the global `HygieneData`,
73 // which will almost certainly be different than the serialized id.
74 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
75 // A map from the `DefPathHash` of an `ExpnId` to the position
76 // of their associated `ExpnData`. Ideally, we would store a `DefId`,
77 // but we need to decode this before we've constructed a `TyCtxt` (which
78 // makes it difficult to decode a `DefId`).
80 // Note that these `DefPathHashes` correspond to both local and foreign
81 // `ExpnData` (e.g `ExpnData.krate` may not be `LOCAL_CRATE`). Alternatively,
82 // we could look up the `ExpnData` from the metadata of foreign crates,
83 // but it seemed easier to have `OnDiskCache` be independent of the `CStore`.
84 expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
85 // Additional information used when decoding hygiene data.
86 hygiene_context: HygieneDecodeContext,
87 // Maps `ExpnHash`es to their raw value from the *previous*
88 // compilation session. This is used as an initial 'guess' when
89 // we try to map an `ExpnHash` to its value in the current
90 // compilation session.
91 foreign_expn_data: UnhashMap<ExpnHash, u32>,
94 // This type is used only for serialization and deserialization.
95 #[derive(Encodable, Decodable)]
97 file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
98 query_result_index: EncodedDepNodeIndex,
99 side_effects_index: EncodedDepNodeIndex,
100 // The location of all allocations.
101 interpret_alloc_index: Vec<u32>,
102 // See `OnDiskCache.syntax_contexts`
103 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
104 // See `OnDiskCache.expn_data`
105 expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
106 foreign_expn_data: UnhashMap<ExpnHash, u32>,
109 pub type EncodedDepNodeIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
111 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
112 struct SourceFileIndex(u32);
114 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Encodable, Decodable)]
115 pub struct AbsoluteBytePos(u32);
117 impl AbsoluteBytePos {
118 fn new(pos: usize) -> AbsoluteBytePos {
119 debug_assert!(pos <= u32::MAX as usize);
120 AbsoluteBytePos(pos as u32)
123 fn to_usize(self) -> usize {
128 /// An `EncodedSourceFileId` is the same as a `StableSourceFileId` except that
129 /// the source crate is represented as a [StableCrateId] instead of as a
130 /// `CrateNum`. This way `EncodedSourceFileId` can be encoded and decoded
131 /// without any additional context, i.e. with a simple `opaque::Decoder` (which
132 /// is the only thing available when decoding the cache's [Footer].
133 #[derive(Encodable, Decodable, Clone, Debug)]
134 struct EncodedSourceFileId {
136 stable_crate_id: StableCrateId,
139 impl EncodedSourceFileId {
140 fn translate(&self, tcx: TyCtxt<'_>) -> StableSourceFileId {
141 let cnum = tcx.stable_crate_id_to_crate_num(self.stable_crate_id);
142 StableSourceFileId { file_name_hash: self.file_name_hash, cnum }
145 fn new(tcx: TyCtxt<'_>, file: &SourceFile) -> EncodedSourceFileId {
146 let source_file_id = StableSourceFileId::new(file);
147 EncodedSourceFileId {
148 file_name_hash: source_file_id.file_name_hash,
149 stable_crate_id: tcx.stable_crate_id(source_file_id.cnum),
154 impl<'sess> rustc_middle::ty::OnDiskCache<'sess> for OnDiskCache<'sess> {
155 /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
156 fn new(sess: &'sess Session, data: Mmap, start_pos: usize) -> Self {
157 debug_assert!(sess.opts.incremental.is_some());
159 // Wrap in a scope so we can borrow `data`.
160 let footer: Footer = {
161 let mut decoder = opaque::Decoder::new(&data[..], start_pos);
163 // Decode the *position* of the footer, which can be found in the
164 // last 8 bytes of the file.
165 decoder.set_position(data.len() - IntEncodedWithFixedSize::ENCODED_SIZE);
166 let footer_pos = IntEncodedWithFixedSize::decode(&mut decoder)
167 .expect("error while trying to decode footer position")
170 // Decode the file footer, which contains all the lookup tables, etc.
171 decoder.set_position(footer_pos);
173 decode_tagged(&mut decoder, TAG_FILE_FOOTER)
174 .expect("error while trying to decode footer position")
178 serialized_data: RwLock::new(Some(data)),
179 file_index_to_stable_id: footer.file_index_to_stable_id,
180 file_index_to_file: Default::default(),
181 source_map: sess.source_map(),
182 current_side_effects: Default::default(),
183 query_result_index: footer.query_result_index.into_iter().collect(),
184 prev_side_effects_index: footer.side_effects_index.into_iter().collect(),
185 alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
186 syntax_contexts: footer.syntax_contexts,
187 expn_data: footer.expn_data,
188 foreign_expn_data: footer.foreign_expn_data,
189 hygiene_context: Default::default(),
193 fn new_empty(source_map: &'sess SourceMap) -> Self {
195 serialized_data: RwLock::new(None),
196 file_index_to_stable_id: Default::default(),
197 file_index_to_file: Default::default(),
199 current_side_effects: Default::default(),
200 query_result_index: Default::default(),
201 prev_side_effects_index: Default::default(),
202 alloc_decoding_state: AllocDecodingState::new(Vec::new()),
203 syntax_contexts: FxHashMap::default(),
204 expn_data: UnhashMap::default(),
205 foreign_expn_data: UnhashMap::default(),
206 hygiene_context: Default::default(),
210 /// Execute all cache promotions and release the serialized backing Mmap.
212 /// Cache promotions require invoking queries, which needs to read the serialized data.
213 /// In order to serialize the new on-disk cache, the former on-disk cache file needs to be
214 /// deleted, hence we won't be able to refer to its memmapped data.
215 fn drop_serialized_data(&self, tcx: TyCtxt<'tcx>) {
216 // Load everything into memory so we can write it out to the on-disk
217 // cache. The vast majority of cacheable query results should already
218 // be in memory, so this should be a cheap operation.
219 // Do this *before* we clone 'latest_foreign_def_path_hashes', since
220 // loading existing queries may cause us to create new DepNodes, which
221 // may in turn end up invoking `store_foreign_def_id_hash`
222 tcx.dep_graph.exec_cache_promotions(QueryCtxt::from_tcx(tcx));
224 *self.serialized_data.write() = None;
227 fn serialize<'tcx>(&self, tcx: TyCtxt<'tcx>, encoder: &mut FileEncoder) -> FileEncodeResult {
228 // Serializing the `DepGraph` should not modify it.
229 tcx.dep_graph.with_ignore(|| {
230 // Allocate `SourceFileIndex`es.
231 let (file_to_file_index, file_index_to_stable_id) = {
232 let files = tcx.sess.source_map().files();
233 let mut file_to_file_index =
234 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
235 let mut file_index_to_stable_id =
236 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
238 for (index, file) in files.iter().enumerate() {
239 let index = SourceFileIndex(index as u32);
240 let file_ptr: *const SourceFile = &**file as *const _;
241 file_to_file_index.insert(file_ptr, index);
242 let source_file_id = EncodedSourceFileId::new(tcx, &file);
243 file_index_to_stable_id.insert(index, source_file_id);
246 (file_to_file_index, file_index_to_stable_id)
249 let hygiene_encode_context = HygieneEncodeContext::default();
251 let mut encoder = CacheEncoder {
254 type_shorthands: Default::default(),
255 predicate_shorthands: Default::default(),
256 interpret_allocs: Default::default(),
257 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
259 hygiene_context: &hygiene_encode_context,
262 // Encode query results.
263 let mut query_result_index = EncodedDepNodeIndex::new();
265 tcx.sess.time("encode_query_results", || -> FileEncodeResult {
266 let enc = &mut encoder;
267 let qri = &mut query_result_index;
268 QueryCtxt::from_tcx(tcx).encode_query_results(enc, qri)
271 // Encode side effects.
272 let side_effects_index: EncodedDepNodeIndex = self
273 .current_side_effects
277 |(dep_node_index, side_effects)| -> Result<_, <FileEncoder as Encoder>::Error> {
278 let pos = AbsoluteBytePos::new(encoder.position());
279 let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
280 encoder.encode_tagged(dep_node_index, side_effects)?;
282 Ok((dep_node_index, pos))
285 .collect::<Result<_, _>>()?;
287 let interpret_alloc_index = {
288 let mut interpret_alloc_index = Vec::new();
291 let new_n = encoder.interpret_allocs.len();
292 // If we have found new IDs, serialize those too.
297 interpret_alloc_index.reserve(new_n - n);
298 for idx in n..new_n {
299 let id = encoder.interpret_allocs[idx];
300 let pos = encoder.position() as u32;
301 interpret_alloc_index.push(pos);
302 interpret::specialized_encode_alloc_id(&mut encoder, tcx, id)?;
306 interpret_alloc_index
309 let mut syntax_contexts = FxHashMap::default();
310 let mut expn_data = UnhashMap::default();
311 let mut foreign_expn_data = UnhashMap::default();
313 // Encode all hygiene data (`SyntaxContextData` and `ExpnData`) from the current
316 hygiene_encode_context.encode(
318 |encoder, index, ctxt_data| -> FileEncodeResult {
319 let pos = AbsoluteBytePos::new(encoder.position());
320 encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data)?;
321 syntax_contexts.insert(index, pos);
324 |encoder, expn_id, data, hash| -> FileEncodeResult {
325 if expn_id.krate == LOCAL_CRATE {
326 let pos = AbsoluteBytePos::new(encoder.position());
327 encoder.encode_tagged(TAG_EXPN_DATA, data)?;
328 expn_data.insert(hash, pos);
330 foreign_expn_data.insert(hash, expn_id.local_id.as_u32());
336 // `Encode the file footer.
337 let footer_pos = encoder.position() as u64;
338 encoder.encode_tagged(
341 file_index_to_stable_id,
344 interpret_alloc_index,
351 // Encode the position of the footer as the last 8 bytes of the
352 // file so we know where to look for it.
353 IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder)?;
355 // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
356 // of the footer must be the last thing in the data stream.
362 fn def_path_hash_to_def_id(&self, tcx: TyCtxt<'tcx>, hash: DefPathHash) -> DefId {
363 debug!("def_path_hash_to_def_id({:?})", hash);
365 let stable_crate_id = hash.stable_crate_id();
367 // If this is a DefPathHash from the local crate, we can look up the
368 // DefId in the tcx's `Definitions`.
369 if stable_crate_id == tcx.sess.local_stable_crate_id() {
370 tcx.definitions_untracked().local_def_path_hash_to_def_id(hash).to_def_id()
372 // If this is a DefPathHash from an upstream crate, let the CrateStore map
374 let cnum = tcx.cstore_untracked().stable_crate_id_to_crate_num(stable_crate_id);
375 tcx.cstore_untracked().def_path_hash_to_def_id(cnum, hash)
380 impl<'sess> OnDiskCache<'sess> {
381 pub fn as_dyn(&self) -> &dyn rustc_middle::ty::OnDiskCache<'sess> {
385 /// Loads a `QuerySideEffects` created during the previous compilation session.
386 pub fn load_side_effects(
389 dep_node_index: SerializedDepNodeIndex,
390 ) -> QuerySideEffects {
391 let side_effects: Option<QuerySideEffects> =
392 self.load_indexed(tcx, dep_node_index, &self.prev_side_effects_index, "side_effects");
394 side_effects.unwrap_or_default()
397 /// Stores a `QuerySideEffects` emitted during the current compilation session.
398 /// Anything stored like this will be available via `load_side_effects` in
399 /// the next compilation session.
402 pub fn store_side_effects(&self, dep_node_index: DepNodeIndex, side_effects: QuerySideEffects) {
403 let mut current_side_effects = self.current_side_effects.borrow_mut();
404 let prev = current_side_effects.insert(dep_node_index, side_effects);
405 debug_assert!(prev.is_none());
408 /// Returns the cached query result if there is something in the cache for
409 /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
410 pub fn try_load_query_result<'tcx, T>(
413 dep_node_index: SerializedDepNodeIndex,
416 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
418 self.load_indexed(tcx, dep_node_index, &self.query_result_index, "query result")
421 /// Stores side effect emitted during computation of an anonymous query.
422 /// Since many anonymous queries can share the same `DepNode`, we aggregate
423 /// them -- as opposed to regular queries where we assume that there is a
424 /// 1:1 relationship between query-key and `DepNode`.
427 pub fn store_side_effects_for_anon_node(
429 dep_node_index: DepNodeIndex,
430 side_effects: QuerySideEffects,
432 let mut current_side_effects = self.current_side_effects.borrow_mut();
434 let x = current_side_effects.entry(dep_node_index).or_default();
435 x.append(side_effects);
438 fn load_indexed<'tcx, T>(
441 dep_node_index: SerializedDepNodeIndex,
442 index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
443 debug_tag: &'static str,
446 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
448 let pos = index.get(&dep_node_index).cloned()?;
450 self.with_decoder(tcx, pos, |decoder| match decode_tagged(decoder, dep_node_index) {
452 Err(e) => bug!("could not decode cached {}: {}", debug_tag, e),
456 fn with_decoder<'a, 'tcx, T, F: for<'s> FnOnce(&mut CacheDecoder<'s, 'tcx>) -> T>(
459 pos: AbsoluteBytePos,
463 T: Decodable<CacheDecoder<'a, 'tcx>>,
465 let serialized_data = self.serialized_data.read();
466 let mut decoder = CacheDecoder {
468 opaque: opaque::Decoder::new(serialized_data.as_deref().unwrap_or(&[]), pos.to_usize()),
469 source_map: self.source_map,
470 file_index_to_file: &self.file_index_to_file,
471 file_index_to_stable_id: &self.file_index_to_stable_id,
472 alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
473 syntax_contexts: &self.syntax_contexts,
474 expn_data: &self.expn_data,
475 foreign_expn_data: &self.foreign_expn_data,
476 hygiene_context: &self.hygiene_context,
482 //- DECODING -------------------------------------------------------------------
484 /// A decoder that can read from the incremental compilation cache. It is similar to the one
485 /// we use for crate metadata decoding in that it can rebase spans and eventually
486 /// will also handle things that contain `Ty` instances.
487 pub struct CacheDecoder<'a, 'tcx> {
489 opaque: opaque::Decoder<'a>,
490 source_map: &'a SourceMap,
491 file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
492 file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, EncodedSourceFileId>,
493 alloc_decoding_session: AllocDecodingSession<'a>,
494 syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
495 expn_data: &'a UnhashMap<ExpnHash, AbsoluteBytePos>,
496 foreign_expn_data: &'a UnhashMap<ExpnHash, u32>,
497 hygiene_context: &'a HygieneDecodeContext,
500 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
501 fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
504 ref file_index_to_file,
505 ref file_index_to_stable_id,
514 let stable_id = file_index_to_stable_id[&index].translate(tcx);
516 .source_file_by_stable_id(stable_id)
517 .expect("failed to lookup `SourceFile` in new context")
523 trait DecoderWithPosition: Decoder {
524 fn position(&self) -> usize;
527 impl<'a> DecoderWithPosition for opaque::Decoder<'a> {
528 fn position(&self) -> usize {
533 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
534 fn position(&self) -> usize {
535 self.opaque.position()
539 // Decodes something that was encoded with `encode_tagged()` and verify that the
540 // tag matches and the correct amount of bytes was read.
541 fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> Result<V, D::Error>
543 T: Decodable<D> + Eq + std::fmt::Debug,
545 D: DecoderWithPosition,
547 let start_pos = decoder.position();
549 let actual_tag = T::decode(decoder)?;
550 assert_eq!(actual_tag, expected_tag);
551 let value = V::decode(decoder)?;
552 let end_pos = decoder.position();
554 let expected_len: u64 = Decodable::decode(decoder)?;
555 assert_eq!((end_pos - start_pos) as u64, expected_len);
560 impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
561 const CLEAR_CROSS_CRATE: bool = false;
564 fn tcx(&self) -> TyCtxt<'tcx> {
569 fn position(&self) -> usize {
570 self.opaque.position()
574 fn peek_byte(&self) -> u8 {
575 self.opaque.data[self.opaque.position()]
578 fn cached_ty_for_shorthand<F>(
582 ) -> Result<Ty<'tcx>, Self::Error>
584 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
586 let tcx = self.tcx();
588 let cache_key = ty::CReaderCacheKey { cnum: None, pos: shorthand };
590 if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
594 let ty = or_insert_with(self)?;
595 // This may overwrite the entry, but it should overwrite with the same value.
596 tcx.ty_rcache.borrow_mut().insert_same(cache_key, ty);
600 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
602 F: FnOnce(&mut Self) -> R,
604 debug_assert!(pos < self.opaque.data.len());
606 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
607 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
609 self.opaque = old_opaque;
613 fn decode_alloc_id(&mut self) -> Result<interpret::AllocId, Self::Error> {
614 let alloc_decoding_session = self.alloc_decoding_session;
615 alloc_decoding_session.decode_alloc_id(self)
619 rustc_middle::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
621 // This ensures that the `Decodable<opaque::Decoder>::decode` specialization for `Vec<u8>` is used
622 // when a `CacheDecoder` is passed to `Decodable::decode`. Unfortunately, we have to manually opt
623 // into specializations this way, given how `CacheDecoder` and the decoding traits currently work.
624 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Vec<u8> {
625 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
626 Decodable::decode(&mut d.opaque)
630 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for SyntaxContext {
631 fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
632 let syntax_contexts = decoder.syntax_contexts;
633 rustc_span::hygiene::decode_syntax_context(decoder, decoder.hygiene_context, |this, id| {
634 // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
635 // We look up the position of the associated `SyntaxData` and decode it.
636 let pos = syntax_contexts.get(&id).unwrap();
637 this.with_position(pos.to_usize(), |decoder| {
638 let data: SyntaxContextData = decode_tagged(decoder, TAG_SYNTAX_CONTEXT)?;
645 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for ExpnId {
646 fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
647 let hash = ExpnHash::decode(decoder)?;
649 return Ok(ExpnId::root());
652 if let Some(expn_id) = ExpnId::from_hash(hash) {
656 let krate = decoder.tcx.stable_crate_id_to_crate_num(hash.stable_crate_id());
658 let expn_id = if krate == LOCAL_CRATE {
659 // We look up the position of the associated `ExpnData` and decode it.
663 .unwrap_or_else(|| panic!("Bad hash {:?} (map {:?})", hash, decoder.expn_data));
665 let data: ExpnData = decoder
666 .with_position(pos.to_usize(), |decoder| decode_tagged(decoder, TAG_EXPN_DATA))?;
667 let expn_id = rustc_span::hygiene::register_local_expn_id(data, hash);
669 #[cfg(debug_assertions)]
671 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
672 let mut hcx = decoder.tcx.create_stable_hashing_context();
673 let mut hasher = StableHasher::new();
674 hcx.while_hashing_spans(true, |hcx| {
675 expn_id.expn_data().hash_stable(hcx, &mut hasher)
677 let local_hash: u64 = hasher.finish();
678 debug_assert_eq!(hash.local_hash(), local_hash);
683 let index_guess = decoder.foreign_expn_data[&hash];
684 decoder.tcx.cstore_untracked().expn_hash_to_expn_id(
692 debug_assert_eq!(expn_id.krate, krate);
697 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Span {
698 fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
699 let ctxt = SyntaxContext::decode(decoder)?;
700 let parent = Option::<LocalDefId>::decode(decoder)?;
701 let tag: u8 = Decodable::decode(decoder)?;
703 if tag == TAG_PARTIAL_SPAN {
704 return Ok(Span::new(BytePos(0), BytePos(0), ctxt, parent));
705 } else if tag == TAG_RELATIVE_SPAN {
706 let dlo = u32::decode(decoder)?;
707 let dto = u32::decode(decoder)?;
710 decoder.tcx.definitions_untracked().def_span(parent.unwrap()).data_untracked();
711 let span = Span::new(
712 enclosing.lo + BytePos::from_u32(dlo),
713 enclosing.lo + BytePos::from_u32(dto),
720 debug_assert_eq!(tag, TAG_FULL_SPAN);
723 let file_lo_index = SourceFileIndex::decode(decoder)?;
724 let line_lo = usize::decode(decoder)?;
725 let col_lo = BytePos::decode(decoder)?;
726 let len = BytePos::decode(decoder)?;
728 let file_lo = decoder.file_index_to_file(file_lo_index);
729 let lo = file_lo.lines[line_lo - 1] + col_lo;
732 Ok(Span::new(lo, hi, ctxt, parent))
736 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for CrateNum {
737 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
738 let stable_id = StableCrateId::decode(d)?;
739 let cnum = d.tcx.stable_crate_id_to_crate_num(stable_id);
744 // This impl makes sure that we get a runtime error when we try decode a
745 // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
746 // because we would not know how to transform the `DefIndex` to the current
748 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefIndex {
749 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<DefIndex, String> {
750 Err(d.error("trying to decode `DefIndex` outside the context of a `DefId`"))
754 // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
755 // compilation sessions. We use the `DefPathHash`, which is stable across
756 // sessions, to map the old `DefId` to the new one.
757 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefId {
758 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
759 // Load the `DefPathHash` which is was we encoded the `DefId` as.
760 let def_path_hash = DefPathHash::decode(d)?;
762 // Using the `DefPathHash`, we can lookup the new `DefId`.
763 // Subtle: We only encode a `DefId` as part of a query result.
764 // If we get to this point, then all of the query inputs were green,
765 // which means that the definition with this hash is guaranteed to
766 // still exist in the current compilation session.
767 Ok(d.tcx().on_disk_cache.as_ref().unwrap().def_path_hash_to_def_id(d.tcx(), def_path_hash))
771 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx FxHashSet<LocalDefId> {
772 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
773 RefDecodable::decode(d)
777 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
778 for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
780 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
781 RefDecodable::decode(d)
785 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [thir::abstract_const::Node<'tcx>] {
786 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
787 RefDecodable::decode(d)
791 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
792 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
793 RefDecodable::decode(d)
797 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_ast::InlineAsmTemplatePiece] {
798 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
799 RefDecodable::decode(d)
803 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Span] {
804 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
805 RefDecodable::decode(d)
809 //- ENCODING -------------------------------------------------------------------
811 pub trait OpaqueEncoder: Encoder {
812 fn position(&self) -> usize;
815 impl OpaqueEncoder for FileEncoder {
817 fn position(&self) -> usize {
818 FileEncoder::position(self)
822 /// An encoder that can write to the incremental compilation cache.
823 pub struct CacheEncoder<'a, 'tcx, E: OpaqueEncoder> {
826 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
827 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
828 interpret_allocs: FxIndexSet<interpret::AllocId>,
829 source_map: CachingSourceMapView<'tcx>,
830 file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
831 hygiene_context: &'a HygieneEncodeContext,
834 impl<'a, 'tcx, E> CacheEncoder<'a, 'tcx, E>
836 E: 'a + OpaqueEncoder,
838 fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
839 self.file_to_file_index[&(&*source_file as *const SourceFile)]
842 /// Encode something with additional information that allows to do some
843 /// sanity checks when decoding the data again. This method will first
844 /// encode the specified tag, then the given value, then the number of
845 /// bytes taken up by tag and value. On decoding, we can then verify that
846 /// we get the expected tag and read the expected number of bytes.
847 fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(
851 ) -> Result<(), E::Error> {
852 let start_pos = self.position();
857 let end_pos = self.position();
858 ((end_pos - start_pos) as u64).encode(self)
862 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for SyntaxContext
864 E: 'a + OpaqueEncoder,
866 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
867 rustc_span::hygiene::raw_encode_syntax_context(*self, s.hygiene_context, s)
871 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for ExpnId
873 E: 'a + OpaqueEncoder,
875 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
876 s.hygiene_context.schedule_expn_data_for_encoding(*self);
877 self.expn_hash().encode(s)
881 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for Span
883 E: 'a + OpaqueEncoder,
885 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
886 let span_data = self.data_untracked();
887 span_data.ctxt.encode(s)?;
888 span_data.parent.encode(s)?;
890 if span_data.is_dummy() {
891 return TAG_PARTIAL_SPAN.encode(s);
894 if let Some(parent) = span_data.parent {
895 let enclosing = s.tcx.definitions_untracked().def_span(parent).data_untracked();
896 if enclosing.contains(span_data) {
897 TAG_RELATIVE_SPAN.encode(s)?;
898 (span_data.lo - enclosing.lo).to_u32().encode(s)?;
899 (span_data.hi - enclosing.lo).to_u32().encode(s)?;
904 let pos = s.source_map.byte_pos_to_line_and_col(span_data.lo);
905 let partial_span = match &pos {
906 Some((file_lo, _, _)) => !file_lo.contains(span_data.hi),
911 return TAG_PARTIAL_SPAN.encode(s);
914 let (file_lo, line_lo, col_lo) = pos.unwrap();
916 let len = span_data.hi - span_data.lo;
918 let source_file_index = s.source_file_index(file_lo);
920 TAG_FULL_SPAN.encode(s)?;
921 source_file_index.encode(s)?;
928 impl<'a, 'tcx, E> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx, E>
930 E: 'a + OpaqueEncoder,
932 const CLEAR_CROSS_CRATE: bool = false;
934 fn position(&self) -> usize {
935 self.encoder.position()
937 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
938 &mut self.type_shorthands
940 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
941 &mut self.predicate_shorthands
943 fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
944 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
950 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for CrateNum
952 E: 'a + OpaqueEncoder,
954 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
955 s.tcx.stable_crate_id(*self).encode(s)
959 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefId
961 E: 'a + OpaqueEncoder,
963 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
964 s.tcx.def_path_hash(*self).encode(s)
968 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefIndex
970 E: 'a + OpaqueEncoder,
972 fn encode(&self, _: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
973 bug!("encoding `DefIndex` without context");
977 macro_rules! encoder_methods {
978 ($($name:ident($ty:ty);)*) => {
980 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
981 self.encoder.$name(value)
986 impl<'a, 'tcx, E> Encoder for CacheEncoder<'a, 'tcx, E>
988 E: 'a + OpaqueEncoder,
990 type Error = E::Error;
993 fn emit_unit(&mut self) -> Result<(), Self::Error> {
1017 emit_raw_bytes(&[u8]);
1021 // This ensures that the `Encodable<opaque::FileEncoder>::encode` specialization for byte slices
1022 // is used when a `CacheEncoder` having an `opaque::FileEncoder` is passed to `Encodable::encode`.
1023 // Unfortunately, we have to manually opt into specializations this way, given how `CacheEncoder`
1024 // and the encoding traits currently work.
1025 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx, FileEncoder>> for [u8] {
1026 fn encode(&self, e: &mut CacheEncoder<'a, 'tcx, FileEncoder>) -> FileEncodeResult {
1027 self.encode(e.encoder)
1031 pub fn encode_query_results<'a, 'tcx, CTX, Q>(
1033 encoder: &mut CacheEncoder<'a, 'tcx, FileEncoder>,
1034 query_result_index: &mut EncodedDepNodeIndex,
1035 ) -> FileEncodeResult
1037 CTX: QueryContext + 'tcx,
1038 Q: super::QueryDescription<CTX> + super::QueryAccessors<CTX>,
1039 Q::Value: Encodable<CacheEncoder<'a, 'tcx, FileEncoder>>,
1044 .extra_verbose_generic_activity("encode_query_results_for", std::any::type_name::<Q>());
1046 assert!(Q::query_state(tcx).all_inactive());
1047 let cache = Q::query_cache(tcx);
1048 let mut res = Ok(());
1049 cache.iter_results(&mut |key, value, dep_node| {
1053 if Q::cache_on_disk(tcx, &key, Some(value)) {
1054 let dep_node = SerializedDepNodeIndex::new(dep_node.index());
1056 // Record position of the cache entry.
1057 query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.encoder.position())));
1059 // Encode the type check tables with the `SerializedDepNodeIndex`
1061 match encoder.encode_tagged(dep_node, value) {