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