Skip to content

Commit a67ded0

Browse files
committed
Don't recurse into allocations, use a global table instead
1 parent fb730d7 commit a67ded0

File tree

7 files changed

+192
-152
lines changed

7 files changed

+192
-152
lines changed

src/librustc/ich/impls_ty.rs

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -398,12 +398,12 @@ impl_stable_hash_for!(struct mir::interpret::MemoryPointer {
398398

399399
enum AllocDiscriminant {
400400
Alloc,
401-
ExternStatic,
401+
Static,
402402
Function,
403403
}
404404
impl_stable_hash_for!(enum self::AllocDiscriminant {
405405
Alloc,
406-
ExternStatic,
406+
Static,
407407
Function
408408
});
409409

@@ -414,24 +414,26 @@ impl<'a> HashStable<StableHashingContext<'a>> for mir::interpret::AllocId {
414414
hasher: &mut StableHasher<W>,
415415
) {
416416
ty::tls::with_opt(|tcx| {
417+
trace!("hashing {:?}", *self);
417418
let tcx = tcx.expect("can't hash AllocIds during hir lowering");
418-
if let Some(alloc) = tcx.interpret_interner.get_alloc(*self) {
419+
if let Some(def_id) = tcx.interpret_interner
420+
.get_corresponding_static_def_id(*self) {
421+
AllocDiscriminant::Static.hash_stable(hcx, hasher);
422+
trace!("hashing {:?} as static {:?}", *self, def_id);
423+
def_id.hash_stable(hcx, hasher);
424+
} else if let Some(alloc) = tcx.interpret_interner.get_alloc(*self) {
419425
AllocDiscriminant::Alloc.hash_stable(hcx, hasher);
420426
if hcx.alloc_id_recursion_tracker.insert(*self) {
421-
tcx
422-
.interpret_interner
423-
.get_corresponding_static_def_id(*self)
424-
.hash_stable(hcx, hasher);
427+
trace!("hashing {:?} as alloc {:#?}", *self, alloc);
425428
alloc.hash_stable(hcx, hasher);
426429
assert!(hcx.alloc_id_recursion_tracker.remove(self));
430+
} else {
431+
trace!("skipping hashing of {:?} due to recursion", *self);
427432
}
428433
} else if let Some(inst) = tcx.interpret_interner.get_fn(*self) {
434+
trace!("hashing {:?} as fn {:#?}", *self, inst);
429435
AllocDiscriminant::Function.hash_stable(hcx, hasher);
430436
inst.hash_stable(hcx, hasher);
431-
} else if let Some(def_id) = tcx.interpret_interner
432-
.get_corresponding_static_def_id(*self) {
433-
AllocDiscriminant::ExternStatic.hash_stable(hcx, hasher);
434-
def_id.hash_stable(hcx, hasher);
435437
} else {
436438
bug!("no allocation for {}", self);
437439
}

src/librustc/mir/interpret/mod.rs

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,12 @@ pub struct AllocId(pub u64);
154154
impl ::rustc_serialize::UseSpecializedEncodable for AllocId {}
155155
impl ::rustc_serialize::UseSpecializedDecodable for AllocId {}
156156

157-
pub const ALLOC_DISCRIMINANT: usize = 0;
158-
pub const FN_DISCRIMINANT: usize = 1;
159-
pub const EXTERN_STATIC_DISCRIMINANT: usize = 2;
160-
pub const SHORTHAND_START: usize = 3;
157+
#[derive(RustcDecodable, RustcEncodable)]
158+
enum AllocKind {
159+
Alloc,
160+
Fn,
161+
ExternStatic,
162+
}
161163

162164
pub fn specialized_encode_alloc_id<
163165
'a, 'tcx,
@@ -166,26 +168,22 @@ pub fn specialized_encode_alloc_id<
166168
encoder: &mut E,
167169
tcx: TyCtxt<'a, 'tcx, 'tcx>,
168170
alloc_id: AllocId,
169-
shorthand: Option<usize>,
170171
) -> Result<(), E::Error> {
171-
if let Some(shorthand) = shorthand {
172-
return shorthand.encode(encoder);
173-
}
174172
if let Some(alloc) = tcx.interpret_interner.get_alloc(alloc_id) {
175173
trace!("encoding {:?} with {:#?}", alloc_id, alloc);
176-
ALLOC_DISCRIMINANT.encode(encoder)?;
174+
AllocKind::Alloc.encode(encoder)?;
177175
alloc.encode(encoder)?;
178176
// encode whether this allocation is the root allocation of a static
179177
tcx.interpret_interner
180178
.get_corresponding_static_def_id(alloc_id)
181179
.encode(encoder)?;
182180
} else if let Some(fn_instance) = tcx.interpret_interner.get_fn(alloc_id) {
183181
trace!("encoding {:?} with {:#?}", alloc_id, fn_instance);
184-
FN_DISCRIMINANT.encode(encoder)?;
182+
AllocKind::Fn.encode(encoder)?;
185183
fn_instance.encode(encoder)?;
186184
} else if let Some(did) = tcx.interpret_interner.get_corresponding_static_def_id(alloc_id) {
187185
// extern "C" statics don't have allocations, just encode its def_id
188-
EXTERN_STATIC_DISCRIMINANT.encode(encoder)?;
186+
AllocKind::ExternStatic.encode(encoder)?;
189187
did.encode(encoder)?;
190188
} else {
191189
bug!("alloc id without corresponding allocation: {}", alloc_id);
@@ -196,21 +194,18 @@ pub fn specialized_encode_alloc_id<
196194
pub fn specialized_decode_alloc_id<
197195
'a, 'tcx,
198196
D: Decoder,
199-
CACHE: FnOnce(&mut D, usize, AllocId),
200-
SHORT: FnOnce(&mut D, usize) -> Result<AllocId, D::Error>
197+
CACHE: FnOnce(&mut D, AllocId),
201198
>(
202199
decoder: &mut D,
203200
tcx: TyCtxt<'a, 'tcx, 'tcx>,
204-
pos: usize,
205201
cache: CACHE,
206-
short: SHORT,
207202
) -> Result<AllocId, D::Error> {
208-
match usize::decode(decoder)? {
209-
ALLOC_DISCRIMINANT => {
203+
match AllocKind::decode(decoder)? {
204+
AllocKind::Alloc => {
210205
let alloc_id = tcx.interpret_interner.reserve();
211-
trace!("creating alloc id {:?} at {}", alloc_id, pos);
206+
trace!("creating alloc id {:?}", alloc_id);
212207
// insert early to allow recursive allocs
213-
cache(decoder, pos, alloc_id);
208+
cache(decoder, alloc_id);
214209

215210
let allocation = Allocation::decode(decoder)?;
216211
trace!("decoded alloc {:?} {:#?}", alloc_id, allocation);
@@ -223,26 +218,23 @@ pub fn specialized_decode_alloc_id<
223218

224219
Ok(alloc_id)
225220
},
226-
FN_DISCRIMINANT => {
227-
trace!("creating fn alloc id at {}", pos);
221+
AllocKind::Fn => {
222+
trace!("creating fn alloc id");
228223
let instance = ty::Instance::decode(decoder)?;
229224
trace!("decoded fn alloc instance: {:?}", instance);
230225
let id = tcx.interpret_interner.create_fn_alloc(instance);
231226
trace!("created fn alloc id: {:?}", id);
232-
cache(decoder, pos, id);
227+
cache(decoder, id);
233228
Ok(id)
234229
},
235-
EXTERN_STATIC_DISCRIMINANT => {
236-
trace!("creating extern static alloc id at {}", pos);
230+
AllocKind::ExternStatic => {
231+
trace!("creating extern static alloc id at");
237232
let did = DefId::decode(decoder)?;
238233
let alloc_id = tcx.interpret_interner.reserve();
234+
cache(decoder, alloc_id);
239235
tcx.interpret_interner.cache(did, alloc_id);
240236
Ok(alloc_id)
241237
},
242-
shorthand => {
243-
trace!("loading shorthand {}", shorthand);
244-
short(decoder, shorthand)
245-
},
246238
}
247239
}
248240

src/librustc/ty/maps/on_disk_cache.rs

Lines changed: 75 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,11 @@ pub struct OnDiskCache<'sess> {
7777
// `serialized_data`.
7878
prev_diagnostics_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
7979

80-
// A cache to ensure we don't read allocations twice
81-
interpret_alloc_cache: RefCell<FxHashMap<usize, interpret::AllocId>>,
80+
// Alloc indices to memory location map
81+
prev_interpret_alloc_index: Vec<AbsoluteBytePos>,
8282

83-
// A map from positions to size of the serialized allocation
84-
// so we can skip over already processed allocations
85-
interpret_alloc_size: RefCell<FxHashMap<usize, usize>>,
83+
/// Deserialization: A cache to ensure we don't read allocations twice
84+
interpret_alloc_cache: RefCell<FxHashMap<usize, interpret::AllocId>>,
8685
}
8786

8887
// This type is used only for (de-)serialization.
@@ -92,6 +91,8 @@ struct Footer {
9291
prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
9392
query_result_index: EncodedQueryResultIndex,
9493
diagnostics_index: EncodedQueryResultIndex,
94+
// the location of all allocations
95+
interpret_alloc_index: Vec<AbsoluteBytePos>,
9596
}
9697

9798
type EncodedQueryResultIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
@@ -148,8 +149,8 @@ impl<'sess> OnDiskCache<'sess> {
148149
query_result_index: footer.query_result_index.into_iter().collect(),
149150
prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
150151
synthetic_expansion_infos: Lock::new(FxHashMap()),
152+
prev_interpret_alloc_index: footer.interpret_alloc_index,
151153
interpret_alloc_cache: RefCell::new(FxHashMap::default()),
152-
interpret_alloc_size: RefCell::new(FxHashMap::default()),
153154
}
154155
}
155156

@@ -165,8 +166,8 @@ impl<'sess> OnDiskCache<'sess> {
165166
query_result_index: FxHashMap(),
166167
prev_diagnostics_index: FxHashMap(),
167168
synthetic_expansion_infos: Lock::new(FxHashMap()),
169+
prev_interpret_alloc_index: Vec::new(),
168170
interpret_alloc_cache: RefCell::new(FxHashMap::default()),
169-
interpret_alloc_size: RefCell::new(FxHashMap::default()),
170171
}
171172
}
172173

@@ -199,7 +200,9 @@ impl<'sess> OnDiskCache<'sess> {
199200
type_shorthands: FxHashMap(),
200201
predicate_shorthands: FxHashMap(),
201202
expn_info_shorthands: FxHashMap(),
202-
interpret_alloc_shorthands: FxHashMap(),
203+
interpret_allocs: FxHashMap(),
204+
interpret_alloc_ids: FxHashSet(),
205+
interpret_allocs_inverse: Vec::new(),
203206
codemap: CachingCodemapView::new(tcx.sess.codemap()),
204207
file_to_file_index,
205208
};
@@ -277,6 +280,31 @@ impl<'sess> OnDiskCache<'sess> {
277280
diagnostics_index
278281
};
279282

283+
let interpret_alloc_index = {
284+
let mut interpret_alloc_index = Vec::new();
285+
let mut n = 0;
286+
loop {
287+
let new_n = encoder.interpret_alloc_ids.len();
288+
for idx in n..new_n {
289+
let id = encoder.interpret_allocs_inverse[idx];
290+
let pos = AbsoluteBytePos::new(encoder.position());
291+
interpret_alloc_index.push(pos);
292+
interpret::specialized_encode_alloc_id(
293+
&mut encoder,
294+
tcx,
295+
id,
296+
)?;
297+
}
298+
// if we have found new ids, serialize those, too
299+
if n == new_n {
300+
// otherwise, abort
301+
break;
302+
}
303+
n = new_n;
304+
}
305+
interpret_alloc_index
306+
};
307+
280308
let sorted_cnums = sorted_cnums_including_local_crate(tcx);
281309
let prev_cnums: Vec<_> = sorted_cnums.iter().map(|&cnum| {
282310
let crate_name = tcx.original_crate_name(cnum).as_str().to_string();
@@ -291,6 +319,7 @@ impl<'sess> OnDiskCache<'sess> {
291319
prev_cnums,
292320
query_result_index,
293321
diagnostics_index,
322+
interpret_alloc_index,
294323
})?;
295324

296325
// Encode the position of the footer as the last 8 bytes of the
@@ -396,8 +425,8 @@ impl<'sess> OnDiskCache<'sess> {
396425
file_index_to_file: &self.file_index_to_file,
397426
file_index_to_stable_id: &self.file_index_to_stable_id,
398427
synthetic_expansion_infos: &self.synthetic_expansion_infos,
428+
prev_interpret_alloc_index: &self.prev_interpret_alloc_index,
399429
interpret_alloc_cache: &self.interpret_alloc_cache,
400-
interpret_alloc_size: &self.interpret_alloc_size,
401430
};
402431

403432
match decode_tagged(&mut decoder, dep_node_index) {
@@ -460,7 +489,8 @@ struct CacheDecoder<'a, 'tcx: 'a, 'x> {
460489
file_index_to_file: &'x Lock<FxHashMap<FileMapIndex, Lrc<FileMap>>>,
461490
file_index_to_stable_id: &'x FxHashMap<FileMapIndex, StableFilemapId>,
462491
interpret_alloc_cache: &'x RefCell<FxHashMap<usize, interpret::AllocId>>,
463-
interpret_alloc_size: &'x RefCell<FxHashMap<usize, usize>>,
492+
/// maps from index in the cache file to location in the cache file
493+
prev_interpret_alloc_index: &'x [AbsoluteBytePos],
464494
}
465495

466496
impl<'a, 'tcx, 'x> CacheDecoder<'a, 'tcx, 'x> {
@@ -584,36 +614,29 @@ implement_ty_decoder!( CacheDecoder<'a, 'tcx, 'x> );
584614
impl<'a, 'tcx, 'x> SpecializedDecoder<interpret::AllocId> for CacheDecoder<'a, 'tcx, 'x> {
585615
fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
586616
let tcx = self.tcx;
587-
let pos = TyDecoder::position(self);
588-
trace!("specialized_decode_alloc_id: {:?}", pos);
589-
if let Some(cached) = self.interpret_alloc_cache.borrow().get(&pos).cloned() {
590-
// if there's no end position we are currently deserializing a recursive
591-
// allocation
592-
if let Some(end) = self.interpret_alloc_size.borrow().get(&pos).cloned() {
593-
trace!("{} already cached as {:?}", pos, cached);
594-
// skip ahead
595-
self.opaque.set_position(end);
596-
return Ok(cached)
597-
}
617+
let idx = usize::decode(self)?;
618+
trace!("loading index {}", idx);
619+
620+
if let Some(cached) = self.interpret_alloc_cache.borrow().get(&idx).cloned() {
621+
trace!("loading alloc id {:?} from alloc_cache", cached);
622+
return Ok(cached);
598623
}
599-
let id = interpret::specialized_decode_alloc_id(
600-
self,
601-
tcx,
602-
pos,
603-
|this, pos, alloc_id| {
604-
assert!(this.interpret_alloc_cache.borrow_mut().insert(pos, alloc_id).is_none());
605-
},
606-
|this, shorthand| {
607-
// need to load allocation
608-
this.with_position(shorthand, |this| interpret::AllocId::decode(this))
609-
}
610-
)?;
611-
assert!(self
612-
.interpret_alloc_size
613-
.borrow_mut()
614-
.insert(pos, TyDecoder::position(self))
615-
.is_none());
616-
Ok(id)
624+
let pos = self.prev_interpret_alloc_index[idx].to_usize();
625+
trace!("loading position {}", pos);
626+
self.with_position(pos, |this| {
627+
interpret::specialized_decode_alloc_id(
628+
this,
629+
tcx,
630+
|this, alloc_id| {
631+
trace!("caching idx {} for alloc id {} at position {}", idx, alloc_id, pos);
632+
assert!(this
633+
.interpret_alloc_cache
634+
.borrow_mut()
635+
.insert(idx, alloc_id)
636+
.is_none());
637+
},
638+
)
639+
})
617640
}
618641
}
619642
impl<'a, 'tcx, 'x> SpecializedDecoder<Span> for CacheDecoder<'a, 'tcx, 'x> {
@@ -777,7 +800,9 @@ struct CacheEncoder<'enc, 'a, 'tcx, E>
777800
type_shorthands: FxHashMap<ty::Ty<'tcx>, usize>,
778801
predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
779802
expn_info_shorthands: FxHashMap<Mark, AbsoluteBytePos>,
780-
interpret_alloc_shorthands: FxHashMap<interpret::AllocId, usize>,
803+
interpret_allocs: FxHashMap<interpret::AllocId, usize>,
804+
interpret_allocs_inverse: Vec<interpret::AllocId>,
805+
interpret_alloc_ids: FxHashSet<interpret::AllocId>,
781806
codemap: CachingCodemapView<'tcx>,
782807
file_to_file_index: FxHashMap<*const FileMap, FileMapIndex>,
783808
}
@@ -814,27 +839,17 @@ impl<'enc, 'a, 'tcx, E> SpecializedEncoder<interpret::AllocId> for CacheEncoder<
814839
where E: 'enc + ty_codec::TyEncoder
815840
{
816841
fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
817-
use std::collections::hash_map::Entry;
818-
let tcx = self.tcx;
819-
let pos = self.position();
820-
let shorthand = match self.interpret_alloc_shorthands.entry(*alloc_id) {
821-
Entry::Occupied(entry) => Some(entry.get().clone()),
822-
Entry::Vacant(entry) => {
823-
// ensure that we don't place any AllocIds at the very beginning
824-
// of the metadata file, because that would end up making our indices
825-
// not special. It is essentially impossible for that to happen,
826-
// but let's make sure
827-
assert!(pos >= interpret::SHORTHAND_START);
828-
entry.insert(pos);
829-
None
830-
},
842+
let index = if self.interpret_alloc_ids.insert(*alloc_id) {
843+
let idx = self.interpret_alloc_ids.len() - 1;
844+
assert_eq!(idx, self.interpret_allocs_inverse.len());
845+
self.interpret_allocs_inverse.push(*alloc_id);
846+
assert!(self.interpret_allocs.insert(*alloc_id, idx).is_none());
847+
idx
848+
} else {
849+
self.interpret_allocs[alloc_id]
831850
};
832-
interpret::specialized_encode_alloc_id(
833-
self,
834-
tcx,
835-
*alloc_id,
836-
shorthand,
837-
)
851+
852+
index.encode(self)
838853
}
839854
}
840855

0 commit comments

Comments
 (0)