Skip to content

Commit 341d8b8

Browse files
committed
Auto merge of rust-lang#103808 - cjgillot:vec-cache, r=TaKO8Ki
Use an IndexVec to cache queries with index-like key Revival of an old idea. Let's see if it has more effect. r? `@ghost`
2 parents fd815a5 + bc9a202 commit 341d8b8

File tree

9 files changed

+232
-25
lines changed

9 files changed

+232
-25
lines changed

compiler/rustc_hir/src/hir_id.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
1+
use crate::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_ID};
22
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
33
use rustc_span::{def_id::DefPathHash, HashStableContext};
44
use std::fmt;
@@ -22,6 +22,18 @@ impl OwnerId {
2222
}
2323
}
2424

25+
impl rustc_index::vec::Idx for OwnerId {
26+
#[inline]
27+
fn new(idx: usize) -> Self {
28+
OwnerId { def_id: LocalDefId { local_def_index: DefIndex::from_usize(idx) } }
29+
}
30+
31+
#[inline]
32+
fn index(self) -> usize {
33+
self.def_id.local_def_index.as_usize()
34+
}
35+
}
36+
2537
impl<CTX: HashStableContext> HashStable<CTX> for OwnerId {
2638
#[inline]
2739
fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {

compiler/rustc_index/src/vec.rs

+2
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,12 @@ pub trait Idx: Copy + 'static + Eq + PartialEq + Debug + Hash {
1717

1818
fn index(self) -> usize;
1919

20+
#[inline]
2021
fn increment_by(&mut self, amount: usize) {
2122
*self = self.plus(amount);
2223
}
2324

25+
#[inline]
2426
fn plus(self, amount: usize) -> Self {
2527
Self::new(self.index() + amount)
2628
}

compiler/rustc_query_impl/src/keys.rs renamed to compiler/rustc_middle/src/query/keys.rs

+16-7
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
//! Defines the set of legal keys that can be used in queries.
22
3+
use crate::infer::canonical::Canonical;
4+
use crate::mir;
5+
use crate::traits;
6+
use crate::ty::fast_reject::SimplifiedType;
7+
use crate::ty::subst::{GenericArg, SubstsRef};
8+
use crate::ty::{self, layout::TyAndLayout, Ty, TyCtxt};
39
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
410
use rustc_hir::hir_id::{HirId, OwnerId};
5-
use rustc_middle::infer::canonical::Canonical;
6-
use rustc_middle::mir;
7-
use rustc_middle::traits;
8-
use rustc_middle::ty::fast_reject::SimplifiedType;
9-
use rustc_middle::ty::subst::{GenericArg, SubstsRef};
10-
use rustc_middle::ty::{self, layout::TyAndLayout, Ty, TyCtxt};
11+
use rustc_query_system::query::{DefaultCacheSelector, VecCacheSelector};
1112
use rustc_span::symbol::{Ident, Symbol};
1213
use rustc_span::{Span, DUMMY_SP};
1314

1415
/// The `Key` trait controls what types can legally be used as the key
1516
/// for a query.
16-
pub trait Key {
17+
pub trait Key: Sized {
18+
type CacheSelector = DefaultCacheSelector<Self>;
19+
1720
/// Given an instance of this key, what crate is it referring to?
1821
/// This is used to find the provider.
1922
fn query_crate_is_local(&self) -> bool;
@@ -100,6 +103,8 @@ impl<'tcx> Key for mir::interpret::LitToConstInput<'tcx> {
100103
}
101104

102105
impl Key for CrateNum {
106+
type CacheSelector = VecCacheSelector<Self>;
107+
103108
#[inline(always)]
104109
fn query_crate_is_local(&self) -> bool {
105110
*self == LOCAL_CRATE
@@ -110,6 +115,8 @@ impl Key for CrateNum {
110115
}
111116

112117
impl Key for OwnerId {
118+
type CacheSelector = VecCacheSelector<Self>;
119+
113120
#[inline(always)]
114121
fn query_crate_is_local(&self) -> bool {
115122
true
@@ -123,6 +130,8 @@ impl Key for OwnerId {
123130
}
124131

125132
impl Key for LocalDefId {
133+
type CacheSelector = VecCacheSelector<Self>;
134+
126135
#[inline(always)]
127136
fn query_crate_is_local(&self) -> bool {
128137
true

compiler/rustc_middle/src/query/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
use crate::ty::{self, print::describe_as_module, TyCtxt};
88
use rustc_span::def_id::LOCAL_CRATE;
99

10+
mod keys;
11+
pub use keys::Key;
12+
1013
// Each of these queries corresponds to a function pointer field in the
1114
// `Providers` struct for requesting a value of that type, and a method
1215
// on `tcx: TyCtxt` (and `tcx.at(span)`) for doing that request in a way

compiler/rustc_middle/src/ty/query.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use crate::mir::interpret::{
1515
};
1616
use crate::mir::interpret::{LitToConstError, LitToConstInput};
1717
use crate::mir::mono::CodegenUnit;
18+
use crate::query::Key;
1819
use crate::thir;
1920
use crate::traits::query::{
2021
CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,
@@ -121,10 +122,10 @@ macro_rules! query_helper_param_ty {
121122

122123
macro_rules! query_storage {
123124
([][$K:ty, $V:ty]) => {
124-
<DefaultCacheSelector as CacheSelector<$K, $V>>::Cache
125+
<<$K as Key>::CacheSelector as CacheSelector<'tcx, $V>>::Cache
125126
};
126127
([(arena_cache) $($rest:tt)*][$K:ty, $V:ty]) => {
127-
<ArenaCacheSelector<'tcx> as CacheSelector<$K, $V>>::Cache
128+
<<$K as Key>::CacheSelector as CacheSelector<'tcx, $V>>::ArenaCache
128129
};
129130
([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
130131
query_storage!([$($modifiers)*][$($args)*])

compiler/rustc_query_impl/src/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ use rustc_query_system::query::*;
3232
#[cfg(parallel_compiler)]
3333
pub use rustc_query_system::query::{deadlock, QueryContext};
3434

35-
mod keys;
36-
use keys::Key;
35+
use rustc_middle::query::Key;
3736

3837
pub use rustc_query_system::query::QueryConfig;
3938
pub(crate) use rustc_query_system::query::QueryVTable;

compiler/rustc_query_impl/src/plumbing.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
//! generate the actual methods on tcx which find and execute the provider,
33
//! manage the caches, and so forth.
44
5-
use crate::keys::Key;
65
use crate::on_disk_cache::{CacheDecoder, CacheEncoder, EncodedDepNodeIndex};
76
use crate::profiling_support::QueryKeyStringCache;
87
use crate::{on_disk_cache, Queries};
@@ -12,6 +11,7 @@ use rustc_errors::{Diagnostic, Handler};
1211
use rustc_middle::dep_graph::{
1312
self, DepKind, DepKindStruct, DepNode, DepNodeIndex, SerializedDepNodeIndex,
1413
};
14+
use rustc_middle::query::Key;
1515
use rustc_middle::ty::tls::{self, ImplicitCtxt};
1616
use rustc_middle::ty::{self, TyCtxt};
1717
use rustc_query_system::dep_graph::{DepNodeParams, HasDepContext};

compiler/rustc_query_system/src/query/caches.rs

+192-11
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,17 @@ use rustc_data_structures::sharded::Sharded;
88
#[cfg(not(parallel_compiler))]
99
use rustc_data_structures::sync::Lock;
1010
use rustc_data_structures::sync::WorkerLocal;
11+
use rustc_index::vec::{Idx, IndexVec};
1112
use std::default::Default;
1213
use std::fmt::Debug;
1314
use std::hash::Hash;
1415
use std::marker::PhantomData;
1516

16-
pub trait CacheSelector<K, V> {
17-
type Cache;
17+
pub trait CacheSelector<'tcx, V> {
18+
type Cache
19+
where
20+
V: Clone;
21+
type ArenaCache;
1822
}
1923

2024
pub trait QueryStorage {
@@ -47,10 +51,13 @@ pub trait QueryCache: QueryStorage + Sized {
4751
fn iter(&self, f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex));
4852
}
4953

50-
pub struct DefaultCacheSelector;
54+
pub struct DefaultCacheSelector<K>(PhantomData<K>);
5155

52-
impl<K: Eq + Hash, V: Clone> CacheSelector<K, V> for DefaultCacheSelector {
53-
type Cache = DefaultCache<K, V>;
56+
impl<'tcx, K: Eq + Hash, V: 'tcx> CacheSelector<'tcx, V> for DefaultCacheSelector<K> {
57+
type Cache = DefaultCache<K, V>
58+
where
59+
V: Clone;
60+
type ArenaCache = ArenaCache<'tcx, K, V>;
5461
}
5562

5663
pub struct DefaultCache<K, V> {
@@ -134,12 +141,6 @@ where
134141
}
135142
}
136143

137-
pub struct ArenaCacheSelector<'tcx>(PhantomData<&'tcx ()>);
138-
139-
impl<'tcx, K: Eq + Hash, V: 'tcx> CacheSelector<K, V> for ArenaCacheSelector<'tcx> {
140-
type Cache = ArenaCache<'tcx, K, V>;
141-
}
142-
143144
pub struct ArenaCache<'tcx, K, V> {
144145
arena: WorkerLocal<TypedArena<(V, DepNodeIndex)>>,
145146
#[cfg(parallel_compiler)]
@@ -224,3 +225,183 @@ where
224225
}
225226
}
226227
}
228+
229+
pub struct VecCacheSelector<K>(PhantomData<K>);
230+
231+
impl<'tcx, K: Idx, V: 'tcx> CacheSelector<'tcx, V> for VecCacheSelector<K> {
232+
type Cache = VecCache<K, V>
233+
where
234+
V: Clone;
235+
type ArenaCache = VecArenaCache<'tcx, K, V>;
236+
}
237+
238+
pub struct VecCache<K: Idx, V> {
239+
#[cfg(parallel_compiler)]
240+
cache: Sharded<IndexVec<K, Option<(V, DepNodeIndex)>>>,
241+
#[cfg(not(parallel_compiler))]
242+
cache: Lock<IndexVec<K, Option<(V, DepNodeIndex)>>>,
243+
}
244+
245+
impl<K: Idx, V> Default for VecCache<K, V> {
246+
fn default() -> Self {
247+
VecCache { cache: Default::default() }
248+
}
249+
}
250+
251+
impl<K: Eq + Idx, V: Clone + Debug> QueryStorage for VecCache<K, V> {
252+
type Value = V;
253+
type Stored = V;
254+
255+
#[inline]
256+
fn store_nocache(&self, value: Self::Value) -> Self::Stored {
257+
// We have no dedicated storage
258+
value
259+
}
260+
}
261+
262+
impl<K, V> QueryCache for VecCache<K, V>
263+
where
264+
K: Eq + Idx + Clone + Debug,
265+
V: Clone + Debug,
266+
{
267+
type Key = K;
268+
269+
#[inline(always)]
270+
fn lookup<R, OnHit>(&self, key: &K, on_hit: OnHit) -> Result<R, ()>
271+
where
272+
OnHit: FnOnce(&V, DepNodeIndex) -> R,
273+
{
274+
#[cfg(parallel_compiler)]
275+
let lock = self.cache.get_shard_by_hash(key.index() as u64).lock();
276+
#[cfg(not(parallel_compiler))]
277+
let lock = self.cache.lock();
278+
if let Some(Some(value)) = lock.get(*key) {
279+
let hit_result = on_hit(&value.0, value.1);
280+
Ok(hit_result)
281+
} else {
282+
Err(())
283+
}
284+
}
285+
286+
#[inline]
287+
fn complete(&self, key: K, value: V, index: DepNodeIndex) -> Self::Stored {
288+
#[cfg(parallel_compiler)]
289+
let mut lock = self.cache.get_shard_by_hash(key.index() as u64).lock();
290+
#[cfg(not(parallel_compiler))]
291+
let mut lock = self.cache.lock();
292+
lock.insert(key, (value.clone(), index));
293+
value
294+
}
295+
296+
fn iter(&self, f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex)) {
297+
#[cfg(parallel_compiler)]
298+
{
299+
let shards = self.cache.lock_shards();
300+
for shard in shards.iter() {
301+
for (k, v) in shard.iter_enumerated() {
302+
if let Some(v) = v {
303+
f(&k, &v.0, v.1);
304+
}
305+
}
306+
}
307+
}
308+
#[cfg(not(parallel_compiler))]
309+
{
310+
let map = self.cache.lock();
311+
for (k, v) in map.iter_enumerated() {
312+
if let Some(v) = v {
313+
f(&k, &v.0, v.1);
314+
}
315+
}
316+
}
317+
}
318+
}
319+
320+
pub struct VecArenaCache<'tcx, K: Idx, V> {
321+
arena: WorkerLocal<TypedArena<(V, DepNodeIndex)>>,
322+
#[cfg(parallel_compiler)]
323+
cache: Sharded<IndexVec<K, Option<&'tcx (V, DepNodeIndex)>>>,
324+
#[cfg(not(parallel_compiler))]
325+
cache: Lock<IndexVec<K, Option<&'tcx (V, DepNodeIndex)>>>,
326+
}
327+
328+
impl<'tcx, K: Idx, V> Default for VecArenaCache<'tcx, K, V> {
329+
fn default() -> Self {
330+
VecArenaCache {
331+
arena: WorkerLocal::new(|_| TypedArena::default()),
332+
cache: Default::default(),
333+
}
334+
}
335+
}
336+
337+
impl<'tcx, K: Eq + Idx, V: Debug + 'tcx> QueryStorage for VecArenaCache<'tcx, K, V> {
338+
type Value = V;
339+
type Stored = &'tcx V;
340+
341+
#[inline]
342+
fn store_nocache(&self, value: Self::Value) -> Self::Stored {
343+
let value = self.arena.alloc((value, DepNodeIndex::INVALID));
344+
let value = unsafe { &*(&value.0 as *const _) };
345+
&value
346+
}
347+
}
348+
349+
impl<'tcx, K, V: 'tcx> QueryCache for VecArenaCache<'tcx, K, V>
350+
where
351+
K: Eq + Idx + Clone + Debug,
352+
V: Debug,
353+
{
354+
type Key = K;
355+
356+
#[inline(always)]
357+
fn lookup<R, OnHit>(&self, key: &K, on_hit: OnHit) -> Result<R, ()>
358+
where
359+
OnHit: FnOnce(&&'tcx V, DepNodeIndex) -> R,
360+
{
361+
#[cfg(parallel_compiler)]
362+
let lock = self.cache.get_shard_by_hash(key.index() as u64).lock();
363+
#[cfg(not(parallel_compiler))]
364+
let lock = self.cache.lock();
365+
if let Some(Some(value)) = lock.get(*key) {
366+
let hit_result = on_hit(&&value.0, value.1);
367+
Ok(hit_result)
368+
} else {
369+
Err(())
370+
}
371+
}
372+
373+
#[inline]
374+
fn complete(&self, key: K, value: V, index: DepNodeIndex) -> Self::Stored {
375+
let value = self.arena.alloc((value, index));
376+
let value = unsafe { &*(value as *const _) };
377+
#[cfg(parallel_compiler)]
378+
let mut lock = self.cache.get_shard_by_hash(key.index() as u64).lock();
379+
#[cfg(not(parallel_compiler))]
380+
let mut lock = self.cache.lock();
381+
lock.insert(key, value);
382+
&value.0
383+
}
384+
385+
fn iter(&self, f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex)) {
386+
#[cfg(parallel_compiler)]
387+
{
388+
let shards = self.cache.lock_shards();
389+
for shard in shards.iter() {
390+
for (k, v) in shard.iter_enumerated() {
391+
if let Some(v) = v {
392+
f(&k, &v.0, v.1);
393+
}
394+
}
395+
}
396+
}
397+
#[cfg(not(parallel_compiler))]
398+
{
399+
let map = self.cache.lock();
400+
for (k, v) in map.iter_enumerated() {
401+
if let Some(v) = v {
402+
f(&k, &v.0, v.1);
403+
}
404+
}
405+
}
406+
}
407+
}

compiler/rustc_query_system/src/query/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ pub use self::job::{print_query_stack, QueryInfo, QueryJob, QueryJobId, QueryJob
88

99
mod caches;
1010
pub use self::caches::{
11-
ArenaCacheSelector, CacheSelector, DefaultCacheSelector, QueryCache, QueryStorage,
11+
CacheSelector, DefaultCacheSelector, QueryCache, QueryStorage, VecCacheSelector,
1212
};
1313

1414
mod config;

0 commit comments

Comments
 (0)