]> git.lizzy.rs Git - rust.git/blob - src/librustc_query_system/query/plumbing.rs
b371a914c6fce02304d26bd16c237862b4a91e7c
[rust.git] / src / librustc_query_system / query / plumbing.rs
1 //! The implementation of the query system itself. This defines the macros that
2 //! generate the actual methods on tcx which find and execute the provider,
3 //! manage the caches, and so forth.
4
5 use crate::dep_graph::{DepKind, DepNode};
6 use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
7 use crate::query::caches::QueryCache;
8 use crate::query::config::QueryDescription;
9 use crate::query::job::{QueryInfo, QueryJob, QueryJobId, QueryJobInfo, QueryShardJobId};
10 use crate::query::QueryContext;
11
12 #[cfg(not(parallel_compiler))]
13 use rustc_data_structures::cold_path;
14 use rustc_data_structures::fingerprint::Fingerprint;
15 use rustc_data_structures::fx::{FxHashMap, FxHasher};
16 use rustc_data_structures::sharded::Sharded;
17 use rustc_data_structures::sync::{Lock, LockGuard};
18 use rustc_data_structures::thin_vec::ThinVec;
19 use rustc_errors::{Diagnostic, FatalError};
20 use rustc_span::source_map::DUMMY_SP;
21 use rustc_span::Span;
22 use std::collections::hash_map::Entry;
23 use std::convert::TryFrom;
24 use std::fmt::Debug;
25 use std::hash::{Hash, Hasher};
26 use std::mem;
27 use std::num::NonZeroU32;
28 use std::ptr;
29 #[cfg(debug_assertions)]
30 use std::sync::atomic::{AtomicUsize, Ordering};
31
32 pub struct QueryStateShard<CTX: QueryContext, K, C> {
33     pub(super) cache: C,
34     active: FxHashMap<K, QueryResult<CTX>>,
35
36     /// Used to generate unique ids for active jobs.
37     jobs: u32,
38 }
39
40 impl<CTX: QueryContext, K, C: Default> Default for QueryStateShard<CTX, K, C> {
41     fn default() -> QueryStateShard<CTX, K, C> {
42         QueryStateShard { cache: Default::default(), active: Default::default(), jobs: 0 }
43     }
44 }
45
46 pub struct QueryState<CTX: QueryContext, C: QueryCache> {
47     cache: C,
48     shards: Sharded<QueryStateShard<CTX, C::Key, C::Sharded>>,
49     #[cfg(debug_assertions)]
50     pub cache_hits: AtomicUsize,
51 }
52
53 impl<CTX: QueryContext, C: QueryCache> QueryState<CTX, C> {
54     pub(super) fn get_lookup<'tcx>(
55         &'tcx self,
56         key: &C::Key,
57     ) -> QueryLookup<'tcx, CTX, C::Key, C::Sharded> {
58         // We compute the key's hash once and then use it for both the
59         // shard lookup and the hashmap lookup. This relies on the fact
60         // that both of them use `FxHasher`.
61         let mut hasher = FxHasher::default();
62         key.hash(&mut hasher);
63         let key_hash = hasher.finish();
64
65         let shard = self.shards.get_shard_index_by_hash(key_hash);
66         let lock = self.shards.get_shard_by_index(shard).lock();
67         QueryLookup { key_hash, shard, lock }
68     }
69 }
70
71 /// Indicates the state of a query for a given key in a query map.
72 enum QueryResult<CTX: QueryContext> {
73     /// An already executing query. The query job can be used to await for its completion.
74     Started(QueryJob<CTX>),
75
76     /// The query panicked. Queries trying to wait on this will raise a fatal error which will
77     /// silently panic.
78     Poisoned,
79 }
80
81 impl<CTX: QueryContext, C: QueryCache> QueryState<CTX, C> {
82     pub fn iter_results<R>(
83         &self,
84         f: impl for<'a> FnOnce(
85             Box<dyn Iterator<Item = (&'a C::Key, &'a C::Value, DepNodeIndex)> + 'a>,
86         ) -> R,
87     ) -> R {
88         self.cache.iter(&self.shards, |shard| &mut shard.cache, f)
89     }
90
91     pub fn all_inactive(&self) -> bool {
92         let shards = self.shards.lock_shards();
93         shards.iter().all(|shard| shard.active.is_empty())
94     }
95
96     pub fn try_collect_active_jobs(
97         &self,
98         kind: CTX::DepKind,
99         make_query: fn(C::Key) -> CTX::Query,
100         jobs: &mut FxHashMap<QueryJobId<CTX::DepKind>, QueryJobInfo<CTX>>,
101     ) -> Option<()>
102     where
103         C::Key: Clone,
104     {
105         // We use try_lock_shards here since we are called from the
106         // deadlock handler, and this shouldn't be locked.
107         let shards = self.shards.try_lock_shards()?;
108         let shards = shards.iter().enumerate();
109         jobs.extend(shards.flat_map(|(shard_id, shard)| {
110             shard.active.iter().filter_map(move |(k, v)| {
111                 if let QueryResult::Started(ref job) = *v {
112                     let id =
113                         QueryJobId { job: job.id, shard: u16::try_from(shard_id).unwrap(), kind };
114                     let info = QueryInfo { span: job.span, query: make_query(k.clone()) };
115                     Some((id, QueryJobInfo { info, job: job.clone() }))
116                 } else {
117                     None
118                 }
119             })
120         }));
121
122         Some(())
123     }
124 }
125
126 impl<CTX: QueryContext, C: QueryCache> Default for QueryState<CTX, C> {
127     fn default() -> QueryState<CTX, C> {
128         QueryState {
129             cache: C::default(),
130             shards: Default::default(),
131             #[cfg(debug_assertions)]
132             cache_hits: AtomicUsize::new(0),
133         }
134     }
135 }
136
137 /// Values used when checking a query cache which can be reused on a cache-miss to execute the query.
138 pub struct QueryLookup<'tcx, CTX: QueryContext, K, C> {
139     pub(super) key_hash: u64,
140     shard: usize,
141     pub(super) lock: LockGuard<'tcx, QueryStateShard<CTX, K, C>>,
142 }
143
144 /// A type representing the responsibility to execute the job in the `job` field.
145 /// This will poison the relevant query if dropped.
146 struct JobOwner<'tcx, CTX: QueryContext, C>
147 where
148     C: QueryCache,
149     C::Key: Eq + Hash + Clone + Debug,
150     C::Value: Clone,
151 {
152     state: &'tcx QueryState<CTX, C>,
153     key: C::Key,
154     id: QueryJobId<CTX::DepKind>,
155 }
156
157 impl<'tcx, CTX: QueryContext, C> JobOwner<'tcx, CTX, C>
158 where
159     C: QueryCache,
160     C::Key: Eq + Hash + Clone + Debug,
161     C::Value: Clone,
162 {
163     /// Either gets a `JobOwner` corresponding the query, allowing us to
164     /// start executing the query, or returns with the result of the query.
165     /// This function assumes that `try_get_cached` is already called and returned `lookup`.
166     /// If the query is executing elsewhere, this will wait for it and return the result.
167     /// If the query panicked, this will silently panic.
168     ///
169     /// This function is inlined because that results in a noticeable speed-up
170     /// for some compile-time benchmarks.
171     #[inline(always)]
172     fn try_start<'a, 'b, Q>(
173         tcx: CTX,
174         span: Span,
175         key: &C::Key,
176         mut lookup: QueryLookup<'a, CTX, C::Key, C::Sharded>,
177     ) -> TryGetJob<'b, CTX, C>
178     where
179         Q: QueryDescription<CTX, Key = C::Key, Value = C::Value, Cache = C>,
180         CTX: QueryContext,
181     {
182         let lock = &mut *lookup.lock;
183
184         let (latch, mut _query_blocked_prof_timer) = match lock.active.entry((*key).clone()) {
185             Entry::Occupied(mut entry) => {
186                 match entry.get_mut() {
187                     QueryResult::Started(job) => {
188                         // For parallel queries, we'll block and wait until the query running
189                         // in another thread has completed. Record how long we wait in the
190                         // self-profiler.
191                         let _query_blocked_prof_timer = if cfg!(parallel_compiler) {
192                             Some(tcx.profiler().query_blocked())
193                         } else {
194                             None
195                         };
196
197                         // Create the id of the job we're waiting for
198                         let id = QueryJobId::new(job.id, lookup.shard, Q::DEP_KIND);
199
200                         (job.latch(id), _query_blocked_prof_timer)
201                     }
202                     QueryResult::Poisoned => FatalError.raise(),
203                 }
204             }
205             Entry::Vacant(entry) => {
206                 // No job entry for this query. Return a new one to be started later.
207
208                 // Generate an id unique within this shard.
209                 let id = lock.jobs.checked_add(1).unwrap();
210                 lock.jobs = id;
211                 let id = QueryShardJobId(NonZeroU32::new(id).unwrap());
212
213                 let global_id = QueryJobId::new(id, lookup.shard, Q::DEP_KIND);
214
215                 let job = tcx.current_query_job();
216                 let job = QueryJob::new(id, span, job);
217
218                 entry.insert(QueryResult::Started(job));
219
220                 let owner =
221                     JobOwner { state: Q::query_state(tcx), id: global_id, key: (*key).clone() };
222                 return TryGetJob::NotYetStarted(owner);
223             }
224         };
225         mem::drop(lookup.lock);
226
227         // If we are single-threaded we know that we have cycle error,
228         // so we just return the error.
229         #[cfg(not(parallel_compiler))]
230         return TryGetJob::Cycle(cold_path(|| {
231             Q::handle_cycle_error(tcx, latch.find_cycle_in_stack(tcx, span))
232         }));
233
234         // With parallel queries we might just have to wait on some other
235         // thread.
236         #[cfg(parallel_compiler)]
237         {
238             let result = latch.wait_on(tcx, span);
239
240             if let Err(cycle) = result {
241                 return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
242             }
243
244             let cached = try_get_cached(
245                 tcx,
246                 Q::query_state(tcx),
247                 (*key).clone(),
248                 |value, index| (value.clone(), index),
249                 |_, _| panic!("value must be in cache after waiting"),
250             );
251
252             if let Some(prof_timer) = _query_blocked_prof_timer.take() {
253                 prof_timer.finish_with_query_invocation_id(cached.1.into());
254             }
255
256             return TryGetJob::JobCompleted(cached);
257         }
258     }
259
260     /// Completes the query by updating the query cache with the `result`,
261     /// signals the waiter and forgets the JobOwner, so it won't poison the query
262     #[inline(always)]
263     fn complete(self, tcx: CTX, result: &C::Value, dep_node_index: DepNodeIndex) {
264         // We can move out of `self` here because we `mem::forget` it below
265         let key = unsafe { ptr::read(&self.key) };
266         let state = self.state;
267
268         // Forget ourself so our destructor won't poison the query
269         mem::forget(self);
270
271         let job = {
272             let result = result.clone();
273             let mut lock = state.shards.get_shard_by_value(&key).lock();
274             let job = match lock.active.remove(&key).unwrap() {
275                 QueryResult::Started(job) => job,
276                 QueryResult::Poisoned => panic!(),
277             };
278             state.cache.complete(tcx, &mut lock.cache, key, result, dep_node_index);
279             job
280         };
281
282         job.signal_complete();
283     }
284 }
285
286 #[inline(always)]
287 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
288 where
289     F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
290 {
291     let diagnostics = Lock::new(ThinVec::new());
292     let result = f(Some(&diagnostics));
293     (result, diagnostics.into_inner())
294 }
295
296 impl<'tcx, CTX: QueryContext, C: QueryCache> Drop for JobOwner<'tcx, CTX, C>
297 where
298     C::Key: Eq + Hash + Clone + Debug,
299     C::Value: Clone,
300 {
301     #[inline(never)]
302     #[cold]
303     fn drop(&mut self) {
304         // Poison the query so jobs waiting on it panic.
305         let state = self.state;
306         let shard = state.shards.get_shard_by_value(&self.key);
307         let job = {
308             let mut shard = shard.lock();
309             let job = match shard.active.remove(&self.key).unwrap() {
310                 QueryResult::Started(job) => job,
311                 QueryResult::Poisoned => panic!(),
312             };
313             shard.active.insert(self.key.clone(), QueryResult::Poisoned);
314             job
315         };
316         // Also signal the completion of the job, so waiters
317         // will continue execution.
318         job.signal_complete();
319     }
320 }
321
322 #[derive(Clone)]
323 pub struct CycleError<Q> {
324     /// The query and related span that uses the cycle.
325     pub usage: Option<(Span, Q)>,
326     pub cycle: Vec<QueryInfo<Q>>,
327 }
328
329 /// The result of `try_start`.
330 enum TryGetJob<'tcx, CTX: QueryContext, C: QueryCache>
331 where
332     C::Key: Eq + Hash + Clone + Debug,
333     C::Value: Clone,
334 {
335     /// The query is not yet started. Contains a guard to the cache eventually used to start it.
336     NotYetStarted(JobOwner<'tcx, CTX, C>),
337
338     /// The query was already completed.
339     /// Returns the result of the query and its dep-node index
340     /// if it succeeded or a cycle error if it failed.
341     #[cfg(parallel_compiler)]
342     JobCompleted((C::Value, DepNodeIndex)),
343
344     /// Trying to execute the query resulted in a cycle.
345     Cycle(C::Value),
346 }
347
348 /// Checks if the query is already computed and in the cache.
349 /// It returns the shard index and a lock guard to the shard,
350 /// which will be used if the query is not in the cache and we need
351 /// to compute it.
352 #[inline(always)]
353 fn try_get_cached<CTX, C, R, OnHit, OnMiss>(
354     tcx: CTX,
355     state: &QueryState<CTX, C>,
356     key: C::Key,
357     // `on_hit` can be called while holding a lock to the query cache
358     on_hit: OnHit,
359     on_miss: OnMiss,
360 ) -> R
361 where
362     C: QueryCache,
363     CTX: QueryContext,
364     OnHit: FnOnce(&C::Value, DepNodeIndex) -> R,
365     OnMiss: FnOnce(C::Key, QueryLookup<'_, CTX, C::Key, C::Sharded>) -> R,
366 {
367     state.cache.lookup(
368         state,
369         key,
370         |value, index| {
371             if unlikely!(tcx.profiler().enabled()) {
372                 tcx.profiler().query_cache_hit(index.into());
373             }
374             #[cfg(debug_assertions)]
375             {
376                 state.cache_hits.fetch_add(1, Ordering::Relaxed);
377             }
378             on_hit(value, index)
379         },
380         on_miss,
381     )
382 }
383
384 #[inline(always)]
385 fn try_execute_query<Q, CTX>(
386     tcx: CTX,
387     span: Span,
388     key: Q::Key,
389     lookup: QueryLookup<'_, CTX, Q::Key, <Q::Cache as QueryCache>::Sharded>,
390 ) -> Q::Value
391 where
392     Q: QueryDescription<CTX>,
393     CTX: QueryContext,
394 {
395     let job = match JobOwner::try_start::<Q>(tcx, span, &key, lookup) {
396         TryGetJob::NotYetStarted(job) => job,
397         TryGetJob::Cycle(result) => return result,
398         #[cfg(parallel_compiler)]
399         TryGetJob::JobCompleted((v, index)) => {
400             tcx.dep_graph().read_index(index);
401             return v;
402         }
403     };
404
405     // Fast path for when incr. comp. is off. `to_dep_node` is
406     // expensive for some `DepKind`s.
407     if !tcx.dep_graph().is_fully_enabled() {
408         let null_dep_node = DepNode::new_no_params(DepKind::NULL);
409         return force_query_with_job::<Q, _>(tcx, key, job, null_dep_node).0;
410     }
411
412     if Q::ANON {
413         let prof_timer = tcx.profiler().query_provider();
414
415         let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
416             tcx.start_query(job.id, diagnostics, |tcx| {
417                 tcx.dep_graph().with_anon_task(Q::DEP_KIND, || Q::compute(tcx, key))
418             })
419         });
420
421         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
422
423         tcx.dep_graph().read_index(dep_node_index);
424
425         if unlikely!(!diagnostics.is_empty()) {
426             tcx.store_diagnostics_for_anon_node(dep_node_index, diagnostics);
427         }
428
429         job.complete(tcx, &result, dep_node_index);
430
431         return result;
432     }
433
434     let dep_node = Q::to_dep_node(tcx, &key);
435
436     if !Q::EVAL_ALWAYS {
437         // The diagnostics for this query will be
438         // promoted to the current session during
439         // `try_mark_green()`, so we can ignore them here.
440         let loaded = tcx.start_query(job.id, None, |tcx| {
441             let marked = tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node);
442             marked.map(|(prev_dep_node_index, dep_node_index)| {
443                 (
444                     load_from_disk_and_cache_in_memory::<Q, _>(
445                         tcx,
446                         key.clone(),
447                         prev_dep_node_index,
448                         dep_node_index,
449                         &dep_node,
450                     ),
451                     dep_node_index,
452                 )
453             })
454         });
455         if let Some((result, dep_node_index)) = loaded {
456             job.complete(tcx, &result, dep_node_index);
457             return result;
458         }
459     }
460
461     let (result, dep_node_index) = force_query_with_job::<Q, _>(tcx, key, job, dep_node);
462     tcx.dep_graph().read_index(dep_node_index);
463     result
464 }
465
466 fn load_from_disk_and_cache_in_memory<Q, CTX>(
467     tcx: CTX,
468     key: Q::Key,
469     prev_dep_node_index: SerializedDepNodeIndex,
470     dep_node_index: DepNodeIndex,
471     dep_node: &DepNode<CTX::DepKind>,
472 ) -> Q::Value
473 where
474     CTX: QueryContext,
475     Q: QueryDescription<CTX>,
476 {
477     // Note this function can be called concurrently from the same query
478     // We must ensure that this is handled correctly.
479
480     debug_assert!(tcx.dep_graph().is_green(dep_node));
481
482     // First we try to load the result from the on-disk cache.
483     let result = if Q::cache_on_disk(tcx, key.clone(), None) {
484         let prof_timer = tcx.profiler().incr_cache_loading();
485         let result = Q::try_load_from_disk(tcx, prev_dep_node_index);
486         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
487
488         // We always expect to find a cached result for things that
489         // can be forced from `DepNode`.
490         debug_assert!(
491             !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
492             "missing on-disk cache entry for {:?}",
493             dep_node
494         );
495         result
496     } else {
497         // Some things are never cached on disk.
498         None
499     };
500
501     let result = if let Some(result) = result {
502         result
503     } else {
504         // We could not load a result from the on-disk cache, so
505         // recompute.
506         let prof_timer = tcx.profiler().query_provider();
507
508         // The dep-graph for this computation is already in-place.
509         let result = tcx.dep_graph().with_ignore(|| Q::compute(tcx, key));
510
511         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
512
513         result
514     };
515
516     // If `-Zincremental-verify-ich` is specified, re-hash results from
517     // the cache and make sure that they have the expected fingerprint.
518     if unlikely!(tcx.incremental_verify_ich()) {
519         incremental_verify_ich::<Q, _>(tcx, &result, dep_node, dep_node_index);
520     }
521
522     result
523 }
524
525 #[inline(never)]
526 #[cold]
527 fn incremental_verify_ich<Q, CTX>(
528     tcx: CTX,
529     result: &Q::Value,
530     dep_node: &DepNode<CTX::DepKind>,
531     dep_node_index: DepNodeIndex,
532 ) where
533     CTX: QueryContext,
534     Q: QueryDescription<CTX>,
535 {
536     assert!(
537         Some(tcx.dep_graph().fingerprint_of(dep_node_index))
538             == tcx.dep_graph().prev_fingerprint_of(dep_node),
539         "fingerprint for green query instance not loaded from cache: {:?}",
540         dep_node,
541     );
542
543     debug!("BEGIN verify_ich({:?})", dep_node);
544     let mut hcx = tcx.create_stable_hashing_context();
545
546     let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
547     debug!("END verify_ich({:?})", dep_node);
548
549     let old_hash = tcx.dep_graph().fingerprint_of(dep_node_index);
550
551     assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
552 }
553
554 #[inline(always)]
555 fn force_query_with_job<Q, CTX>(
556     tcx: CTX,
557     key: Q::Key,
558     job: JobOwner<'_, CTX, Q::Cache>,
559     dep_node: DepNode<CTX::DepKind>,
560 ) -> (Q::Value, DepNodeIndex)
561 where
562     Q: QueryDescription<CTX>,
563     CTX: QueryContext,
564 {
565     // If the following assertion triggers, it can have two reasons:
566     // 1. Something is wrong with DepNode creation, either here or
567     //    in `DepGraph::try_mark_green()`.
568     // 2. Two distinct query keys get mapped to the same `DepNode`
569     //    (see for example #48923).
570     assert!(
571         !tcx.dep_graph().dep_node_exists(&dep_node),
572         "forcing query with already existing `DepNode`\n\
573                  - query-key: {:?}\n\
574                  - dep-node: {:?}",
575         key,
576         dep_node
577     );
578
579     let prof_timer = tcx.profiler().query_provider();
580
581     let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
582         tcx.start_query(job.id, diagnostics, |tcx| {
583             if Q::EVAL_ALWAYS {
584                 tcx.dep_graph().with_eval_always_task(
585                     dep_node,
586                     tcx,
587                     key,
588                     Q::compute,
589                     Q::hash_result,
590                 )
591             } else {
592                 tcx.dep_graph().with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
593             }
594         })
595     });
596
597     prof_timer.finish_with_query_invocation_id(dep_node_index.into());
598
599     if unlikely!(!diagnostics.is_empty()) {
600         if dep_node.kind != DepKind::NULL {
601             tcx.store_diagnostics(dep_node_index, diagnostics);
602         }
603     }
604
605     job.complete(tcx, &result, dep_node_index);
606
607     (result, dep_node_index)
608 }
609
610 #[inline(never)]
611 pub fn get_query<Q, CTX>(tcx: CTX, span: Span, key: Q::Key) -> Q::Value
612 where
613     Q: QueryDescription<CTX>,
614     CTX: QueryContext,
615 {
616     debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
617
618     try_get_cached(
619         tcx,
620         Q::query_state(tcx),
621         key,
622         |value, index| {
623             tcx.dep_graph().read_index(index);
624             value.clone()
625         },
626         |key, lookup| try_execute_query::<Q, _>(tcx, span, key, lookup),
627     )
628 }
629
630 /// Ensure that either this query has all green inputs or been executed.
631 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
632 ///
633 /// This function is particularly useful when executing passes for their
634 /// side-effects -- e.g., in order to report errors for erroneous programs.
635 ///
636 /// Note: The optimization is only available during incr. comp.
637 pub fn ensure_query<Q, CTX>(tcx: CTX, key: Q::Key)
638 where
639     Q: QueryDescription<CTX>,
640     CTX: QueryContext,
641 {
642     if Q::EVAL_ALWAYS {
643         let _ = get_query::<Q, _>(tcx, DUMMY_SP, key);
644         return;
645     }
646
647     // Ensuring an anonymous query makes no sense
648     assert!(!Q::ANON);
649
650     let dep_node = Q::to_dep_node(tcx, &key);
651
652     match tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node) {
653         None => {
654             // A None return from `try_mark_green_and_read` means that this is either
655             // a new dep node or that the dep node has already been marked red.
656             // Either way, we can't call `dep_graph.read()` as we don't have the
657             // DepNodeIndex. We must invoke the query itself. The performance cost
658             // this introduces should be negligible as we'll immediately hit the
659             // in-memory cache, or another query down the line will.
660             let _ = get_query::<Q, _>(tcx, DUMMY_SP, key);
661         }
662         Some((_, dep_node_index)) => {
663             tcx.profiler().query_cache_hit(dep_node_index.into());
664         }
665     }
666 }
667
668 pub fn force_query<Q, CTX>(tcx: CTX, key: Q::Key, span: Span, dep_node: DepNode<CTX::DepKind>)
669 where
670     Q: QueryDescription<CTX>,
671     CTX: QueryContext,
672 {
673     // We may be concurrently trying both execute and force a query.
674     // Ensure that only one of them runs the query.
675
676     try_get_cached(
677         tcx,
678         Q::query_state(tcx),
679         key,
680         |_, _| {
681             // Cache hit, do nothing
682         },
683         |key, lookup| {
684             let job = match JobOwner::try_start::<Q>(tcx, span, &key, lookup) {
685                 TryGetJob::NotYetStarted(job) => job,
686                 TryGetJob::Cycle(_) => return,
687                 #[cfg(parallel_compiler)]
688                 TryGetJob::JobCompleted(_) => return,
689             };
690             force_query_with_job::<Q, _>(tcx, key, job, dep_node);
691         },
692     );
693 }