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