]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_query_system/src/query/plumbing.rs
Auto merge of #93696 - Amanieu:compiler-builtins-0.1.68, r=Mark-Simulacrum
[rust.git] / compiler / rustc_query_system / src / 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::{DepContext, DepNode, DepNodeIndex, DepNodeParams};
6 use crate::query::caches::QueryCache;
7 use crate::query::config::{QueryDescription, QueryVtable};
8 use crate::query::job::{report_cycle, QueryInfo, QueryJob, QueryJobId, QueryJobInfo};
9 use crate::query::{QueryContext, QueryMap, QuerySideEffects, QueryStackFrame};
10 use rustc_data_structures::fingerprint::Fingerprint;
11 use rustc_data_structures::fx::{FxHashMap, FxHasher};
12 #[cfg(parallel_compiler)]
13 use rustc_data_structures::profiling::TimingGuard;
14 use rustc_data_structures::sharded::{get_shard_index_by_hash, Sharded};
15 use rustc_data_structures::sync::{Lock, LockGuard};
16 use rustc_data_structures::thin_vec::ThinVec;
17 use rustc_errors::{DiagnosticBuilder, FatalError};
18 use rustc_session::Session;
19 use rustc_span::{Span, DUMMY_SP};
20 use std::cell::Cell;
21 use std::collections::hash_map::Entry;
22 use std::fmt::Debug;
23 use std::hash::{Hash, Hasher};
24 use std::mem;
25 use std::ptr;
26
27 pub struct QueryCacheStore<C: QueryCache> {
28     cache: C,
29     shards: Sharded<C::Sharded>,
30 }
31
32 impl<C: QueryCache + Default> Default for QueryCacheStore<C> {
33     fn default() -> Self {
34         Self { cache: C::default(), shards: Default::default() }
35     }
36 }
37
38 /// Values used when checking a query cache which can be reused on a cache-miss to execute the query.
39 pub struct QueryLookup {
40     pub(super) key_hash: u64,
41     shard: usize,
42 }
43
44 // We compute the key's hash once and then use it for both the
45 // shard lookup and the hashmap lookup. This relies on the fact
46 // that both of them use `FxHasher`.
47 fn hash_for_shard<K: Hash>(key: &K) -> u64 {
48     let mut hasher = FxHasher::default();
49     key.hash(&mut hasher);
50     hasher.finish()
51 }
52
53 impl<C: QueryCache> QueryCacheStore<C> {
54     pub(super) fn get_lookup<'tcx>(
55         &'tcx self,
56         key: &C::Key,
57     ) -> (QueryLookup, LockGuard<'tcx, C::Sharded>) {
58         let key_hash = hash_for_shard(key);
59         let shard = get_shard_index_by_hash(key_hash);
60         let lock = self.shards.get_shard_by_index(shard).lock();
61         (QueryLookup { key_hash, shard }, lock)
62     }
63
64     pub fn iter_results(&self, f: &mut dyn FnMut(&C::Key, &C::Value, DepNodeIndex)) {
65         self.cache.iter(&self.shards, f)
66     }
67 }
68
69 struct QueryStateShard<K> {
70     active: FxHashMap<K, QueryResult>,
71 }
72
73 impl<K> Default for QueryStateShard<K> {
74     fn default() -> QueryStateShard<K> {
75         QueryStateShard { active: Default::default() }
76     }
77 }
78
79 pub struct QueryState<K> {
80     shards: Sharded<QueryStateShard<K>>,
81 }
82
83 /// Indicates the state of a query for a given key in a query map.
84 enum QueryResult {
85     /// An already executing query. The query job can be used to await for its completion.
86     Started(QueryJob),
87
88     /// The query panicked. Queries trying to wait on this will raise a fatal error which will
89     /// silently panic.
90     Poisoned,
91 }
92
93 impl<K> QueryState<K>
94 where
95     K: Eq + Hash + Clone + Debug,
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<CTX: Copy>(
103         &self,
104         tcx: CTX,
105         make_query: fn(CTX, K) -> QueryStackFrame,
106         jobs: &mut QueryMap,
107     ) -> Option<()> {
108         // We use try_lock_shards here since we are called from the
109         // deadlock handler, and this shouldn't be locked.
110         let shards = self.shards.try_lock_shards()?;
111         for shard in shards.iter() {
112             for (k, v) in shard.active.iter() {
113                 if let QueryResult::Started(ref job) = *v {
114                     let query = make_query(tcx, k.clone());
115                     jobs.insert(job.id, QueryJobInfo { query, job: job.clone() });
116                 }
117             }
118         }
119
120         Some(())
121     }
122 }
123
124 impl<K> Default for QueryState<K> {
125     fn default() -> QueryState<K> {
126         QueryState { shards: Default::default() }
127     }
128 }
129
130 /// A type representing the responsibility to execute the job in the `job` field.
131 /// This will poison the relevant query if dropped.
132 struct JobOwner<'tcx, K>
133 where
134     K: Eq + Hash + Clone,
135 {
136     state: &'tcx QueryState<K>,
137     key: K,
138     id: QueryJobId,
139 }
140
141 #[cold]
142 #[inline(never)]
143 fn mk_cycle<CTX, V, R>(
144     tcx: CTX,
145     error: CycleError,
146     handle_cycle_error: fn(CTX, DiagnosticBuilder<'_>) -> V,
147     cache: &dyn crate::query::QueryStorage<Value = V, Stored = R>,
148 ) -> R
149 where
150     CTX: QueryContext,
151     V: std::fmt::Debug,
152     R: Clone,
153 {
154     let error = report_cycle(tcx.dep_context().sess(), error);
155     let value = handle_cycle_error(tcx, error);
156     cache.store_nocache(value)
157 }
158
159 impl<'tcx, K> JobOwner<'tcx, K>
160 where
161     K: Eq + Hash + 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<'b, CTX>(
173         tcx: &'b CTX,
174         state: &'b QueryState<K>,
175         span: Span,
176         key: K,
177         lookup: QueryLookup,
178     ) -> TryGetJob<'b, K>
179     where
180         CTX: QueryContext,
181     {
182         let shard = lookup.shard;
183         let mut state_lock = state.shards.get_shard_by_index(shard).lock();
184         let lock = &mut *state_lock;
185
186         match lock.active.entry(key) {
187             Entry::Vacant(entry) => {
188                 let id = tcx.next_job_id();
189                 let job = tcx.current_query_job();
190                 let job = QueryJob::new(id, span, job);
191
192                 let key = entry.key().clone();
193                 entry.insert(QueryResult::Started(job));
194
195                 let owner = JobOwner { state, id, key };
196                 return TryGetJob::NotYetStarted(owner);
197             }
198             Entry::Occupied(mut entry) => {
199                 match entry.get_mut() {
200                     #[cfg(not(parallel_compiler))]
201                     QueryResult::Started(job) => {
202                         let id = job.id;
203                         drop(state_lock);
204
205                         // If we are single-threaded we know that we have cycle error,
206                         // so we just return the error.
207                         return TryGetJob::Cycle(id.find_cycle_in_stack(
208                             tcx.try_collect_active_jobs().unwrap(),
209                             &tcx.current_query_job(),
210                             span,
211                         ));
212                     }
213                     #[cfg(parallel_compiler)]
214                     QueryResult::Started(job) => {
215                         // For parallel queries, we'll block and wait until the query running
216                         // in another thread has completed. Record how long we wait in the
217                         // self-profiler.
218                         let query_blocked_prof_timer = tcx.dep_context().profiler().query_blocked();
219
220                         // Get the latch out
221                         let latch = job.latch();
222
223                         drop(state_lock);
224
225                         // With parallel queries we might just have to wait on some other
226                         // thread.
227                         let result = latch.wait_on(tcx.current_query_job(), span);
228
229                         match result {
230                             Ok(()) => TryGetJob::JobCompleted(query_blocked_prof_timer),
231                             Err(cycle) => TryGetJob::Cycle(cycle),
232                         }
233                     }
234                     QueryResult::Poisoned => FatalError.raise(),
235                 }
236             }
237         }
238     }
239
240     /// Completes the query by updating the query cache with the `result`,
241     /// signals the waiter and forgets the JobOwner, so it won't poison the query
242     fn complete<C>(
243         self,
244         cache: &QueryCacheStore<C>,
245         result: C::Value,
246         dep_node_index: DepNodeIndex,
247     ) -> C::Stored
248     where
249         C: QueryCache<Key = K>,
250     {
251         // We can move out of `self` here because we `mem::forget` it below
252         let key = unsafe { ptr::read(&self.key) };
253         let state = self.state;
254
255         // Forget ourself so our destructor won't poison the query
256         mem::forget(self);
257
258         let (job, result) = {
259             let key_hash = hash_for_shard(&key);
260             let shard = get_shard_index_by_hash(key_hash);
261             let job = {
262                 let mut lock = state.shards.get_shard_by_index(shard).lock();
263                 match lock.active.remove(&key).unwrap() {
264                     QueryResult::Started(job) => job,
265                     QueryResult::Poisoned => panic!(),
266                 }
267             };
268             let result = {
269                 let mut lock = cache.shards.get_shard_by_index(shard).lock();
270                 cache.cache.complete(&mut lock, key, result, dep_node_index)
271             };
272             (job, result)
273         };
274
275         job.signal_complete();
276         result
277     }
278 }
279
280 impl<'tcx, K> Drop for JobOwner<'tcx, K>
281 where
282     K: Eq + Hash + Clone,
283 {
284     #[inline(never)]
285     #[cold]
286     fn drop(&mut self) {
287         // Poison the query so jobs waiting on it panic.
288         let state = self.state;
289         let shard = state.shards.get_shard_by_value(&self.key);
290         let job = {
291             let mut shard = shard.lock();
292             let job = match shard.active.remove(&self.key).unwrap() {
293                 QueryResult::Started(job) => job,
294                 QueryResult::Poisoned => panic!(),
295             };
296             shard.active.insert(self.key.clone(), QueryResult::Poisoned);
297             job
298         };
299         // Also signal the completion of the job, so waiters
300         // will continue execution.
301         job.signal_complete();
302     }
303 }
304
305 #[derive(Clone)]
306 pub(crate) struct CycleError {
307     /// The query and related span that uses the cycle.
308     pub usage: Option<(Span, QueryStackFrame)>,
309     pub cycle: Vec<QueryInfo>,
310 }
311
312 /// The result of `try_start`.
313 enum TryGetJob<'tcx, K>
314 where
315     K: Eq + Hash + Clone,
316 {
317     /// The query is not yet started. Contains a guard to the cache eventually used to start it.
318     NotYetStarted(JobOwner<'tcx, K>),
319
320     /// The query was already completed.
321     /// Returns the result of the query and its dep-node index
322     /// if it succeeded or a cycle error if it failed.
323     #[cfg(parallel_compiler)]
324     JobCompleted(TimingGuard<'tcx>),
325
326     /// Trying to execute the query resulted in a cycle.
327     Cycle(CycleError),
328 }
329
330 /// Checks if the query is already computed and in the cache.
331 /// It returns the shard index and a lock guard to the shard,
332 /// which will be used if the query is not in the cache and we need
333 /// to compute it.
334 #[inline]
335 pub fn try_get_cached<'a, CTX, C, R, OnHit>(
336     tcx: CTX,
337     cache: &'a QueryCacheStore<C>,
338     key: &C::Key,
339     // `on_hit` can be called while holding a lock to the query cache
340     on_hit: OnHit,
341 ) -> Result<R, QueryLookup>
342 where
343     C: QueryCache,
344     CTX: DepContext,
345     OnHit: FnOnce(&C::Stored) -> R,
346 {
347     cache.cache.lookup(cache, &key, |value, index| {
348         if unlikely!(tcx.profiler().enabled()) {
349             tcx.profiler().query_cache_hit(index.into());
350         }
351         tcx.dep_graph().read_index(index);
352         on_hit(value)
353     })
354 }
355
356 fn try_execute_query<CTX, C>(
357     tcx: CTX,
358     state: &QueryState<C::Key>,
359     cache: &QueryCacheStore<C>,
360     span: Span,
361     key: C::Key,
362     lookup: QueryLookup,
363     dep_node: Option<DepNode<CTX::DepKind>>,
364     query: &QueryVtable<CTX, C::Key, C::Value>,
365 ) -> (C::Stored, Option<DepNodeIndex>)
366 where
367     C: QueryCache,
368     C::Key: Clone + DepNodeParams<CTX::DepContext>,
369     CTX: QueryContext,
370 {
371     match JobOwner::<'_, C::Key>::try_start(&tcx, state, span, key.clone(), lookup) {
372         TryGetJob::NotYetStarted(job) => {
373             let (result, dep_node_index) = execute_job(tcx, key, dep_node, query, job.id);
374             let result = job.complete(cache, result, dep_node_index);
375             (result, Some(dep_node_index))
376         }
377         TryGetJob::Cycle(error) => {
378             let result = mk_cycle(tcx, error, query.handle_cycle_error, &cache.cache);
379             (result, None)
380         }
381         #[cfg(parallel_compiler)]
382         TryGetJob::JobCompleted(query_blocked_prof_timer) => {
383             let (v, index) = cache
384                 .cache
385                 .lookup(cache, &key, |value, index| (value.clone(), index))
386                 .unwrap_or_else(|_| panic!("value must be in cache after waiting"));
387
388             if unlikely!(tcx.dep_context().profiler().enabled()) {
389                 tcx.dep_context().profiler().query_cache_hit(index.into());
390             }
391             query_blocked_prof_timer.finish_with_query_invocation_id(index.into());
392
393             (v, Some(index))
394         }
395     }
396 }
397
398 fn execute_job<CTX, K, V>(
399     tcx: CTX,
400     key: K,
401     mut dep_node_opt: Option<DepNode<CTX::DepKind>>,
402     query: &QueryVtable<CTX, K, V>,
403     job_id: QueryJobId,
404 ) -> (V, DepNodeIndex)
405 where
406     K: Clone + DepNodeParams<CTX::DepContext>,
407     V: Debug,
408     CTX: QueryContext,
409 {
410     let dep_graph = tcx.dep_context().dep_graph();
411
412     // Fast path for when incr. comp. is off.
413     if !dep_graph.is_fully_enabled() {
414         let prof_timer = tcx.dep_context().profiler().query_provider();
415         let result = tcx.start_query(job_id, None, || query.compute(*tcx.dep_context(), key));
416         let dep_node_index = dep_graph.next_virtual_depnode_index();
417         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
418         return (result, dep_node_index);
419     }
420
421     if !query.anon && !query.eval_always {
422         // `to_dep_node` is expensive for some `DepKind`s.
423         let dep_node =
424             dep_node_opt.get_or_insert_with(|| query.to_dep_node(*tcx.dep_context(), &key));
425
426         // The diagnostics for this query will be promoted to the current session during
427         // `try_mark_green()`, so we can ignore them here.
428         if let Some(ret) = tcx.start_query(job_id, None, || {
429             try_load_from_disk_and_cache_in_memory(tcx, &key, &dep_node, query)
430         }) {
431             return ret;
432         }
433     }
434
435     let prof_timer = tcx.dep_context().profiler().query_provider();
436     let diagnostics = Lock::new(ThinVec::new());
437
438     let (result, dep_node_index) = tcx.start_query(job_id, Some(&diagnostics), || {
439         if query.anon {
440             return dep_graph.with_anon_task(*tcx.dep_context(), query.dep_kind, || {
441                 query.compute(*tcx.dep_context(), key)
442             });
443         }
444
445         // `to_dep_node` is expensive for some `DepKind`s.
446         let dep_node = dep_node_opt.unwrap_or_else(|| query.to_dep_node(*tcx.dep_context(), &key));
447
448         dep_graph.with_task(dep_node, *tcx.dep_context(), key, query.compute, query.hash_result)
449     });
450
451     prof_timer.finish_with_query_invocation_id(dep_node_index.into());
452
453     let diagnostics = diagnostics.into_inner();
454     let side_effects = QuerySideEffects { diagnostics };
455
456     if unlikely!(!side_effects.is_empty()) {
457         if query.anon {
458             tcx.store_side_effects_for_anon_node(dep_node_index, side_effects);
459         } else {
460             tcx.store_side_effects(dep_node_index, side_effects);
461         }
462     }
463
464     (result, dep_node_index)
465 }
466
467 fn try_load_from_disk_and_cache_in_memory<CTX, K, V>(
468     tcx: CTX,
469     key: &K,
470     dep_node: &DepNode<CTX::DepKind>,
471     query: &QueryVtable<CTX, K, V>,
472 ) -> Option<(V, DepNodeIndex)>
473 where
474     K: Clone,
475     CTX: QueryContext,
476     V: Debug,
477 {
478     // Note this function can be called concurrently from the same query
479     // We must ensure that this is handled correctly.
480
481     let dep_graph = tcx.dep_context().dep_graph();
482     let (prev_dep_node_index, dep_node_index) = dep_graph.try_mark_green(tcx, &dep_node)?;
483
484     debug_assert!(dep_graph.is_green(dep_node));
485
486     // First we try to load the result from the on-disk cache.
487     // Some things are never cached on disk.
488     if query.cache_on_disk {
489         let prof_timer = tcx.dep_context().profiler().incr_cache_loading();
490
491         // The call to `with_query_deserialization` enforces that no new `DepNodes`
492         // are created during deserialization. See the docs of that method for more
493         // details.
494         let result = dep_graph
495             .with_query_deserialization(|| query.try_load_from_disk(tcx, prev_dep_node_index));
496
497         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
498
499         if let Some(result) = result {
500             if unlikely!(tcx.dep_context().sess().opts.debugging_opts.query_dep_graph) {
501                 dep_graph.mark_debug_loaded_from_disk(*dep_node)
502             }
503
504             let prev_fingerprint = tcx
505                 .dep_context()
506                 .dep_graph()
507                 .prev_fingerprint_of(dep_node)
508                 .unwrap_or(Fingerprint::ZERO);
509             // If `-Zincremental-verify-ich` is specified, re-hash results from
510             // the cache and make sure that they have the expected fingerprint.
511             //
512             // If not, we still seek to verify a subset of fingerprints loaded
513             // from disk. Re-hashing results is fairly expensive, so we can't
514             // currently afford to verify every hash. This subset should still
515             // give us some coverage of potential bugs though.
516             let try_verify = prev_fingerprint.as_value().1 % 32 == 0;
517             if unlikely!(
518                 try_verify || tcx.dep_context().sess().opts.debugging_opts.incremental_verify_ich
519             ) {
520                 incremental_verify_ich(*tcx.dep_context(), &result, dep_node, query);
521             }
522
523             return Some((result, dep_node_index));
524         }
525
526         // We always expect to find a cached result for things that
527         // can be forced from `DepNode`.
528         debug_assert!(
529             !tcx.dep_context().fingerprint_style(dep_node.kind).reconstructible(),
530             "missing on-disk cache entry for {:?}",
531             dep_node
532         );
533     }
534
535     // We could not load a result from the on-disk cache, so
536     // recompute.
537     let prof_timer = tcx.dep_context().profiler().query_provider();
538
539     // The dep-graph for this computation is already in-place.
540     let result = dep_graph.with_ignore(|| query.compute(*tcx.dep_context(), key.clone()));
541
542     prof_timer.finish_with_query_invocation_id(dep_node_index.into());
543
544     // Verify that re-running the query produced a result with the expected hash
545     // This catches bugs in query implementations, turning them into ICEs.
546     // For example, a query might sort its result by `DefId` - since `DefId`s are
547     // not stable across compilation sessions, the result could get up getting sorted
548     // in a different order when the query is re-run, even though all of the inputs
549     // (e.g. `DefPathHash` values) were green.
550     //
551     // See issue #82920 for an example of a miscompilation that would get turned into
552     // an ICE by this check
553     incremental_verify_ich(*tcx.dep_context(), &result, dep_node, query);
554
555     Some((result, dep_node_index))
556 }
557
558 fn incremental_verify_ich<CTX, K, V: Debug>(
559     tcx: CTX::DepContext,
560     result: &V,
561     dep_node: &DepNode<CTX::DepKind>,
562     query: &QueryVtable<CTX, K, V>,
563 ) where
564     CTX: QueryContext,
565 {
566     assert!(
567         tcx.dep_graph().is_green(dep_node),
568         "fingerprint for green query instance not loaded from cache: {:?}",
569         dep_node,
570     );
571
572     debug!("BEGIN verify_ich({:?})", dep_node);
573     let new_hash = query.hash_result.map_or(Fingerprint::ZERO, |f| {
574         let mut hcx = tcx.create_stable_hashing_context();
575         f(&mut hcx, result)
576     });
577     let old_hash = tcx.dep_graph().prev_fingerprint_of(dep_node);
578     debug!("END verify_ich({:?})", dep_node);
579
580     if Some(new_hash) != old_hash {
581         incremental_verify_ich_cold(tcx.sess(), DebugArg::from(&dep_node), DebugArg::from(&result));
582     }
583 }
584
585 // This DebugArg business is largely a mirror of std::fmt::ArgumentV1, which is
586 // currently not exposed publicly.
587 //
588 // The PR which added this attempted to use `&dyn Debug` instead, but that
589 // showed statistically significant worse compiler performance. It's not
590 // actually clear what the cause there was -- the code should be cold. If this
591 // can be replaced with `&dyn Debug` with on perf impact, then it probably
592 // should be.
593 extern "C" {
594     type Opaque;
595 }
596
597 struct DebugArg<'a> {
598     value: &'a Opaque,
599     fmt: fn(&Opaque, &mut std::fmt::Formatter<'_>) -> std::fmt::Result,
600 }
601
602 impl<'a, T> From<&'a T> for DebugArg<'a>
603 where
604     T: std::fmt::Debug,
605 {
606     fn from(value: &'a T) -> DebugArg<'a> {
607         DebugArg {
608             value: unsafe { std::mem::transmute(value) },
609             fmt: unsafe {
610                 std::mem::transmute(<T as std::fmt::Debug>::fmt as fn(_, _) -> std::fmt::Result)
611             },
612         }
613     }
614 }
615
616 impl std::fmt::Debug for DebugArg<'_> {
617     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
618         (self.fmt)(self.value, f)
619     }
620 }
621
622 // Note that this is marked #[cold] and intentionally takes the equivalent of
623 // `dyn Debug` for its arguments, as we want to avoid generating a bunch of
624 // different implementations for LLVM to chew on (and filling up the final
625 // binary, too).
626 #[cold]
627 fn incremental_verify_ich_cold(sess: &Session, dep_node: DebugArg<'_>, result: DebugArg<'_>) {
628     let run_cmd = if let Some(crate_name) = &sess.opts.crate_name {
629         format!("`cargo clean -p {}` or `cargo clean`", crate_name)
630     } else {
631         "`cargo clean`".to_string()
632     };
633
634     // When we emit an error message and panic, we try to debug-print the `DepNode`
635     // and query result. Unfortunately, this can cause us to run additional queries,
636     // which may result in another fingerprint mismatch while we're in the middle
637     // of processing this one. To avoid a double-panic (which kills the process
638     // before we can print out the query static), we print out a terse
639     // but 'safe' message if we detect a re-entrant call to this method.
640     thread_local! {
641         static INSIDE_VERIFY_PANIC: Cell<bool> = const { Cell::new(false) };
642     };
643
644     let old_in_panic = INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.replace(true));
645
646     if old_in_panic {
647         sess.struct_err(
648             "internal compiler error: re-entrant incremental verify failure, suppressing message",
649         )
650         .emit();
651     } else {
652         sess.struct_err(&format!("internal compiler error: encountered incremental compilation error with {:?}", dep_node))
653                 .help(&format!("This is a known issue with the compiler. Run {} to allow your project to compile", run_cmd))
654                 .note(&"Please follow the instructions below to create a bug report with the provided information")
655                 .note(&"See <https://github.com/rust-lang/rust/issues/84970> for more information")
656                 .emit();
657         panic!("Found unstable fingerprints for {:?}: {:?}", dep_node, result);
658     }
659
660     INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.set(old_in_panic));
661 }
662
663 /// Ensure that either this query has all green inputs or been executed.
664 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
665 /// Returns true if the query should still run.
666 ///
667 /// This function is particularly useful when executing passes for their
668 /// side-effects -- e.g., in order to report errors for erroneous programs.
669 ///
670 /// Note: The optimization is only available during incr. comp.
671 #[inline(never)]
672 fn ensure_must_run<CTX, K, V>(
673     tcx: CTX,
674     key: &K,
675     query: &QueryVtable<CTX, K, V>,
676 ) -> (bool, Option<DepNode<CTX::DepKind>>)
677 where
678     K: crate::dep_graph::DepNodeParams<CTX::DepContext>,
679     CTX: QueryContext,
680 {
681     if query.eval_always {
682         return (true, None);
683     }
684
685     // Ensuring an anonymous query makes no sense
686     assert!(!query.anon);
687
688     let dep_node = query.to_dep_node(*tcx.dep_context(), key);
689
690     let dep_graph = tcx.dep_context().dep_graph();
691     match dep_graph.try_mark_green(tcx, &dep_node) {
692         None => {
693             // A None return from `try_mark_green` means that this is either
694             // a new dep node or that the dep node has already been marked red.
695             // Either way, we can't call `dep_graph.read()` as we don't have the
696             // DepNodeIndex. We must invoke the query itself. The performance cost
697             // this introduces should be negligible as we'll immediately hit the
698             // in-memory cache, or another query down the line will.
699             (true, Some(dep_node))
700         }
701         Some((_, dep_node_index)) => {
702             dep_graph.read_index(dep_node_index);
703             tcx.dep_context().profiler().query_cache_hit(dep_node_index.into());
704             (false, None)
705         }
706     }
707 }
708
709 pub enum QueryMode {
710     Get,
711     Ensure,
712 }
713
714 pub fn get_query<Q, CTX>(
715     tcx: CTX,
716     span: Span,
717     key: Q::Key,
718     lookup: QueryLookup,
719     mode: QueryMode,
720 ) -> Option<Q::Stored>
721 where
722     Q: QueryDescription<CTX>,
723     Q::Key: DepNodeParams<CTX::DepContext>,
724     CTX: QueryContext,
725 {
726     let query = Q::make_vtable(tcx, &key);
727     let dep_node = if let QueryMode::Ensure = mode {
728         let (must_run, dep_node) = ensure_must_run(tcx, &key, &query);
729         if !must_run {
730             return None;
731         }
732         dep_node
733     } else {
734         None
735     };
736
737     debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
738     let (result, dep_node_index) = try_execute_query(
739         tcx,
740         Q::query_state(tcx),
741         Q::query_cache(tcx),
742         span,
743         key,
744         lookup,
745         dep_node,
746         &query,
747     );
748     if let Some(dep_node_index) = dep_node_index {
749         tcx.dep_context().dep_graph().read_index(dep_node_index)
750     }
751     Some(result)
752 }
753
754 pub fn force_query<Q, CTX>(tcx: CTX, key: Q::Key, dep_node: DepNode<CTX::DepKind>)
755 where
756     Q: QueryDescription<CTX>,
757     Q::Key: DepNodeParams<CTX::DepContext>,
758     CTX: QueryContext,
759 {
760     // We may be concurrently trying both execute and force a query.
761     // Ensure that only one of them runs the query.
762     let cache = Q::query_cache(tcx);
763     let cached = cache.cache.lookup(cache, &key, |_, index| {
764         if unlikely!(tcx.dep_context().profiler().enabled()) {
765             tcx.dep_context().profiler().query_cache_hit(index.into());
766         }
767     });
768
769     let lookup = match cached {
770         Ok(()) => return,
771         Err(lookup) => lookup,
772     };
773
774     let query = Q::make_vtable(tcx, &key);
775     let state = Q::query_state(tcx);
776     debug_assert!(!query.anon);
777
778     try_execute_query(tcx, state, cache, DUMMY_SP, key, lookup, Some(dep_node), &query);
779 }