]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/query/plumbing.rs
ebaa31d703f8e0195fa969b8cb1364fd0b83665d
[rust.git] / src / librustc / ty / 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::{DepNodeIndex, DepNode, DepKind, SerializedDepNodeIndex};
6 use crate::ty::tls;
7 use crate::ty::{TyCtxt};
8 use crate::ty::query::Query;
9 use crate::ty::query::config::{QueryConfig, QueryDescription};
10 use crate::ty::query::job::{QueryJob, QueryResult, QueryInfo};
11 use crate::ty::item_path;
12
13 use crate::util::common::{profq_msg, ProfileQueriesMsg, QueryMsg};
14
15 use errors::DiagnosticBuilder;
16 use errors::Level;
17 use errors::Diagnostic;
18 use errors::FatalError;
19 use rustc_data_structures::fx::{FxHashMap};
20 use rustc_data_structures::sync::{Lrc, Lock};
21 use rustc_data_structures::thin_vec::ThinVec;
22 #[cfg(not(parallel_compiler))]
23 use rustc_data_structures::cold_path;
24 use std::mem;
25 use std::ptr;
26 use std::collections::hash_map::Entry;
27 use syntax_pos::Span;
28 use syntax::source_map::DUMMY_SP;
29
30 pub struct QueryCache<'tcx, D: QueryConfig<'tcx> + ?Sized> {
31     pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
32     pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
33     #[cfg(debug_assertions)]
34     pub(super) cache_hits: usize,
35 }
36
37 pub(super) struct QueryValue<T> {
38     pub(super) value: T,
39     pub(super) index: DepNodeIndex,
40 }
41
42 impl<T> QueryValue<T> {
43     pub(super) fn new(value: T,
44                       dep_node_index: DepNodeIndex)
45                       -> QueryValue<T> {
46         QueryValue {
47             value,
48             index: dep_node_index,
49         }
50     }
51 }
52
53 impl<'tcx, M: QueryConfig<'tcx>> Default for QueryCache<'tcx, M> {
54     fn default() -> QueryCache<'tcx, M> {
55         QueryCache {
56             results: FxHashMap::default(),
57             active: FxHashMap::default(),
58             #[cfg(debug_assertions)]
59             cache_hits: 0,
60         }
61     }
62 }
63
64 // If enabled, send a message to the profile-queries thread
65 macro_rules! profq_msg {
66     ($tcx:expr, $msg:expr) => {
67         if cfg!(debug_assertions) {
68             if $tcx.sess.profile_queries() {
69                 profq_msg($tcx.sess, $msg)
70             }
71         }
72     }
73 }
74
75 // If enabled, format a key using its debug string, which can be
76 // expensive to compute (in terms of time).
77 macro_rules! profq_query_msg {
78     ($query:expr, $tcx:expr, $key:expr) => {{
79         let msg = if cfg!(debug_assertions) {
80             if $tcx.sess.profile_queries_and_keys() {
81                 Some(format!("{:?}", $key))
82             } else { None }
83         } else { None };
84         QueryMsg {
85             query: $query,
86             msg,
87         }
88     }}
89 }
90
91 /// A type representing the responsibility to execute the job in the `job` field.
92 /// This will poison the relevant query if dropped.
93 pub(super) struct JobOwner<'a, 'tcx: 'a, Q: QueryDescription<'tcx> + 'a> {
94     cache: &'a Lock<QueryCache<'tcx, Q>>,
95     key: Q::Key,
96     job: Lrc<QueryJob<'tcx>>,
97 }
98
99 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
100     /// Either gets a JobOwner corresponding the query, allowing us to
101     /// start executing the query, or it returns with the result of the query.
102     /// If the query is executing elsewhere, this will wait for it.
103     /// If the query panicked, this will silently panic.
104     ///
105     /// This function is inlined because that results in a noticeable speedup
106     /// for some compile-time benchmarks.
107     #[inline(always)]
108     pub(super) fn try_get(
109         tcx: TyCtxt<'a, 'tcx, '_>,
110         span: Span,
111         key: &Q::Key,
112     ) -> TryGetJob<'a, 'tcx, Q> {
113         let cache = Q::query_cache(tcx);
114         loop {
115             let mut lock = cache.borrow_mut();
116             if let Some(value) = lock.results.get(key) {
117                 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
118                 tcx.sess.profiler(|p| p.record_query_hit(Q::NAME, Q::CATEGORY));
119                 let result = (value.value.clone(), value.index);
120                 #[cfg(debug_assertions)]
121                 {
122                     lock.cache_hits += 1;
123                 }
124                 return TryGetJob::JobCompleted(result);
125             }
126             let job = match lock.active.entry((*key).clone()) {
127                 Entry::Occupied(entry) => {
128                     match *entry.get() {
129                         QueryResult::Started(ref job) => {
130                             //For parallel queries, we'll block and wait until the query running
131                             //in another thread has completed. Record how long we wait in the
132                             //self-profiler
133                             #[cfg(parallel_compiler)]
134                             tcx.sess.profiler(|p| p.query_blocked_start(Q::NAME, Q::CATEGORY));
135
136                             job.clone()
137                         },
138                         QueryResult::Poisoned => FatalError.raise(),
139                     }
140                 }
141                 Entry::Vacant(entry) => {
142                     // No job entry for this query. Return a new one to be started later
143                     return tls::with_related_context(tcx, |icx| {
144                         // Create the `parent` variable before `info`. This allows LLVM
145                         // to elide the move of `info`
146                         let parent = icx.query.clone();
147                         let info = QueryInfo {
148                             span,
149                             query: Q::query(key.clone()),
150                         };
151                         let job = Lrc::new(QueryJob::new(info, parent));
152                         let owner = JobOwner {
153                             cache,
154                             job: job.clone(),
155                             key: (*key).clone(),
156                         };
157                         entry.insert(QueryResult::Started(job));
158                         TryGetJob::NotYetStarted(owner)
159                     })
160                 }
161             };
162             mem::drop(lock);
163
164             // If we are single-threaded we know that we have cycle error,
165             // so we just return the error
166             #[cfg(not(parallel_compiler))]
167             return TryGetJob::Cycle(cold_path(|| {
168                 Q::handle_cycle_error(tcx, job.find_cycle_in_stack(tcx, span))
169             }));
170
171             // With parallel queries we might just have to wait on some other
172             // thread
173             #[cfg(parallel_compiler)]
174             {
175                 let result = job.r#await(tcx, span);
176                 tcx.sess.profiler(|p| p.query_blocked_end(Q::NAME, Q::CATEGORY));
177
178                 if let Err(cycle) = result {
179                     return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
180                 }
181             }
182         }
183     }
184
185     /// Completes the query by updating the query cache with the `result`,
186     /// signals the waiter and forgets the JobOwner, so it won't poison the query
187     #[inline(always)]
188     pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
189         // We can move out of `self` here because we `mem::forget` it below
190         let key = unsafe { ptr::read(&self.key) };
191         let job = unsafe { ptr::read(&self.job) };
192         let cache = self.cache;
193
194         // Forget ourself so our destructor won't poison the query
195         mem::forget(self);
196
197         let value = QueryValue::new(result.clone(), dep_node_index);
198         {
199             let mut lock = cache.borrow_mut();
200             lock.active.remove(&key);
201             lock.results.insert(key, value);
202         }
203
204         job.signal_complete();
205     }
206 }
207
208 #[inline(always)]
209 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
210 where
211     F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R
212 {
213     let diagnostics = Lock::new(ThinVec::new());
214     let result = f(Some(&diagnostics));
215     (result, diagnostics.into_inner())
216 }
217
218 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
219     #[inline(never)]
220     #[cold]
221     fn drop(&mut self) {
222         // Poison the query so jobs waiting on it panic
223         self.cache.borrow_mut().active.insert(self.key.clone(), QueryResult::Poisoned);
224         // Also signal the completion of the job, so waiters
225         // will continue execution
226         self.job.signal_complete();
227     }
228 }
229
230 #[derive(Clone)]
231 pub struct CycleError<'tcx> {
232     /// The query and related span which uses the cycle
233     pub(super) usage: Option<(Span, Query<'tcx>)>,
234     pub(super) cycle: Vec<QueryInfo<'tcx>>,
235 }
236
237 /// The result of `try_get_lock`
238 pub(super) enum TryGetJob<'a, 'tcx: 'a, D: QueryDescription<'tcx> + 'a> {
239     /// The query is not yet started. Contains a guard to the cache eventually used to start it.
240     NotYetStarted(JobOwner<'a, 'tcx, D>),
241
242     /// The query was already completed.
243     /// Returns the result of the query and its dep node index
244     /// if it succeeded or a cycle error if it failed
245     JobCompleted((D::Value, DepNodeIndex)),
246
247     /// Trying to execute the query resulted in a cycle.
248     Cycle(D::Value),
249 }
250
251 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
252     /// Executes a job by changing the ImplicitCtxt to point to the
253     /// new query job while it executes. It returns the diagnostics
254     /// captured during execution and the actual result.
255     #[inline(always)]
256     pub(super) fn start_query<F, R>(
257         self,
258         job: Lrc<QueryJob<'gcx>>,
259         diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
260         compute: F)
261     -> R
262     where
263         F: for<'b, 'lcx> FnOnce(TyCtxt<'b, 'gcx, 'lcx>) -> R
264     {
265         // The TyCtxt stored in TLS has the same global interner lifetime
266         // as `self`, so we use `with_related_context` to relate the 'gcx lifetimes
267         // when accessing the ImplicitCtxt
268         tls::with_related_context(self, move |current_icx| {
269             // Update the ImplicitCtxt to point to our new query job
270             let new_icx = tls::ImplicitCtxt {
271                 tcx: self.global_tcx(),
272                 query: Some(job),
273                 diagnostics,
274                 layout_depth: current_icx.layout_depth,
275                 task_deps: current_icx.task_deps,
276             };
277
278             // Use the ImplicitCtxt while we execute the query
279             tls::enter_context(&new_icx, |_| {
280                 compute(self.global_tcx())
281             })
282         })
283     }
284
285     #[inline(never)]
286     #[cold]
287     pub(super) fn report_cycle(
288         self,
289         CycleError { usage, cycle: stack }: CycleError<'gcx>
290     ) -> DiagnosticBuilder<'a>
291     {
292         assert!(!stack.is_empty());
293
294         let fix_span = |span: Span, query: &Query<'gcx>| {
295             self.sess.source_map().def_span(query.default_span(self, span))
296         };
297
298         // Disable naming impls with types in this path, since that
299         // sometimes cycles itself, leading to extra cycle errors.
300         // (And cycle errors around impls tend to occur during the
301         // collect/coherence phases anyhow.)
302         item_path::with_forced_impl_filename_line(|| {
303             let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
304             let mut err = struct_span_err!(self.sess,
305                                            span,
306                                            E0391,
307                                            "cycle detected when {}",
308                                            stack[0].query.describe(self));
309
310             for i in 1..stack.len() {
311                 let query = &stack[i].query;
312                 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
313                 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
314             }
315
316             err.note(&format!("...which again requires {}, completing the cycle",
317                               stack[0].query.describe(self)));
318
319             if let Some((span, query)) = usage {
320                 err.span_note(fix_span(span, &query),
321                               &format!("cycle used when {}", query.describe(self)));
322             }
323
324             err
325         })
326     }
327
328     pub fn try_print_query_stack() {
329         eprintln!("query stack during panic:");
330
331         tls::with_context_opt(|icx| {
332             if let Some(icx) = icx {
333                 let mut current_query = icx.query.clone();
334                 let mut i = 0;
335
336                 while let Some(query) = current_query {
337                     let mut db = DiagnosticBuilder::new(icx.tcx.sess.diagnostic(),
338                         Level::FailureNote,
339                         &format!("#{} [{}] {}",
340                                  i,
341                                  query.info.query.name(),
342                                  query.info.query.describe(icx.tcx)));
343                     db.set_span(icx.tcx.sess.source_map().def_span(query.info.span));
344                     icx.tcx.sess.diagnostic().force_print_db(db);
345
346                     current_query = query.parent.clone();
347                     i += 1;
348                 }
349             }
350         });
351
352         eprintln!("end of query stack");
353     }
354
355     #[inline(never)]
356     pub(super) fn get_query<Q: QueryDescription<'gcx>>(
357         self,
358         span: Span,
359         key: Q::Key)
360     -> Q::Value {
361         debug!("ty::query::get_query<{}>(key={:?}, span={:?})",
362                Q::NAME,
363                key,
364                span);
365
366         profq_msg!(self,
367             ProfileQueriesMsg::QueryBegin(
368                 span.data(),
369                 profq_query_msg!(Q::NAME, self, key),
370             )
371         );
372
373         let job = match JobOwner::try_get(self, span, &key) {
374             TryGetJob::NotYetStarted(job) => job,
375             TryGetJob::Cycle(result) => return result,
376             TryGetJob::JobCompleted((v, index)) => {
377                 self.dep_graph.read_index(index);
378                 return v
379             }
380         };
381
382         // Fast path for when incr. comp. is off. `to_dep_node` is
383         // expensive for some DepKinds.
384         if !self.dep_graph.is_fully_enabled() {
385             let null_dep_node = DepNode::new_no_params(crate::dep_graph::DepKind::Null);
386             return self.force_query_with_job::<Q>(key, job, null_dep_node).0;
387         }
388
389         let dep_node = Q::to_dep_node(self, &key);
390
391         if dep_node.kind.is_anon() {
392             profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
393             self.sess.profiler(|p| p.start_query(Q::NAME, Q::CATEGORY));
394
395             let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
396                 self.start_query(job.job.clone(), diagnostics, |tcx| {
397                     tcx.dep_graph.with_anon_task(dep_node.kind, || {
398                         Q::compute(tcx.global_tcx(), key)
399                     })
400                 })
401             });
402
403             self.sess.profiler(|p| p.end_query(Q::NAME, Q::CATEGORY));
404             profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
405
406             self.dep_graph.read_index(dep_node_index);
407
408             if unlikely!(!diagnostics.is_empty()) {
409                 self.queries.on_disk_cache
410                     .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
411             }
412
413             job.complete(&result, dep_node_index);
414
415             return result;
416         }
417
418         if !dep_node.kind.is_input() {
419             // The diagnostics for this query will be
420             // promoted to the current session during
421             // try_mark_green(), so we can ignore them here.
422             let loaded = self.start_query(job.job.clone(), None, |tcx| {
423                 let marked = tcx.dep_graph.try_mark_green_and_read(tcx, &dep_node);
424                 marked.map(|(prev_dep_node_index, dep_node_index)| {
425                     (tcx.load_from_disk_and_cache_in_memory::<Q>(
426                         key.clone(),
427                         prev_dep_node_index,
428                         dep_node_index,
429                         &dep_node
430                     ), dep_node_index)
431                 })
432             });
433             if let Some((result, dep_node_index)) = loaded {
434                 job.complete(&result, dep_node_index);
435                 return result;
436             }
437         }
438
439         let (result, dep_node_index) = self.force_query_with_job::<Q>(key, job, dep_node);
440         self.dep_graph.read_index(dep_node_index);
441         result
442     }
443
444     fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'gcx>>(
445         self,
446         key: Q::Key,
447         prev_dep_node_index: SerializedDepNodeIndex,
448         dep_node_index: DepNodeIndex,
449         dep_node: &DepNode
450     ) -> Q::Value
451     {
452         // Note this function can be called concurrently from the same query
453         // We must ensure that this is handled correctly
454
455         debug_assert!(self.dep_graph.is_green(dep_node));
456
457         // First we try to load the result from the on-disk cache
458         let result = if Q::cache_on_disk(self.global_tcx(), key.clone()) &&
459                         self.sess.opts.debugging_opts.incremental_queries {
460             self.sess.profiler(|p| p.incremental_load_result_start(Q::NAME));
461             let result = Q::try_load_from_disk(self.global_tcx(), prev_dep_node_index);
462             self.sess.profiler(|p| p.incremental_load_result_end(Q::NAME));
463
464             // We always expect to find a cached result for things that
465             // can be forced from DepNode.
466             debug_assert!(!dep_node.kind.can_reconstruct_query_key() ||
467                           result.is_some(),
468                           "Missing on-disk cache entry for {:?}",
469                           dep_node);
470             result
471         } else {
472             // Some things are never cached on disk.
473             None
474         };
475
476         let result = if let Some(result) = result {
477             profq_msg!(self, ProfileQueriesMsg::CacheHit);
478             self.sess.profiler(|p| p.record_query_hit(Q::NAME, Q::CATEGORY));
479
480             result
481         } else {
482             // We could not load a result from the on-disk cache, so
483             // recompute.
484
485             self.sess.profiler(|p| p.start_query(Q::NAME, Q::CATEGORY));
486
487             // The dep-graph for this computation is already in
488             // place
489             let result = self.dep_graph.with_ignore(|| {
490                 Q::compute(self, key)
491             });
492
493             self.sess.profiler(|p| p.end_query(Q::NAME, Q::CATEGORY));
494             result
495         };
496
497         // If -Zincremental-verify-ich is specified, re-hash results from
498         // the cache and make sure that they have the expected fingerprint.
499         if unlikely!(self.sess.opts.debugging_opts.incremental_verify_ich) {
500             self.incremental_verify_ich::<Q>(&result, dep_node, dep_node_index);
501         }
502
503         if unlikely!(self.sess.opts.debugging_opts.query_dep_graph) {
504             self.dep_graph.mark_loaded_from_cache(dep_node_index, true);
505         }
506
507         result
508     }
509
510     #[inline(never)]
511     #[cold]
512     fn incremental_verify_ich<Q: QueryDescription<'gcx>>(
513         self,
514         result: &Q::Value,
515         dep_node: &DepNode,
516         dep_node_index: DepNodeIndex,
517     ) {
518         use crate::ich::Fingerprint;
519
520         assert!(Some(self.dep_graph.fingerprint_of(dep_node_index)) ==
521                 self.dep_graph.prev_fingerprint_of(dep_node),
522                 "Fingerprint for green query instance not loaded \
523                     from cache: {:?}", dep_node);
524
525         debug!("BEGIN verify_ich({:?})", dep_node);
526         let mut hcx = self.create_stable_hashing_context();
527
528         let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
529         debug!("END verify_ich({:?})", dep_node);
530
531         let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
532
533         assert!(new_hash == old_hash, "Found unstable fingerprints \
534             for {:?}", dep_node);
535     }
536
537     #[inline(always)]
538     fn force_query_with_job<Q: QueryDescription<'gcx>>(
539         self,
540         key: Q::Key,
541         job: JobOwner<'_, 'gcx, Q>,
542         dep_node: DepNode)
543     -> (Q::Value, DepNodeIndex) {
544         // If the following assertion triggers, it can have two reasons:
545         // 1. Something is wrong with DepNode creation, either here or
546         //    in DepGraph::try_mark_green()
547         // 2. Two distinct query keys get mapped to the same DepNode
548         //    (see for example #48923)
549         assert!(!self.dep_graph.dep_node_exists(&dep_node),
550                 "Forcing query with already existing DepNode.\n\
551                  - query-key: {:?}\n\
552                  - dep-node: {:?}",
553                 key, dep_node);
554
555         profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
556         self.sess.profiler(|p| p.start_query(Q::NAME, Q::CATEGORY));
557
558         let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
559             self.start_query(job.job.clone(), diagnostics, |tcx| {
560                 if dep_node.kind.is_eval_always() {
561                     tcx.dep_graph.with_eval_always_task(dep_node,
562                                                         tcx,
563                                                         key,
564                                                         Q::compute,
565                                                         Q::hash_result)
566                 } else {
567                     tcx.dep_graph.with_task(dep_node,
568                                             tcx,
569                                             key,
570                                             Q::compute,
571                                             Q::hash_result)
572                 }
573             })
574         });
575
576         self.sess.profiler(|p| p.end_query(Q::NAME, Q::CATEGORY));
577         profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
578
579         if unlikely!(self.sess.opts.debugging_opts.query_dep_graph) {
580             self.dep_graph.mark_loaded_from_cache(dep_node_index, false);
581         }
582
583         if dep_node.kind != crate::dep_graph::DepKind::Null {
584             if unlikely!(!diagnostics.is_empty()) {
585                 self.queries.on_disk_cache
586                     .store_diagnostics(dep_node_index, diagnostics);
587             }
588         }
589
590         job.complete(&result, dep_node_index);
591
592         (result, dep_node_index)
593     }
594
595     /// Ensure that either this query has all green inputs or been executed.
596     /// Executing query::ensure(D) is considered a read of the dep-node D.
597     ///
598     /// This function is particularly useful when executing passes for their
599     /// side-effects -- e.g., in order to report errors for erroneous programs.
600     ///
601     /// Note: The optimization is only available during incr. comp.
602     pub(super) fn ensure_query<Q: QueryDescription<'gcx>>(self, key: Q::Key) -> () {
603         let dep_node = Q::to_dep_node(self, &key);
604
605         // Ensuring an "input" or anonymous query makes no sense
606         assert!(!dep_node.kind.is_anon());
607         assert!(!dep_node.kind.is_input());
608         if self.dep_graph.try_mark_green_and_read(self, &dep_node).is_none() {
609             // A None return from `try_mark_green_and_read` means that this is either
610             // a new dep node or that the dep node has already been marked red.
611             // Either way, we can't call `dep_graph.read()` as we don't have the
612             // DepNodeIndex. We must invoke the query itself. The performance cost
613             // this introduces should be negligible as we'll immediately hit the
614             // in-memory cache, or another query down the line will.
615
616             let _ = self.get_query::<Q>(DUMMY_SP, key);
617         } else {
618             profq_msg!(self, ProfileQueriesMsg::CacheHit);
619             self.sess.profiler(|p| p.record_query_hit(Q::NAME, Q::CATEGORY));
620         }
621     }
622
623     #[allow(dead_code)]
624     fn force_query<Q: QueryDescription<'gcx>>(
625         self,
626         key: Q::Key,
627         span: Span,
628         dep_node: DepNode
629     ) {
630         profq_msg!(
631             self,
632             ProfileQueriesMsg::QueryBegin(span.data(), profq_query_msg!(Q::NAME, self, key))
633         );
634
635         // We may be concurrently trying both execute and force a query
636         // Ensure that only one of them runs the query
637         let job = match JobOwner::try_get(self, span, &key) {
638             TryGetJob::NotYetStarted(job) => job,
639             TryGetJob::Cycle(_) |
640             TryGetJob::JobCompleted(_) => {
641                 return
642             }
643         };
644         self.force_query_with_job::<Q>(key, job, dep_node);
645     }
646 }
647
648 macro_rules! handle_cycle_error {
649     ([][$tcx: expr, $error:expr]) => {{
650         $tcx.report_cycle($error).emit();
651         Value::from_cycle_error($tcx.global_tcx())
652     }};
653     ([fatal_cycle$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
654         $tcx.report_cycle($error).emit();
655         $tcx.sess.abort_if_errors();
656         unreachable!()
657     }};
658     ([cycle_delay_bug$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
659         $tcx.report_cycle($error).delay_as_bug();
660         Value::from_cycle_error($tcx.global_tcx())
661     }};
662     ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
663         handle_cycle_error!([$($modifiers),*][$($args)*])
664     };
665 }
666
667 macro_rules! hash_result {
668     ([][$hcx:expr, $result:expr]) => {{
669         dep_graph::hash_result($hcx, &$result)
670     }};
671     ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{
672         None
673     }};
674     ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
675         hash_result!([$($modifiers),*][$($args)*])
676     };
677 }
678
679 macro_rules! define_queries {
680     (<$tcx:tt> $($category:tt {
681         $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
682     },)*) => {
683         define_queries_inner! { <$tcx>
684             $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($K) -> $V,)*)*
685         }
686     }
687 }
688
689 macro_rules! define_queries_inner {
690     (<$tcx:tt>
691      $($(#[$attr:meta])* category<$category:tt>
692         [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
693
694         use std::mem;
695         #[cfg(parallel_compiler)]
696         use ty::query::job::QueryResult;
697         use rustc_data_structures::sync::Lock;
698         use crate::{
699             rustc_data_structures::stable_hasher::HashStable,
700             rustc_data_structures::stable_hasher::StableHasherResult,
701             rustc_data_structures::stable_hasher::StableHasher,
702             ich::StableHashingContext
703         };
704         use crate::util::profiling::ProfileCategory;
705
706         define_queries_struct! {
707             tcx: $tcx,
708             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
709         }
710
711         impl<$tcx> Queries<$tcx> {
712             pub fn new(
713                 providers: IndexVec<CrateNum, Providers<$tcx>>,
714                 fallback_extern_providers: Providers<$tcx>,
715                 on_disk_cache: OnDiskCache<'tcx>,
716             ) -> Self {
717                 Queries {
718                     providers,
719                     fallback_extern_providers: Box::new(fallback_extern_providers),
720                     on_disk_cache,
721                     $($name: Default::default()),*
722                 }
723             }
724
725             pub fn record_computed_queries(&self, sess: &Session) {
726                 sess.profiler(|p| {
727                     $(
728                         p.record_computed_queries(
729                             <queries::$name<'_> as QueryConfig<'_>>::NAME,
730                             <queries::$name<'_> as QueryConfig<'_>>::CATEGORY,
731                             self.$name.lock().results.len()
732                         );
733                     )*
734                 });
735             }
736
737             #[cfg(parallel_compiler)]
738             pub fn collect_active_jobs(&self) -> Vec<Lrc<QueryJob<$tcx>>> {
739                 let mut jobs = Vec::new();
740
741                 // We use try_lock here since we are only called from the
742                 // deadlock handler, and this shouldn't be locked
743                 $(
744                     jobs.extend(
745                         self.$name.try_lock().unwrap().active.values().filter_map(|v|
746                             if let QueryResult::Started(ref job) = *v {
747                                 Some(job.clone())
748                             } else {
749                                 None
750                             }
751                         )
752                     );
753                 )*
754
755                 jobs
756             }
757
758             pub fn print_stats(&self) {
759                 let mut queries = Vec::new();
760
761                 #[derive(Clone)]
762                 struct QueryStats {
763                     name: &'static str,
764                     cache_hits: usize,
765                     key_size: usize,
766                     key_type: &'static str,
767                     value_size: usize,
768                     value_type: &'static str,
769                     entry_count: usize,
770                 }
771
772                 fn stats<'tcx, Q: QueryConfig<'tcx>>(
773                     name: &'static str,
774                     map: &QueryCache<'tcx, Q>
775                 ) -> QueryStats {
776                     QueryStats {
777                         name,
778                         #[cfg(debug_assertions)]
779                         cache_hits: map.cache_hits,
780                         #[cfg(not(debug_assertions))]
781                         cache_hits: 0,
782                         key_size: mem::size_of::<Q::Key>(),
783                         key_type: unsafe { type_name::<Q::Key>() },
784                         value_size: mem::size_of::<Q::Value>(),
785                         value_type: unsafe { type_name::<Q::Value>() },
786                         entry_count: map.results.len(),
787                     }
788                 }
789
790                 $(
791                     queries.push(stats::<queries::$name<'_>>(
792                         stringify!($name),
793                         &*self.$name.lock()
794                     ));
795                 )*
796
797                 if cfg!(debug_assertions) {
798                     let hits: usize = queries.iter().map(|s| s.cache_hits).sum();
799                     let results: usize = queries.iter().map(|s| s.entry_count).sum();
800                     println!("\nQuery cache hit rate: {}", hits as f64 / (hits + results) as f64);
801                 }
802
803                 let mut query_key_sizes = queries.clone();
804                 query_key_sizes.sort_by_key(|q| q.key_size);
805                 println!("\nLarge query keys:");
806                 for q in query_key_sizes.iter().rev()
807                                         .filter(|q| q.key_size > 8) {
808                     println!(
809                         "   {} - {} x {} - {}",
810                         q.name,
811                         q.key_size,
812                         q.entry_count,
813                         q.key_type
814                     );
815                 }
816
817                 let mut query_value_sizes = queries.clone();
818                 query_value_sizes.sort_by_key(|q| q.value_size);
819                 println!("\nLarge query values:");
820                 for q in query_value_sizes.iter().rev()
821                                           .filter(|q| q.value_size > 8) {
822                     println!(
823                         "   {} - {} x {} - {}",
824                         q.name,
825                         q.value_size,
826                         q.entry_count,
827                         q.value_type
828                     );
829                 }
830
831                 if cfg!(debug_assertions) {
832                     let mut query_cache_hits = queries.clone();
833                     query_cache_hits.sort_by_key(|q| q.cache_hits);
834                     println!("\nQuery cache hits:");
835                     for q in query_cache_hits.iter().rev() {
836                         println!(
837                             "   {} - {} ({}%)",
838                             q.name,
839                             q.cache_hits,
840                             q.cache_hits as f64 / (q.cache_hits + q.entry_count) as f64
841                         );
842                     }
843                 }
844
845                 let mut query_value_count = queries.clone();
846                 query_value_count.sort_by_key(|q| q.entry_count);
847                 println!("\nQuery value count:");
848                 for q in query_value_count.iter().rev() {
849                     println!("   {} - {}", q.name, q.entry_count);
850                 }
851             }
852         }
853
854         #[allow(nonstandard_style)]
855         #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
856         pub enum Query<$tcx> {
857             $($(#[$attr])* $name($K)),*
858         }
859
860         impl<$tcx> Query<$tcx> {
861             pub fn name(&self) -> &'static str {
862                 match *self {
863                     $(Query::$name(_) => stringify!($name),)*
864                 }
865             }
866
867             pub fn describe(&self, tcx: TyCtxt<'_, '_, '_>) -> Cow<'static, str> {
868                 let (r, name) = match *self {
869                     $(Query::$name(key) => {
870                         (queries::$name::describe(tcx, key), stringify!($name))
871                     })*
872                 };
873                 if tcx.sess.verbose() {
874                     format!("{} [{}]", r, name).into()
875                 } else {
876                     r
877                 }
878             }
879
880             // FIXME(eddyb) Get more valid Span's on queries.
881             pub fn default_span(&self, tcx: TyCtxt<'_, $tcx, '_>, span: Span) -> Span {
882                 if !span.is_dummy() {
883                     return span;
884                 }
885                 // The def_span query is used to calculate default_span,
886                 // so exit to avoid infinite recursion
887                 if let Query::def_span(..) = *self {
888                     return span
889                 }
890                 match *self {
891                     $(Query::$name(key) => key.default_span(tcx),)*
892                 }
893             }
894         }
895
896         impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
897             fn hash_stable<W: StableHasherResult>(&self,
898                                                 hcx: &mut StableHashingContext<'a>,
899                                                 hasher: &mut StableHasher<W>) {
900                 mem::discriminant(self).hash_stable(hcx, hasher);
901                 match *self {
902                     $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
903                 }
904             }
905         }
906
907         pub mod queries {
908             use std::marker::PhantomData;
909
910             $(#[allow(nonstandard_style)]
911             pub struct $name<$tcx> {
912                 data: PhantomData<&$tcx ()>
913             })*
914         }
915
916         // This module and the functions in it exist only to provide a
917         // predictable symbol name prefix for query providers. This is helpful
918         // for analyzing queries in profilers.
919         pub(super) mod __query_compute {
920             $(#[inline(never)]
921             pub fn $name<F: FnOnce() -> R, R>(f: F) -> R {
922                 f()
923             })*
924         }
925
926         $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
927             type Key = $K;
928             type Value = $V;
929
930             const NAME: &'static str = stringify!($name);
931             const CATEGORY: ProfileCategory = $category;
932         }
933
934         impl<$tcx> QueryAccessors<$tcx> for queries::$name<$tcx> {
935             #[inline(always)]
936             fn query(key: Self::Key) -> Query<'tcx> {
937                 Query::$name(key)
938             }
939
940             #[inline(always)]
941             fn query_cache<'a>(tcx: TyCtxt<'a, $tcx, '_>) -> &'a Lock<QueryCache<$tcx, Self>> {
942                 &tcx.queries.$name
943             }
944
945             #[allow(unused)]
946             #[inline(always)]
947             fn to_dep_node(tcx: TyCtxt<'_, $tcx, '_>, key: &Self::Key) -> DepNode {
948                 use crate::dep_graph::DepConstructor::*;
949
950                 DepNode::new(tcx, $node(*key))
951             }
952
953             #[inline]
954             fn compute(tcx: TyCtxt<'_, 'tcx, '_>, key: Self::Key) -> Self::Value {
955                 __query_compute::$name(move || {
956                     let provider = tcx.queries.providers.get(key.query_crate())
957                         // HACK(eddyb) it's possible crates may be loaded after
958                         // the query engine is created, and because crate loading
959                         // is not yet integrated with the query engine, such crates
960                         // would be missing appropriate entries in `providers`.
961                         .unwrap_or(&tcx.queries.fallback_extern_providers)
962                         .$name;
963                     provider(tcx.global_tcx(), key)
964                 })
965             }
966
967             fn hash_result(
968                 _hcx: &mut StableHashingContext<'_>,
969                 _result: &Self::Value
970             ) -> Option<Fingerprint> {
971                 hash_result!([$($modifiers)*][_hcx, _result])
972             }
973
974             fn handle_cycle_error(
975                 tcx: TyCtxt<'_, 'tcx, '_>,
976                 error: CycleError<'tcx>
977             ) -> Self::Value {
978                 handle_cycle_error!([$($modifiers)*][tcx, error])
979             }
980         })*
981
982         #[derive(Copy, Clone)]
983         pub struct TyCtxtEnsure<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
984             pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
985         }
986
987         impl<'a, $tcx, 'lcx> TyCtxtEnsure<'a, $tcx, 'lcx> {
988             $($(#[$attr])*
989             #[inline(always)]
990             pub fn $name(self, key: $K) {
991                 self.tcx.ensure_query::<queries::$name<'_>>(key)
992             })*
993         }
994
995         #[derive(Copy, Clone)]
996         pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
997             pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
998             pub span: Span,
999         }
1000
1001         impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
1002             type Target = TyCtxt<'a, 'gcx, 'tcx>;
1003             #[inline(always)]
1004             fn deref(&self) -> &Self::Target {
1005                 &self.tcx
1006             }
1007         }
1008
1009         impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
1010             /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
1011             /// are executed instead of just returing their results.
1012             #[inline(always)]
1013             pub fn ensure(self) -> TyCtxtEnsure<'a, $tcx, 'lcx> {
1014                 TyCtxtEnsure {
1015                     tcx: self,
1016                 }
1017             }
1018
1019             /// Returns a transparent wrapper for `TyCtxt` which uses
1020             /// `span` as the location of queries performed through it.
1021             #[inline(always)]
1022             pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
1023                 TyCtxtAt {
1024                     tcx: self,
1025                     span
1026                 }
1027             }
1028
1029             $($(#[$attr])*
1030             #[inline(always)]
1031             pub fn $name(self, key: $K) -> $V {
1032                 self.at(DUMMY_SP).$name(key)
1033             })*
1034         }
1035
1036         impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
1037             $($(#[$attr])*
1038             #[inline(always)]
1039             pub fn $name(self, key: $K) -> $V {
1040                 self.tcx.get_query::<queries::$name<'_>>(self.span, key)
1041             })*
1042         }
1043
1044         define_provider_struct! {
1045             tcx: $tcx,
1046             input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
1047         }
1048
1049         impl<$tcx> Copy for Providers<$tcx> {}
1050         impl<$tcx> Clone for Providers<$tcx> {
1051             fn clone(&self) -> Self { *self }
1052         }
1053     }
1054 }
1055
1056 macro_rules! define_queries_struct {
1057     (tcx: $tcx:tt,
1058      input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
1059         pub struct Queries<$tcx> {
1060             /// This provides access to the incrimental comilation on-disk cache for query results.
1061             /// Do not access this directly. It is only meant to be used by
1062             /// `DepGraph::try_mark_green()` and the query infrastructure.
1063             pub(crate) on_disk_cache: OnDiskCache<'tcx>,
1064
1065             providers: IndexVec<CrateNum, Providers<$tcx>>,
1066             fallback_extern_providers: Box<Providers<$tcx>>,
1067
1068             $($(#[$attr])*  $name: Lock<QueryCache<$tcx, queries::$name<$tcx>>>,)*
1069         }
1070     };
1071 }
1072
1073 macro_rules! define_provider_struct {
1074     (tcx: $tcx:tt,
1075      input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
1076         pub struct Providers<$tcx> {
1077             $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
1078         }
1079
1080         impl<$tcx> Default for Providers<$tcx> {
1081             fn default() -> Self {
1082                 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
1083                     bug!("tcx.{}({:?}) unsupported by its crate",
1084                          stringify!($name), key);
1085                 })*
1086                 Providers { $($name),* }
1087             }
1088         }
1089     };
1090 }
1091
1092
1093 /// The red/green evaluation system will try to mark a specific DepNode in the
1094 /// dependency graph as green by recursively trying to mark the dependencies of
1095 /// that DepNode as green. While doing so, it will sometimes encounter a DepNode
1096 /// where we don't know if it is red or green and we therefore actually have
1097 /// to recompute its value in order to find out. Since the only piece of
1098 /// information that we have at that point is the DepNode we are trying to
1099 /// re-evaluate, we need some way to re-run a query from just that. This is what
1100 /// `force_from_dep_node()` implements.
1101 ///
1102 /// In the general case, a DepNode consists of a DepKind and an opaque
1103 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
1104 /// is usually constructed by computing a stable hash of the query-key that the
1105 /// DepNode corresponds to. Consequently, it is not in general possible to go
1106 /// back from hash to query-key (since hash functions are not reversible). For
1107 /// this reason `force_from_dep_node()` is expected to fail from time to time
1108 /// because we just cannot find out, from the DepNode alone, what the
1109 /// corresponding query-key is and therefore cannot re-run the query.
1110 ///
1111 /// The system deals with this case letting `try_mark_green` fail which forces
1112 /// the root query to be re-evaluated.
1113 ///
1114 /// Now, if force_from_dep_node() would always fail, it would be pretty useless.
1115 /// Fortunately, we can use some contextual information that will allow us to
1116 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
1117 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
1118 /// valid `DefPathHash`. Since we also always build a huge table that maps every
1119 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
1120 /// everything we need to re-run the query.
1121 ///
1122 /// Take the `mir_validated` query as an example. Like many other queries, it
1123 /// just has a single parameter: the `DefId` of the item it will compute the
1124 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
1125 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
1126 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
1127 /// `DefId` in `tcx.def_path_hash_to_def_id`.
1128 ///
1129 /// When you implement a new query, it will likely have a corresponding new
1130 /// `DepKind`, and you'll have to support it here in `force_from_dep_node()`. As
1131 /// a rule of thumb, if your query takes a `DefId` or `DefIndex` as sole parameter,
1132 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
1133 /// add it to the "We don't have enough information to reconstruct..." group in
1134 /// the match below.
1135 pub fn force_from_dep_node<'a, 'gcx, 'lcx>(tcx: TyCtxt<'a, 'gcx, 'lcx>,
1136                                            dep_node: &DepNode)
1137                                            -> bool {
1138     use crate::hir::def_id::LOCAL_CRATE;
1139
1140     // We must avoid ever having to call force_from_dep_node() for a
1141     // DepNode::CodegenUnit:
1142     // Since we cannot reconstruct the query key of a DepNode::CodegenUnit, we
1143     // would always end up having to evaluate the first caller of the
1144     // `codegen_unit` query that *is* reconstructible. This might very well be
1145     // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
1146     // to re-trigger calling the `codegen_unit` query with the right key. At
1147     // that point we would already have re-done all the work we are trying to
1148     // avoid doing in the first place.
1149     // The solution is simple: Just explicitly call the `codegen_unit` query for
1150     // each CGU, right after partitioning. This way `try_mark_green` will always
1151     // hit the cache instead of having to go through `force_from_dep_node`.
1152     // This assertion makes sure, we actually keep applying the solution above.
1153     debug_assert!(dep_node.kind != DepKind::CodegenUnit,
1154                   "calling force_from_dep_node() on DepKind::CodegenUnit");
1155
1156     if !dep_node.kind.can_reconstruct_query_key() {
1157         return false
1158     }
1159
1160     macro_rules! def_id {
1161         () => {
1162             if let Some(def_id) = dep_node.extract_def_id(tcx) {
1163                 def_id
1164             } else {
1165                 // return from the whole function
1166                 return false
1167             }
1168         }
1169     };
1170
1171     macro_rules! krate {
1172         () => { (def_id!()).krate }
1173     };
1174
1175     macro_rules! force {
1176         ($query:ident, $key:expr) => {
1177             {
1178                 tcx.force_query::<crate::ty::query::queries::$query<'_>>($key, DUMMY_SP, *dep_node);
1179             }
1180         }
1181     };
1182
1183     // FIXME(#45015): We should try move this boilerplate code into a macro
1184     //                somehow.
1185     match dep_node.kind {
1186         // These are inputs that are expected to be pre-allocated and that
1187         // should therefore always be red or green already
1188         DepKind::AllLocalTraitImpls |
1189         DepKind::Krate |
1190         DepKind::CrateMetadata |
1191         DepKind::HirBody |
1192         DepKind::Hir |
1193
1194         // This are anonymous nodes
1195         DepKind::TraitSelect |
1196
1197         // We don't have enough information to reconstruct the query key of
1198         // these
1199         DepKind::IsCopy |
1200         DepKind::IsSized |
1201         DepKind::IsFreeze |
1202         DepKind::NeedsDrop |
1203         DepKind::Layout |
1204         DepKind::ConstEval |
1205         DepKind::ConstEvalRaw |
1206         DepKind::InstanceSymbolName |
1207         DepKind::MirShim |
1208         DepKind::BorrowCheckKrate |
1209         DepKind::Specializes |
1210         DepKind::ImplementationsOfTrait |
1211         DepKind::TypeParamPredicates |
1212         DepKind::CodegenUnit |
1213         DepKind::CompileCodegenUnit |
1214         DepKind::FulfillObligation |
1215         DepKind::VtableMethods |
1216         DepKind::EraseRegionsTy |
1217         DepKind::NormalizeProjectionTy |
1218         DepKind::NormalizeTyAfterErasingRegions |
1219         DepKind::ImpliedOutlivesBounds |
1220         DepKind::DropckOutlives |
1221         DepKind::EvaluateObligation |
1222         DepKind::EvaluateGoal |
1223         DepKind::TypeOpAscribeUserType |
1224         DepKind::TypeOpEq |
1225         DepKind::TypeOpSubtype |
1226         DepKind::TypeOpProvePredicate |
1227         DepKind::TypeOpNormalizeTy |
1228         DepKind::TypeOpNormalizePredicate |
1229         DepKind::TypeOpNormalizePolyFnSig |
1230         DepKind::TypeOpNormalizeFnSig |
1231         DepKind::SubstituteNormalizeAndTestPredicates |
1232         DepKind::MethodAutoderefSteps |
1233         DepKind::InstanceDefSizeEstimate |
1234         DepKind::ProgramClausesForEnv |
1235
1236         // This one should never occur in this context
1237         DepKind::Null => {
1238             bug!("force_from_dep_node() - Encountered {:?}", dep_node)
1239         }
1240
1241         // These are not queries
1242         DepKind::CoherenceCheckTrait |
1243         DepKind::ItemVarianceConstraints => {
1244             return false
1245         }
1246
1247         DepKind::RegionScopeTree => { force!(region_scope_tree, def_id!()); }
1248
1249         DepKind::Coherence => { force!(crate_inherent_impls, LOCAL_CRATE); }
1250         DepKind::CoherenceInherentImplOverlapCheck => {
1251             force!(crate_inherent_impls_overlap_check, LOCAL_CRATE)
1252         },
1253         DepKind::PrivacyAccessLevels => { force!(privacy_access_levels, LOCAL_CRATE); }
1254         DepKind::MirBuilt => { force!(mir_built, def_id!()); }
1255         DepKind::MirConstQualif => { force!(mir_const_qualif, def_id!()); }
1256         DepKind::MirConst => { force!(mir_const, def_id!()); }
1257         DepKind::MirValidated => { force!(mir_validated, def_id!()); }
1258         DepKind::MirOptimized => { force!(optimized_mir, def_id!()); }
1259
1260         DepKind::BorrowCheck => { force!(borrowck, def_id!()); }
1261         DepKind::MirBorrowCheck => { force!(mir_borrowck, def_id!()); }
1262         DepKind::UnsafetyCheckResult => { force!(unsafety_check_result, def_id!()); }
1263         DepKind::UnsafeDeriveOnReprPacked => { force!(unsafe_derive_on_repr_packed, def_id!()); }
1264         DepKind::CheckModAttrs => { force!(check_mod_attrs, def_id!()); }
1265         DepKind::CheckModLoops => { force!(check_mod_loops, def_id!()); }
1266         DepKind::CheckModUnstableApiUsage => { force!(check_mod_unstable_api_usage, def_id!()); }
1267         DepKind::CheckModItemTypes => { force!(check_mod_item_types, def_id!()); }
1268         DepKind::CheckModPrivacy => { force!(check_mod_privacy, def_id!()); }
1269         DepKind::CheckModIntrinsics => { force!(check_mod_intrinsics, def_id!()); }
1270         DepKind::CheckModLiveness => { force!(check_mod_liveness, def_id!()); }
1271         DepKind::CheckModImplWf => { force!(check_mod_impl_wf, def_id!()); }
1272         DepKind::CollectModItemTypes => { force!(collect_mod_item_types, def_id!()); }
1273         DepKind::Reachability => { force!(reachable_set, LOCAL_CRATE); }
1274         DepKind::MirKeys => { force!(mir_keys, LOCAL_CRATE); }
1275         DepKind::CrateVariances => { force!(crate_variances, LOCAL_CRATE); }
1276         DepKind::AssociatedItems => { force!(associated_item, def_id!()); }
1277         DepKind::TypeOfItem => { force!(type_of, def_id!()); }
1278         DepKind::GenericsOfItem => { force!(generics_of, def_id!()); }
1279         DepKind::PredicatesOfItem => { force!(predicates_of, def_id!()); }
1280         DepKind::PredicatesDefinedOnItem => { force!(predicates_defined_on, def_id!()); }
1281         DepKind::ExplicitPredicatesOfItem => { force!(explicit_predicates_of, def_id!()); }
1282         DepKind::InferredOutlivesOf => { force!(inferred_outlives_of, def_id!()); }
1283         DepKind::InferredOutlivesCrate => { force!(inferred_outlives_crate, LOCAL_CRATE); }
1284         DepKind::SuperPredicatesOfItem => { force!(super_predicates_of, def_id!()); }
1285         DepKind::TraitDefOfItem => { force!(trait_def, def_id!()); }
1286         DepKind::AdtDefOfItem => { force!(adt_def, def_id!()); }
1287         DepKind::ImplTraitRef => { force!(impl_trait_ref, def_id!()); }
1288         DepKind::ImplPolarity => { force!(impl_polarity, def_id!()); }
1289         DepKind::Issue33140SelfTy => { force!(issue33140_self_ty, def_id!()); }
1290         DepKind::FnSignature => { force!(fn_sig, def_id!()); }
1291         DepKind::CoerceUnsizedInfo => { force!(coerce_unsized_info, def_id!()); }
1292         DepKind::ItemVariances => { force!(variances_of, def_id!()); }
1293         DepKind::IsConstFn => { force!(is_const_fn_raw, def_id!()); }
1294         DepKind::IsPromotableConstFn => { force!(is_promotable_const_fn, def_id!()); }
1295         DepKind::IsForeignItem => { force!(is_foreign_item, def_id!()); }
1296         DepKind::SizedConstraint => { force!(adt_sized_constraint, def_id!()); }
1297         DepKind::DtorckConstraint => { force!(adt_dtorck_constraint, def_id!()); }
1298         DepKind::AdtDestructor => { force!(adt_destructor, def_id!()); }
1299         DepKind::AssociatedItemDefIds => { force!(associated_item_def_ids, def_id!()); }
1300         DepKind::InherentImpls => { force!(inherent_impls, def_id!()); }
1301         DepKind::TypeckBodiesKrate => { force!(typeck_item_bodies, LOCAL_CRATE); }
1302         DepKind::TypeckTables => { force!(typeck_tables_of, def_id!()); }
1303         DepKind::UsedTraitImports => { force!(used_trait_imports, def_id!()); }
1304         DepKind::HasTypeckTables => { force!(has_typeck_tables, def_id!()); }
1305         DepKind::SymbolName => { force!(def_symbol_name, def_id!()); }
1306         DepKind::SpecializationGraph => { force!(specialization_graph_of, def_id!()); }
1307         DepKind::ObjectSafety => { force!(is_object_safe, def_id!()); }
1308         DepKind::TraitImpls => { force!(trait_impls_of, def_id!()); }
1309         DepKind::CheckMatch => { force!(check_match, def_id!()); }
1310
1311         DepKind::ParamEnv => { force!(param_env, def_id!()); }
1312         DepKind::Environment => { force!(environment, def_id!()); }
1313         DepKind::DescribeDef => { force!(describe_def, def_id!()); }
1314         DepKind::DefSpan => { force!(def_span, def_id!()); }
1315         DepKind::LookupStability => { force!(lookup_stability, def_id!()); }
1316         DepKind::LookupDeprecationEntry => {
1317             force!(lookup_deprecation_entry, def_id!());
1318         }
1319         DepKind::ConstIsRvaluePromotableToStatic => {
1320             force!(const_is_rvalue_promotable_to_static, def_id!());
1321         }
1322         DepKind::RvaluePromotableMap => { force!(rvalue_promotable_map, def_id!()); }
1323         DepKind::ImplParent => { force!(impl_parent, def_id!()); }
1324         DepKind::TraitOfItem => { force!(trait_of_item, def_id!()); }
1325         DepKind::IsReachableNonGeneric => { force!(is_reachable_non_generic, def_id!()); }
1326         DepKind::IsUnreachableLocalDefinition => {
1327             force!(is_unreachable_local_definition, def_id!());
1328         }
1329         DepKind::IsMirAvailable => { force!(is_mir_available, def_id!()); }
1330         DepKind::ItemAttrs => { force!(item_attrs, def_id!()); }
1331         DepKind::CodegenFnAttrs => { force!(codegen_fn_attrs, def_id!()); }
1332         DepKind::FnArgNames => { force!(fn_arg_names, def_id!()); }
1333         DepKind::RenderedConst => { force!(rendered_const, def_id!()); }
1334         DepKind::DylibDepFormats => { force!(dylib_dependency_formats, krate!()); }
1335         DepKind::IsPanicRuntime => { force!(is_panic_runtime, krate!()); }
1336         DepKind::IsCompilerBuiltins => { force!(is_compiler_builtins, krate!()); }
1337         DepKind::HasGlobalAllocator => { force!(has_global_allocator, krate!()); }
1338         DepKind::HasPanicHandler => { force!(has_panic_handler, krate!()); }
1339         DepKind::ExternCrate => { force!(extern_crate, def_id!()); }
1340         DepKind::LintLevels => { force!(lint_levels, LOCAL_CRATE); }
1341         DepKind::InScopeTraits => { force!(in_scope_traits_map, def_id!().index); }
1342         DepKind::ModuleExports => { force!(module_exports, def_id!()); }
1343         DepKind::IsSanitizerRuntime => { force!(is_sanitizer_runtime, krate!()); }
1344         DepKind::IsProfilerRuntime => { force!(is_profiler_runtime, krate!()); }
1345         DepKind::GetPanicStrategy => { force!(panic_strategy, krate!()); }
1346         DepKind::IsNoBuiltins => { force!(is_no_builtins, krate!()); }
1347         DepKind::ImplDefaultness => { force!(impl_defaultness, def_id!()); }
1348         DepKind::CheckItemWellFormed => { force!(check_item_well_formed, def_id!()); }
1349         DepKind::CheckTraitItemWellFormed => { force!(check_trait_item_well_formed, def_id!()); }
1350         DepKind::CheckImplItemWellFormed => { force!(check_impl_item_well_formed, def_id!()); }
1351         DepKind::ReachableNonGenerics => { force!(reachable_non_generics, krate!()); }
1352         DepKind::NativeLibraries => { force!(native_libraries, krate!()); }
1353         DepKind::EntryFn => { force!(entry_fn, krate!()); }
1354         DepKind::PluginRegistrarFn => { force!(plugin_registrar_fn, krate!()); }
1355         DepKind::ProcMacroDeclsStatic => { force!(proc_macro_decls_static, krate!()); }
1356         DepKind::CrateDisambiguator => { force!(crate_disambiguator, krate!()); }
1357         DepKind::CrateHash => { force!(crate_hash, krate!()); }
1358         DepKind::OriginalCrateName => { force!(original_crate_name, krate!()); }
1359         DepKind::ExtraFileName => { force!(extra_filename, krate!()); }
1360         DepKind::Analysis => { force!(analysis, krate!()); }
1361
1362         DepKind::AllTraitImplementations => {
1363             force!(all_trait_implementations, krate!());
1364         }
1365
1366         DepKind::DllimportForeignItems => {
1367             force!(dllimport_foreign_items, krate!());
1368         }
1369         DepKind::IsDllimportForeignItem => {
1370             force!(is_dllimport_foreign_item, def_id!());
1371         }
1372         DepKind::IsStaticallyIncludedForeignItem => {
1373             force!(is_statically_included_foreign_item, def_id!());
1374         }
1375         DepKind::NativeLibraryKind => { force!(native_library_kind, def_id!()); }
1376         DepKind::LinkArgs => { force!(link_args, LOCAL_CRATE); }
1377
1378         DepKind::ResolveLifetimes => { force!(resolve_lifetimes, krate!()); }
1379         DepKind::NamedRegion => { force!(named_region_map, def_id!().index); }
1380         DepKind::IsLateBound => { force!(is_late_bound_map, def_id!().index); }
1381         DepKind::ObjectLifetimeDefaults => {
1382             force!(object_lifetime_defaults_map, def_id!().index);
1383         }
1384
1385         DepKind::Visibility => { force!(visibility, def_id!()); }
1386         DepKind::DepKind => { force!(dep_kind, krate!()); }
1387         DepKind::CrateName => { force!(crate_name, krate!()); }
1388         DepKind::ItemChildren => { force!(item_children, def_id!()); }
1389         DepKind::ExternModStmtCnum => { force!(extern_mod_stmt_cnum, def_id!()); }
1390         DepKind::GetLibFeatures => { force!(get_lib_features, LOCAL_CRATE); }
1391         DepKind::DefinedLibFeatures => { force!(defined_lib_features, krate!()); }
1392         DepKind::GetLangItems => { force!(get_lang_items, LOCAL_CRATE); }
1393         DepKind::DefinedLangItems => { force!(defined_lang_items, krate!()); }
1394         DepKind::MissingLangItems => { force!(missing_lang_items, krate!()); }
1395         DepKind::VisibleParentMap => { force!(visible_parent_map, LOCAL_CRATE); }
1396         DepKind::MissingExternCrateItem => {
1397             force!(missing_extern_crate_item, krate!());
1398         }
1399         DepKind::UsedCrateSource => { force!(used_crate_source, krate!()); }
1400         DepKind::PostorderCnums => { force!(postorder_cnums, LOCAL_CRATE); }
1401
1402         DepKind::Freevars => { force!(freevars, def_id!()); }
1403         DepKind::MaybeUnusedTraitImport => {
1404             force!(maybe_unused_trait_import, def_id!());
1405         }
1406         DepKind::NamesImportedByGlobUse => { force!(names_imported_by_glob_use, def_id!()); }
1407         DepKind::MaybeUnusedExternCrates => { force!(maybe_unused_extern_crates, LOCAL_CRATE); }
1408         DepKind::StabilityIndex => { force!(stability_index, LOCAL_CRATE); }
1409         DepKind::AllTraits => { force!(all_traits, LOCAL_CRATE); }
1410         DepKind::AllCrateNums => { force!(all_crate_nums, LOCAL_CRATE); }
1411         DepKind::ExportedSymbols => { force!(exported_symbols, krate!()); }
1412         DepKind::CollectAndPartitionMonoItems => {
1413             force!(collect_and_partition_mono_items, LOCAL_CRATE);
1414         }
1415         DepKind::IsCodegenedItem => { force!(is_codegened_item, def_id!()); }
1416         DepKind::OutputFilenames => { force!(output_filenames, LOCAL_CRATE); }
1417
1418         DepKind::TargetFeaturesWhitelist => { force!(target_features_whitelist, LOCAL_CRATE); }
1419
1420         DepKind::Features => { force!(features_query, LOCAL_CRATE); }
1421
1422         DepKind::ProgramClausesFor => { force!(program_clauses_for, def_id!()); }
1423         DepKind::WasmImportModuleMap => { force!(wasm_import_module_map, krate!()); }
1424         DepKind::ForeignModules => { force!(foreign_modules, krate!()); }
1425
1426         DepKind::UpstreamMonomorphizations => {
1427             force!(upstream_monomorphizations, krate!());
1428         }
1429         DepKind::UpstreamMonomorphizationsFor => {
1430             force!(upstream_monomorphizations_for, def_id!());
1431         }
1432         DepKind::BackendOptimizationLevel => {
1433             force!(backend_optimization_level, krate!());
1434         }
1435     }
1436
1437     true
1438 }
1439
1440
1441 // FIXME(#45015): Another piece of boilerplate code that could be generated in
1442 //                a combined define_dep_nodes!()/define_queries!() macro.
1443 macro_rules! impl_load_from_cache {
1444     ($($dep_kind:ident => $query_name:ident,)*) => {
1445         impl DepNode {
1446             // Check whether the query invocation corresponding to the given
1447             // DepNode is eligible for on-disk-caching.
1448             pub fn cache_on_disk(&self, tcx: TyCtxt<'_, '_, '_>) -> bool {
1449                 use crate::ty::query::queries;
1450                 use crate::ty::query::QueryDescription;
1451
1452                 match self.kind {
1453                     $(DepKind::$dep_kind => {
1454                         let def_id = self.extract_def_id(tcx).unwrap();
1455                         queries::$query_name::cache_on_disk(tcx.global_tcx(), def_id)
1456                     })*
1457                     _ => false
1458                 }
1459             }
1460
1461             // This is method will execute the query corresponding to the given
1462             // DepNode. It is only expected to work for DepNodes where the
1463             // above `cache_on_disk` methods returns true.
1464             // Also, as a sanity check, it expects that the corresponding query
1465             // invocation has been marked as green already.
1466             pub fn load_from_on_disk_cache(&self, tcx: TyCtxt<'_, '_, '_>) {
1467                 match self.kind {
1468                     $(DepKind::$dep_kind => {
1469                         debug_assert!(tcx.dep_graph
1470                                          .node_color(self)
1471                                          .map(|c| c.is_green())
1472                                          .unwrap_or(false));
1473
1474                         let def_id = self.extract_def_id(tcx).unwrap();
1475                         let _ = tcx.$query_name(def_id);
1476                     })*
1477                     _ => {
1478                         bug!()
1479                     }
1480                 }
1481             }
1482         }
1483     }
1484 }
1485
1486 impl_load_from_cache!(
1487     TypeckTables => typeck_tables_of,
1488     MirOptimized => optimized_mir,
1489     UnsafetyCheckResult => unsafety_check_result,
1490     BorrowCheck => borrowck,
1491     MirBorrowCheck => mir_borrowck,
1492     MirConstQualif => mir_const_qualif,
1493     SymbolName => def_symbol_name,
1494     ConstIsRvaluePromotableToStatic => const_is_rvalue_promotable_to_static,
1495     CheckMatch => check_match,
1496     TypeOfItem => type_of,
1497     GenericsOfItem => generics_of,
1498     PredicatesOfItem => predicates_of,
1499     UsedTraitImports => used_trait_imports,
1500     CodegenFnAttrs => codegen_fn_attrs,
1501     SpecializationGraph => specialization_graph_of,
1502 );