1use std::collections::hash_map::Entry;
2use std::mem;
3use std::sync::Arc;
4
5use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
6use rustc_data_structures::memmap::Mmap;
7use rustc_data_structures::sync::{HashMapExt, Lock, RwLock};
8use rustc_data_structures::unhash::UnhashMap;
9use rustc_data_structures::unord::{UnordMap, UnordSet};
10use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId};
11use rustc_hir::definitions::DefPathHash;
12use rustc_index::{Idx, IndexVec};
13use rustc_macros::{Decodable, Encodable};
14use rustc_query_system::query::QuerySideEffect;
15use rustc_serialize::opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder};
16use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
17use rustc_session::Session;
18use rustc_span::hygiene::{
19 ExpnId, HygieneDecodeContext, HygieneEncodeContext, SyntaxContext, SyntaxContextKey,
20};
21use rustc_span::source_map::Spanned;
22use rustc_span::{
23 BytePos, ByteSymbol, CachingSourceMapView, ExpnData, ExpnHash, Pos, RelativeBytePos,
24 SourceFile, Span, SpanDecoder, SpanEncoder, StableSourceFileId, Symbol,
25};
26
27use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
28use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState};
29use crate::mir::mono::MonoItem;
30use crate::mir::{self, interpret};
31use crate::ty::codec::{RefDecodable, TyDecoder, TyEncoder};
32use crate::ty::{self, Ty, TyCtxt};
33
34const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
35
36const TAG_FULL_SPAN: u8 = 0;
38const TAG_PARTIAL_SPAN: u8 = 1;
40const TAG_RELATIVE_SPAN: u8 = 2;
41
42const TAG_SYNTAX_CONTEXT: u8 = 0;
43const TAG_EXPN_DATA: u8 = 1;
44
45const SYMBOL_STR: u8 = 0;
47const SYMBOL_OFFSET: u8 = 1;
48const SYMBOL_PREDEFINED: u8 = 2;
49
50pub struct OnDiskCache {
55 serialized_data: RwLock<Option<Mmap>>,
57
58 current_side_effects: Lock<FxIndexMap<DepNodeIndex, QuerySideEffect>>,
61
62 file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
63
64 file_index_to_file: Lock<FxHashMap<SourceFileIndex, Arc<SourceFile>>>,
66
67 query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
70
71 prev_side_effects_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
74
75 alloc_decoding_state: AllocDecodingState,
76
77 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
83 expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
93 hygiene_context: HygieneDecodeContext,
95 foreign_expn_data: UnhashMap<ExpnHash, u32>,
100}
101
102#[derive(Encodable, Decodable)]
104struct Footer {
105 file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
106 query_result_index: EncodedDepNodeIndex,
107 side_effects_index: EncodedDepNodeIndex,
108 interpret_alloc_index: Vec<u64>,
112 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
114 expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
116 foreign_expn_data: UnhashMap<ExpnHash, u32>,
117}
118
119pub type EncodedDepNodeIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
120
121#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
122struct SourceFileIndex(u32);
123
124#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Encodable, Decodable)]
125pub struct AbsoluteBytePos(u64);
126
127impl AbsoluteBytePos {
128 #[inline]
129 pub fn new(pos: usize) -> AbsoluteBytePos {
130 AbsoluteBytePos(pos.try_into().expect("Incremental cache file size overflowed u64."))
131 }
132
133 #[inline]
134 fn to_usize(self) -> usize {
135 self.0 as usize
136 }
137}
138
139#[derive(Encodable, Decodable, Clone, Debug)]
140struct EncodedSourceFileId {
141 stable_source_file_id: StableSourceFileId,
142 stable_crate_id: StableCrateId,
143}
144
145impl EncodedSourceFileId {
146 #[inline]
147 fn new(tcx: TyCtxt<'_>, file: &SourceFile) -> EncodedSourceFileId {
148 EncodedSourceFileId {
149 stable_source_file_id: file.stable_id,
150 stable_crate_id: tcx.stable_crate_id(file.cnum),
151 }
152 }
153}
154
155impl OnDiskCache {
156 pub fn new(sess: &Session, data: Mmap, start_pos: usize) -> Result<Self, ()> {
161 assert!(sess.opts.incremental.is_some());
162
163 let mut decoder = MemDecoder::new(&data, start_pos)?;
164
165 let footer_pos = decoder
168 .with_position(decoder.len() - IntEncodedWithFixedSize::ENCODED_SIZE, |decoder| {
169 IntEncodedWithFixedSize::decode(decoder).0 as usize
170 });
171 let footer: Footer =
173 decoder.with_position(footer_pos, |decoder| decode_tagged(decoder, TAG_FILE_FOOTER));
174
175 Ok(Self {
176 serialized_data: RwLock::new(Some(data)),
177 file_index_to_stable_id: footer.file_index_to_stable_id,
178 file_index_to_file: Default::default(),
179 current_side_effects: Default::default(),
180 query_result_index: footer.query_result_index.into_iter().collect(),
181 prev_side_effects_index: footer.side_effects_index.into_iter().collect(),
182 alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
183 syntax_contexts: footer.syntax_contexts,
184 expn_data: footer.expn_data,
185 foreign_expn_data: footer.foreign_expn_data,
186 hygiene_context: Default::default(),
187 })
188 }
189
190 pub fn new_empty() -> Self {
191 Self {
192 serialized_data: RwLock::new(None),
193 file_index_to_stable_id: Default::default(),
194 file_index_to_file: Default::default(),
195 current_side_effects: Default::default(),
196 query_result_index: Default::default(),
197 prev_side_effects_index: Default::default(),
198 alloc_decoding_state: AllocDecodingState::new(Vec::new()),
199 syntax_contexts: FxHashMap::default(),
200 expn_data: UnhashMap::default(),
201 foreign_expn_data: UnhashMap::default(),
202 hygiene_context: Default::default(),
203 }
204 }
205
206 pub fn drop_serialized_data(&self, tcx: TyCtxt<'_>) {
212 tcx.dep_graph.exec_cache_promotions(tcx);
219
220 *self.serialized_data.write() = None;
221 }
222
223 pub fn serialize(&self, tcx: TyCtxt<'_>, encoder: FileEncoder) -> FileEncodeResult {
224 tcx.dep_graph.with_ignore(|| {
226 let (file_to_file_index, file_index_to_stable_id) = {
228 let files = tcx.sess.source_map().files();
229 let mut file_to_file_index =
230 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
231 let mut file_index_to_stable_id =
232 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
233
234 for (index, file) in files.iter().enumerate() {
235 let index = SourceFileIndex(index as u32);
236 let file_ptr: *const SourceFile = &raw const **file;
237 file_to_file_index.insert(file_ptr, index);
238 let source_file_id = EncodedSourceFileId::new(tcx, file);
239 file_index_to_stable_id.insert(index, source_file_id);
240 }
241
242 (file_to_file_index, file_index_to_stable_id)
243 };
244
245 let hygiene_encode_context = HygieneEncodeContext::default();
246
247 let mut encoder = CacheEncoder {
248 tcx,
249 encoder,
250 type_shorthands: Default::default(),
251 predicate_shorthands: Default::default(),
252 interpret_allocs: Default::default(),
253 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
254 file_to_file_index,
255 hygiene_context: &hygiene_encode_context,
256 symbol_index_table: Default::default(),
257 };
258
259 let mut query_result_index = EncodedDepNodeIndex::new();
261
262 tcx.sess.time("encode_query_results", || {
263 let enc = &mut encoder;
264 let qri = &mut query_result_index;
265 (tcx.query_system.fns.encode_query_results)(tcx, enc, qri);
266 });
267
268 let side_effects_index: EncodedDepNodeIndex = self
270 .current_side_effects
271 .borrow()
272 .iter()
273 .map(|(dep_node_index, side_effect)| {
274 let pos = AbsoluteBytePos::new(encoder.position());
275 let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
276 encoder.encode_tagged(dep_node_index, side_effect);
277
278 (dep_node_index, pos)
279 })
280 .collect();
281
282 let interpret_alloc_index = {
283 let mut interpret_alloc_index = Vec::new();
284 let mut n = 0;
285 loop {
286 let new_n = encoder.interpret_allocs.len();
287 if n == new_n {
289 break;
291 }
292 interpret_alloc_index.reserve(new_n - n);
293 for idx in n..new_n {
294 let id = encoder.interpret_allocs[idx];
295 let pos: u64 = encoder.position().try_into().unwrap();
296 interpret_alloc_index.push(pos);
297 interpret::specialized_encode_alloc_id(&mut encoder, tcx, id);
298 }
299 n = new_n;
300 }
301 interpret_alloc_index
302 };
303
304 let mut syntax_contexts = FxHashMap::default();
305 let mut expn_data = UnhashMap::default();
306 let mut foreign_expn_data = UnhashMap::default();
307
308 hygiene_encode_context.encode(
312 &mut encoder,
313 |encoder, index, ctxt_data| {
314 let pos = AbsoluteBytePos::new(encoder.position());
315 encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data);
316 syntax_contexts.insert(index, pos);
317 },
318 |encoder, expn_id, data, hash| {
319 if expn_id.krate == LOCAL_CRATE {
320 let pos = AbsoluteBytePos::new(encoder.position());
321 encoder.encode_tagged(TAG_EXPN_DATA, data);
322 expn_data.insert(hash, pos);
323 } else {
324 foreign_expn_data.insert(hash, expn_id.local_id.as_u32());
325 }
326 },
327 );
328
329 let footer_pos = encoder.position() as u64;
331 encoder.encode_tagged(
332 TAG_FILE_FOOTER,
333 &Footer {
334 file_index_to_stable_id,
335 query_result_index,
336 side_effects_index,
337 interpret_alloc_index,
338 syntax_contexts,
339 expn_data,
340 foreign_expn_data,
341 },
342 );
343
344 IntEncodedWithFixedSize(footer_pos).encode(&mut encoder.encoder);
347
348 encoder.finish()
352 })
353 }
354
355 pub fn load_side_effect(
357 &self,
358 tcx: TyCtxt<'_>,
359 dep_node_index: SerializedDepNodeIndex,
360 ) -> Option<QuerySideEffect> {
361 let side_effect: Option<QuerySideEffect> =
362 self.load_indexed(tcx, dep_node_index, &self.prev_side_effects_index);
363 side_effect
364 }
365
366 pub fn store_side_effect(&self, dep_node_index: DepNodeIndex, side_effect: QuerySideEffect) {
370 let mut current_side_effects = self.current_side_effects.borrow_mut();
371 let prev = current_side_effects.insert(dep_node_index, side_effect);
372 debug_assert!(prev.is_none());
373 }
374
375 #[inline]
377 pub fn loadable_from_disk(&self, dep_node_index: SerializedDepNodeIndex) -> bool {
378 self.query_result_index.contains_key(&dep_node_index)
379 }
381
382 pub fn try_load_query_result<'tcx, T>(
385 &self,
386 tcx: TyCtxt<'tcx>,
387 dep_node_index: SerializedDepNodeIndex,
388 ) -> Option<T>
389 where
390 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
391 {
392 let opt_value = self.load_indexed(tcx, dep_node_index, &self.query_result_index);
393 debug_assert_eq!(opt_value.is_some(), self.loadable_from_disk(dep_node_index));
394 opt_value
395 }
396
397 fn load_indexed<'tcx, T>(
398 &self,
399 tcx: TyCtxt<'tcx>,
400 dep_node_index: SerializedDepNodeIndex,
401 index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
402 ) -> Option<T>
403 where
404 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
405 {
406 let pos = index.get(&dep_node_index).cloned()?;
407 let value = self.with_decoder(tcx, pos, |decoder| decode_tagged(decoder, dep_node_index));
408 Some(value)
409 }
410
411 fn with_decoder<'a, 'tcx, T, F: for<'s> FnOnce(&mut CacheDecoder<'s, 'tcx>) -> T>(
412 &self,
413 tcx: TyCtxt<'tcx>,
414 pos: AbsoluteBytePos,
415 f: F,
416 ) -> T
417 where
418 T: Decodable<CacheDecoder<'a, 'tcx>>,
419 {
420 let serialized_data = self.serialized_data.read();
421 let mut decoder = CacheDecoder {
422 tcx,
423 opaque: MemDecoder::new(serialized_data.as_deref().unwrap_or(&[]), pos.to_usize())
424 .unwrap(),
425 file_index_to_file: &self.file_index_to_file,
426 file_index_to_stable_id: &self.file_index_to_stable_id,
427 alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
428 syntax_contexts: &self.syntax_contexts,
429 expn_data: &self.expn_data,
430 foreign_expn_data: &self.foreign_expn_data,
431 hygiene_context: &self.hygiene_context,
432 };
433 f(&mut decoder)
434 }
435}
436
437pub struct CacheDecoder<'a, 'tcx> {
443 tcx: TyCtxt<'tcx>,
444 opaque: MemDecoder<'a>,
445 file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Arc<SourceFile>>>,
446 file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, EncodedSourceFileId>,
447 alloc_decoding_session: AllocDecodingSession<'a>,
448 syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
449 expn_data: &'a UnhashMap<ExpnHash, AbsoluteBytePos>,
450 foreign_expn_data: &'a UnhashMap<ExpnHash, u32>,
451 hygiene_context: &'a HygieneDecodeContext,
452}
453
454impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
455 #[inline]
456 fn file_index_to_file(&self, index: SourceFileIndex) -> Arc<SourceFile> {
457 let CacheDecoder { tcx, file_index_to_file, file_index_to_stable_id, .. } = *self;
458
459 Arc::clone(file_index_to_file.borrow_mut().entry(index).or_insert_with(|| {
460 let source_file_id = &file_index_to_stable_id[&index];
461 let source_file_cnum = tcx.stable_crate_id_to_crate_num(source_file_id.stable_crate_id);
462
463 if source_file_cnum != LOCAL_CRATE {
473 self.tcx.import_source_files(source_file_cnum);
474 }
475
476 tcx.sess
477 .source_map()
478 .source_file_by_stable_id(source_file_id.stable_source_file_id)
479 .expect("failed to lookup `SourceFile` in new context")
480 }))
481 }
482
483 #[inline]
485 fn decode_symbol_or_byte_symbol<S>(
486 &mut self,
487 new_from_index: impl Fn(u32) -> S,
488 read_and_intern_str_or_byte_str_this: impl Fn(&mut Self) -> S,
489 read_and_intern_str_or_byte_str_opaque: impl Fn(&mut MemDecoder<'a>) -> S,
490 ) -> S {
491 let tag = self.read_u8();
492
493 match tag {
494 SYMBOL_STR => read_and_intern_str_or_byte_str_this(self),
495 SYMBOL_OFFSET => {
496 let pos = self.read_usize();
498
499 self.opaque.with_position(pos, |d| read_and_intern_str_or_byte_str_opaque(d))
501 }
502 SYMBOL_PREDEFINED => new_from_index(self.read_u32()),
503 _ => unreachable!(),
504 }
505 }
506}
507
508fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> V
511where
512 T: Decodable<D> + Eq + std::fmt::Debug,
513 V: Decodable<D>,
514 D: Decoder,
515{
516 let start_pos = decoder.position();
517
518 let actual_tag = T::decode(decoder);
519 assert_eq!(actual_tag, expected_tag);
520 let value = V::decode(decoder);
521 let end_pos = decoder.position();
522
523 let expected_len: u64 = Decodable::decode(decoder);
524 assert_eq!((end_pos - start_pos) as u64, expected_len);
525
526 value
527}
528
529impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
530 const CLEAR_CROSS_CRATE: bool = false;
531
532 #[inline]
533 fn interner(&self) -> TyCtxt<'tcx> {
534 self.tcx
535 }
536
537 fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
538 where
539 F: FnOnce(&mut Self) -> Ty<'tcx>,
540 {
541 let tcx = self.tcx;
542
543 let cache_key = ty::CReaderCacheKey { cnum: None, pos: shorthand };
544
545 if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
546 return ty;
547 }
548
549 let ty = or_insert_with(self);
550 tcx.ty_rcache.borrow_mut().insert_same(cache_key, ty);
552 ty
553 }
554
555 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
556 where
557 F: FnOnce(&mut Self) -> R,
558 {
559 debug_assert!(pos < self.opaque.len());
560
561 let new_opaque = self.opaque.split_at(pos);
562 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
563 let r = f(self);
564 self.opaque = old_opaque;
565 r
566 }
567
568 fn decode_alloc_id(&mut self) -> interpret::AllocId {
569 let alloc_decoding_session = self.alloc_decoding_session;
570 alloc_decoding_session.decode_alloc_id(self)
571 }
572}
573
574crate::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
575
576impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Vec<u8> {
580 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
581 Decodable::decode(&mut d.opaque)
582 }
583}
584
585impl<'a, 'tcx> SpanDecoder for CacheDecoder<'a, 'tcx> {
586 fn decode_syntax_context(&mut self) -> SyntaxContext {
587 let syntax_contexts = self.syntax_contexts;
588 rustc_span::hygiene::decode_syntax_context(self, self.hygiene_context, |this, id| {
589 let pos = syntax_contexts.get(&id).unwrap();
592 this.with_position(pos.to_usize(), |decoder| {
593 let data: SyntaxContextKey = decode_tagged(decoder, TAG_SYNTAX_CONTEXT);
594 data
595 })
596 })
597 }
598
599 fn decode_expn_id(&mut self) -> ExpnId {
600 let hash = ExpnHash::decode(self);
601 if hash.is_root() {
602 return ExpnId::root();
603 }
604
605 if let Some(expn_id) = ExpnId::from_hash(hash) {
606 return expn_id;
607 }
608
609 let krate = self.tcx.stable_crate_id_to_crate_num(hash.stable_crate_id());
610
611 let expn_id = if krate == LOCAL_CRATE {
612 let pos = self
614 .expn_data
615 .get(&hash)
616 .unwrap_or_else(|| panic!("Bad hash {:?} (map {:?})", hash, self.expn_data));
617
618 let data: ExpnData =
619 self.with_position(pos.to_usize(), |decoder| decode_tagged(decoder, TAG_EXPN_DATA));
620 let expn_id = rustc_span::hygiene::register_local_expn_id(data, hash);
621
622 #[cfg(debug_assertions)]
623 {
624 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
625 let local_hash = self.tcx.with_stable_hashing_context(|mut hcx| {
626 let mut hasher = StableHasher::new();
627 expn_id.expn_data().hash_stable(&mut hcx, &mut hasher);
628 hasher.finish()
629 });
630 debug_assert_eq!(hash.local_hash(), local_hash);
631 }
632
633 expn_id
634 } else {
635 let index_guess = self.foreign_expn_data[&hash];
636 self.tcx.expn_hash_to_expn_id(krate, index_guess, hash)
637 };
638
639 debug_assert_eq!(expn_id.krate, krate);
640 expn_id
641 }
642
643 fn decode_span(&mut self) -> Span {
644 let ctxt = SyntaxContext::decode(self);
645 let parent = Option::<LocalDefId>::decode(self);
646 let tag: u8 = Decodable::decode(self);
647
648 let (lo, hi) = match tag {
649 TAG_PARTIAL_SPAN => (BytePos(0), BytePos(0)),
650 TAG_RELATIVE_SPAN => {
651 let dlo = u32::decode(self);
652 let dto = u32::decode(self);
653
654 let enclosing = self.tcx.source_span_untracked(parent.unwrap()).data_untracked();
655 (enclosing.lo + BytePos::from_u32(dlo), enclosing.lo + BytePos::from_u32(dto))
656 }
657 TAG_FULL_SPAN => {
658 let file_lo_index = SourceFileIndex::decode(self);
659 let line_lo = usize::decode(self);
660 let col_lo = RelativeBytePos::decode(self);
661 let len = BytePos::decode(self);
662
663 let file_lo = self.file_index_to_file(file_lo_index);
664 let lo = file_lo.lines()[line_lo - 1] + col_lo;
665 let lo = file_lo.absolute_position(lo);
666 let hi = lo + len;
667 (lo, hi)
668 }
669 _ => unreachable!(),
670 };
671
672 Span::new(lo, hi, ctxt, parent)
673 }
674
675 fn decode_symbol(&mut self) -> Symbol {
676 self.decode_symbol_or_byte_symbol(
677 Symbol::new,
678 |this| Symbol::intern(this.read_str()),
679 |opaque| Symbol::intern(opaque.read_str()),
680 )
681 }
682
683 fn decode_byte_symbol(&mut self) -> ByteSymbol {
684 self.decode_symbol_or_byte_symbol(
685 ByteSymbol::new,
686 |this| ByteSymbol::intern(this.read_byte_str()),
687 |opaque| ByteSymbol::intern(opaque.read_byte_str()),
688 )
689 }
690
691 fn decode_crate_num(&mut self) -> CrateNum {
692 let stable_id = StableCrateId::decode(self);
693 let cnum = self.tcx.stable_crate_id_to_crate_num(stable_id);
694 cnum
695 }
696
697 fn decode_def_index(&mut self) -> DefIndex {
702 panic!("trying to decode `DefIndex` outside the context of a `DefId`")
703 }
704
705 fn decode_def_id(&mut self) -> DefId {
709 let def_path_hash = DefPathHash::decode(self);
711
712 match self.tcx.def_path_hash_to_def_id(def_path_hash) {
718 Some(r) => r,
719 None => panic!("Failed to convert DefPathHash {def_path_hash:?}"),
720 }
721 }
722
723 fn decode_attr_id(&mut self) -> rustc_span::AttrId {
724 panic!("cannot decode `AttrId` with `CacheDecoder`");
725 }
726}
727
728impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx UnordSet<LocalDefId> {
729 #[inline]
730 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
731 RefDecodable::decode(d)
732 }
733}
734
735impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
736 for &'tcx UnordMap<DefId, ty::EarlyBinder<'tcx, Ty<'tcx>>>
737{
738 #[inline]
739 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
740 RefDecodable::decode(d)
741 }
742}
743
744impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
745 for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
746{
747 #[inline]
748 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
749 RefDecodable::decode(d)
750 }
751}
752
753impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Clause<'tcx>, Span)] {
754 #[inline]
755 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
756 RefDecodable::decode(d)
757 }
758}
759
760impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_ast::InlineAsmTemplatePiece] {
761 #[inline]
762 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
763 RefDecodable::decode(d)
764 }
765}
766
767impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Spanned<MonoItem<'tcx>>] {
768 #[inline]
769 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
770 RefDecodable::decode(d)
771 }
772}
773
774impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
775 for &'tcx crate::traits::specialization_graph::Graph
776{
777 #[inline]
778 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
779 RefDecodable::decode(d)
780 }
781}
782
783macro_rules! impl_ref_decoder {
784 (<$tcx:tt> $($ty:ty,)*) => {
785 $(impl<'a, $tcx> Decodable<CacheDecoder<'a, $tcx>> for &$tcx [$ty] {
786 #[inline]
787 fn decode(d: &mut CacheDecoder<'a, $tcx>) -> Self {
788 RefDecodable::decode(d)
789 }
790 })*
791 };
792}
793
794impl_ref_decoder! {<'tcx>
795 Span,
796 rustc_hir::Attribute,
797 rustc_span::Ident,
798 ty::Variance,
799 rustc_span::def_id::DefId,
800 rustc_span::def_id::LocalDefId,
801 (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo),
802 ty::DeducedParamAttrs,
803}
804
805pub struct CacheEncoder<'a, 'tcx> {
809 tcx: TyCtxt<'tcx>,
810 encoder: FileEncoder,
811 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
812 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
813 interpret_allocs: FxIndexSet<interpret::AllocId>,
814 source_map: CachingSourceMapView<'tcx>,
815 file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
816 hygiene_context: &'a HygieneEncodeContext,
817 symbol_index_table: FxHashMap<u32, usize>,
819}
820
821impl<'a, 'tcx> CacheEncoder<'a, 'tcx> {
822 #[inline]
823 fn source_file_index(&mut self, source_file: Arc<SourceFile>) -> SourceFileIndex {
824 self.file_to_file_index[&(&raw const *source_file)]
825 }
826
827 pub fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(&mut self, tag: T, value: &V) {
833 let start_pos = self.position();
834
835 tag.encode(self);
836 value.encode(self);
837
838 let end_pos = self.position();
839 ((end_pos - start_pos) as u64).encode(self);
840 }
841
842 fn encode_symbol_or_byte_symbol(
844 &mut self,
845 index: u32,
846 emit_str_or_byte_str: impl Fn(&mut Self),
847 ) {
848 if Symbol::is_predefined(index) {
850 self.encoder.emit_u8(SYMBOL_PREDEFINED);
851 self.encoder.emit_u32(index);
852 } else {
853 match self.symbol_index_table.entry(index) {
855 Entry::Vacant(o) => {
856 self.encoder.emit_u8(SYMBOL_STR);
857 let pos = self.encoder.position();
858 o.insert(pos);
859 emit_str_or_byte_str(self);
860 }
861 Entry::Occupied(o) => {
862 let x = *o.get();
863 self.emit_u8(SYMBOL_OFFSET);
864 self.emit_usize(x);
865 }
866 }
867 }
868 }
869
870 #[inline]
871 fn finish(mut self) -> FileEncodeResult {
872 self.encoder.finish()
873 }
874}
875
876impl<'a, 'tcx> SpanEncoder for CacheEncoder<'a, 'tcx> {
877 fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
878 rustc_span::hygiene::raw_encode_syntax_context(syntax_context, self.hygiene_context, self);
879 }
880
881 fn encode_expn_id(&mut self, expn_id: ExpnId) {
882 self.hygiene_context.schedule_expn_data_for_encoding(expn_id);
883 expn_id.expn_hash().encode(self);
884 }
885
886 fn encode_span(&mut self, span: Span) {
887 let span_data = span.data_untracked();
888 span_data.ctxt.encode(self);
889 span_data.parent.encode(self);
890
891 if span_data.is_dummy() {
892 return TAG_PARTIAL_SPAN.encode(self);
893 }
894
895 if let Some(parent) = span_data.parent {
896 let enclosing = self.tcx.source_span_untracked(parent).data_untracked();
897 if enclosing.contains(span_data) {
898 TAG_RELATIVE_SPAN.encode(self);
899 (span_data.lo - enclosing.lo).to_u32().encode(self);
900 (span_data.hi - enclosing.lo).to_u32().encode(self);
901 return;
902 }
903 }
904
905 let pos = self.source_map.byte_pos_to_line_and_col(span_data.lo);
906 let partial_span = match &pos {
907 Some((file_lo, _, _)) => !file_lo.contains(span_data.hi),
908 None => true,
909 };
910
911 if partial_span {
912 return TAG_PARTIAL_SPAN.encode(self);
913 }
914
915 let (file_lo, line_lo, col_lo) = pos.unwrap();
916
917 let len = span_data.hi - span_data.lo;
918
919 let source_file_index = self.source_file_index(file_lo);
920
921 TAG_FULL_SPAN.encode(self);
922 source_file_index.encode(self);
923 line_lo.encode(self);
924 col_lo.encode(self);
925 len.encode(self);
926 }
927
928 fn encode_symbol(&mut self, sym: Symbol) {
929 self.encode_symbol_or_byte_symbol(sym.as_u32(), |this| this.emit_str(sym.as_str()));
930 }
931
932 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
933 self.encode_symbol_or_byte_symbol(byte_sym.as_u32(), |this| {
934 this.emit_byte_str(byte_sym.as_byte_str())
935 });
936 }
937
938 fn encode_crate_num(&mut self, crate_num: CrateNum) {
939 self.tcx.stable_crate_id(crate_num).encode(self);
940 }
941
942 fn encode_def_id(&mut self, def_id: DefId) {
943 self.tcx.def_path_hash(def_id).encode(self);
944 }
945
946 fn encode_def_index(&mut self, _def_index: DefIndex) {
947 bug!("encoding `DefIndex` without context");
948 }
949}
950
951impl<'a, 'tcx> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx> {
952 const CLEAR_CROSS_CRATE: bool = false;
953
954 #[inline]
955 fn position(&self) -> usize {
956 self.encoder.position()
957 }
958 #[inline]
959 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
960 &mut self.type_shorthands
961 }
962 #[inline]
963 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
964 &mut self.predicate_shorthands
965 }
966 #[inline]
967 fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) {
968 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
969
970 index.encode(self);
971 }
972}
973
974macro_rules! encoder_methods {
975 ($($name:ident($ty:ty);)*) => {
976 #[inline]
977 $(fn $name(&mut self, value: $ty) {
978 self.encoder.$name(value)
979 })*
980 }
981}
982
983impl<'a, 'tcx> Encoder for CacheEncoder<'a, 'tcx> {
984 encoder_methods! {
985 emit_usize(usize);
986 emit_u128(u128);
987 emit_u64(u64);
988 emit_u32(u32);
989 emit_u16(u16);
990 emit_u8(u8);
991
992 emit_isize(isize);
993 emit_i128(i128);
994 emit_i64(i64);
995 emit_i32(i32);
996 emit_i16(i16);
997
998 emit_raw_bytes(&[u8]);
999 }
1000}
1001
1002impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for [u8] {
1007 fn encode(&self, e: &mut CacheEncoder<'a, 'tcx>) {
1008 self.encode(&mut e.encoder);
1009 }
1010}