1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The implementation of the query system itself. Defines the macros
12 //! that generate the actual methods on tcx which find and execute the
13 //! provider, manage the caches, and so forth.
15 use dep_graph::{DepNodeIndex, DepNode, DepKind, DepNodeColor};
16 use errors::DiagnosticBuilder;
18 use ty::maps::Query; // NB: actually generated by the macros in this file
19 use ty::maps::config::QueryDescription;
22 use rustc_data_structures::fx::{FxHashMap};
23 use std::cell::{Ref, RefMut};
24 use std::marker::PhantomData;
28 pub(super) struct QueryMap<'tcx, D: QueryDescription<'tcx>> {
29 phantom: PhantomData<(D, &'tcx ())>,
30 pub(super) map: FxHashMap<D::Key, QueryValue<D::Value>>,
33 pub(super) struct QueryValue<T> {
35 pub(super) index: DepNodeIndex,
38 impl<T> QueryValue<T> {
39 pub(super) fn new(value: T,
40 dep_node_index: DepNodeIndex)
44 index: dep_node_index,
49 impl<'tcx, M: QueryDescription<'tcx>> QueryMap<'tcx, M> {
50 pub(super) fn new() -> QueryMap<'tcx, M> {
58 pub(super) trait GetCacheInternal<'tcx>: QueryDescription<'tcx> + Sized {
59 fn get_cache_internal<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
60 -> Ref<'a, QueryMap<'tcx, Self>>;
63 pub(super) struct CycleError<'a, 'tcx: 'a> {
65 cycle: RefMut<'a, [(Span, Query<'tcx>)]>,
68 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
69 pub(super) fn report_cycle(self, CycleError { span, cycle }: CycleError)
70 -> DiagnosticBuilder<'a>
72 // Subtle: release the refcell lock before invoking `describe()`
73 // below by dropping `cycle`.
74 let stack = cycle.to_vec();
77 assert!(!stack.is_empty());
79 // Disable naming impls with types in this path, since that
80 // sometimes cycles itself, leading to extra cycle errors.
81 // (And cycle errors around impls tend to occur during the
82 // collect/coherence phases anyhow.)
83 item_path::with_forced_impl_filename_line(|| {
84 let span = self.sess.codemap().def_span(span);
86 struct_span_err!(self.sess, span, E0391,
87 "unsupported cyclic reference between types/traits detected");
88 err.span_label(span, "cyclic reference");
90 err.span_note(self.sess.codemap().def_span(stack[0].0),
91 &format!("the cycle begins when {}...", stack[0].1.describe(self)));
93 for &(span, ref query) in &stack[1..] {
94 err.span_note(self.sess.codemap().def_span(span),
95 &format!("...which then requires {}...", query.describe(self)));
98 err.note(&format!("...which then again requires {}, completing the cycle.",
99 stack[0].1.describe(self)));
105 pub(super) fn cycle_check<F, R>(self, span: Span, query: Query<'gcx>, compute: F)
106 -> Result<R, CycleError<'a, 'gcx>>
107 where F: FnOnce() -> R
110 let mut stack = self.maps.query_stack.borrow_mut();
111 if let Some((i, _)) = stack.iter().enumerate().rev()
112 .find(|&(_, &(_, ref q))| *q == query) {
113 return Err(CycleError {
115 cycle: RefMut::map(stack, |stack| &mut stack[i..])
118 stack.push((span, query));
121 let result = compute();
123 self.maps.query_stack.borrow_mut().pop();
128 /// Try to read a node index for the node dep_node.
129 /// A node will have an index, when it's already been marked green, or when we can mark it
130 /// green. This function will mark the current task as a reader of the specified node, when
131 /// the a node index can be found for that node.
132 pub(super) fn try_mark_green_and_read(self, dep_node: &DepNode) -> Option<DepNodeIndex> {
133 match self.dep_graph.node_color(dep_node) {
134 Some(DepNodeColor::Green(dep_node_index)) => {
135 self.dep_graph.read_index(dep_node_index);
138 Some(DepNodeColor::Red) => {
142 // try_mark_green (called below) will panic when full incremental
143 // compilation is disabled. If that's the case, we can't try to mark nodes
144 // as green anyway, so we can safely return None here.
145 if !self.dep_graph.is_fully_enabled() {
148 match self.dep_graph.try_mark_green(self.global_tcx(), &dep_node) {
149 Some(dep_node_index) => {
150 debug_assert!(self.dep_graph.is_green(dep_node_index));
151 self.dep_graph.read_index(dep_node_index);
163 // If enabled, send a message to the profile-queries thread
164 macro_rules! profq_msg {
165 ($tcx:expr, $msg:expr) => {
166 if cfg!(debug_assertions) {
167 if $tcx.sess.profile_queries() {
174 // If enabled, format a key using its debug string, which can be
175 // expensive to compute (in terms of time).
176 macro_rules! profq_key {
177 ($tcx:expr, $key:expr) => {
178 if cfg!(debug_assertions) {
179 if $tcx.sess.profile_queries_and_keys() {
180 Some(format!("{:?}", $key))
186 macro_rules! define_maps {
189 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
191 use dep_graph::DepNodeIndex;
192 use std::cell::RefCell;
196 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
199 impl<$tcx> Maps<$tcx> {
200 pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
204 query_stack: RefCell::new(vec![]),
205 $($name: RefCell::new(QueryMap::new())),*
211 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
212 pub enum Query<$tcx> {
213 $($(#[$attr])* $name($K)),*
217 #[derive(Clone, Debug, PartialEq, Eq)]
219 $($name(Option<String>)),*
222 impl<$tcx> Query<$tcx> {
223 pub fn describe(&self, tcx: TyCtxt) -> String {
224 let (r, name) = match *self {
225 $(Query::$name(key) => {
226 (queries::$name::describe(tcx, key), stringify!($name))
229 if tcx.sess.verbose() {
230 format!("{} [{}]", r, name)
238 use std::marker::PhantomData;
240 $(#[allow(bad_style)]
241 pub struct $name<$tcx> {
242 data: PhantomData<&$tcx ()>
246 $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
251 impl<$tcx> GetCacheInternal<$tcx> for queries::$name<$tcx> {
252 fn get_cache_internal<'a>(tcx: TyCtxt<'a, $tcx, $tcx>)
253 -> ::std::cell::Ref<'a, QueryMap<$tcx, Self>> {
254 tcx.maps.$name.borrow()
258 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
261 fn to_dep_node(tcx: TyCtxt<'a, $tcx, 'lcx>, key: &$K) -> DepNode {
262 use dep_graph::DepConstructor::*;
264 DepNode::new(tcx, $node(*key))
267 fn try_get_with(tcx: TyCtxt<'a, $tcx, 'lcx>,
270 -> Result<$V, CycleError<'a, $tcx>>
272 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
278 ProfileQueriesMsg::QueryBegin(
280 QueryMsg::$name(profq_key!(tcx, key))
284 if let Some(value) = tcx.maps.$name.borrow().map.get(&key) {
285 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
286 tcx.dep_graph.read_index(value.index);
287 return Ok((&value.value).clone());
290 // FIXME(eddyb) Get more valid Span's on queries.
291 // def_span guard is necessary to prevent a recursive loop,
292 // default_span calls def_span query internally.
293 if span == DUMMY_SP && stringify!($name) != "def_span" {
294 span = key.default_span(tcx)
297 // Fast path for when incr. comp. is off. `to_dep_node` is
298 // expensive for some DepKinds.
299 if !tcx.dep_graph.is_fully_enabled() {
300 let null_dep_node = DepNode::new_no_params(::dep_graph::DepKind::Null);
301 return Self::force(tcx, key, span, null_dep_node)
305 let dep_node = Self::to_dep_node(tcx, &key);
307 if dep_node.kind.is_anon() {
308 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
310 let res = tcx.cycle_check(span, Query::$name(key), || {
311 tcx.sess.diagnostic().track_diagnostics(|| {
312 tcx.dep_graph.with_anon_task(dep_node.kind, || {
313 Self::compute_result(tcx.global_tcx(), key)
318 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
319 let ((result, dep_node_index), diagnostics) = res;
321 tcx.dep_graph.read_index(dep_node_index);
323 tcx.on_disk_query_result_cache
324 .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
326 let value = QueryValue::new(result, dep_node_index);
337 if !dep_node.kind.is_input() {
338 if let Some(dep_node_index) = tcx.try_mark_green_and_read(&dep_node) {
339 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
340 return Self::load_from_disk_and_cache_in_memory(tcx,
348 match Self::force(tcx, key, span, dep_node) {
349 Ok((result, dep_node_index)) => {
350 tcx.dep_graph.read_index(dep_node_index);
357 /// Ensure that either this query has all green inputs or been executed.
358 /// Executing query::ensure(D) is considered a read of the dep-node D.
360 /// This function is particularly useful when executing passes for their
361 /// side-effects -- e.g., in order to report errors for erroneous programs.
363 /// Note: The optimization is only available during incr. comp.
364 pub fn ensure(tcx: TyCtxt<'a, $tcx, 'lcx>, key: $K) -> () {
365 let dep_node = Self::to_dep_node(tcx, &key);
367 // Ensuring an "input" or anonymous query makes no sense
368 assert!(!dep_node.kind.is_anon());
369 assert!(!dep_node.kind.is_input());
370 if tcx.try_mark_green_and_read(&dep_node).is_none() {
371 // A None return from `try_mark_green_and_read` means that this is either
372 // a new dep node or that the dep node has already been marked red.
373 // Either way, we can't call `dep_graph.read()` as we don't have the
374 // DepNodeIndex. We must invoke the query itself. The performance cost
375 // this introduces should be negligible as we'll immediately hit the
376 // in-memory cache, or another query down the line will.
377 let _ = tcx.$name(key);
381 fn compute_result(tcx: TyCtxt<'a, $tcx, 'lcx>, key: $K) -> $V {
382 let provider = tcx.maps.providers[key.map_crate()].$name;
383 provider(tcx.global_tcx(), key)
386 fn load_from_disk_and_cache_in_memory(tcx: TyCtxt<'a, $tcx, 'lcx>,
389 dep_node_index: DepNodeIndex,
391 -> Result<$V, CycleError<'a, $tcx>>
393 debug_assert!(tcx.dep_graph.is_green(dep_node_index));
395 // First we try to load the result from the on-disk cache
396 let result = if Self::cache_on_disk(key) &&
397 tcx.sess.opts.debugging_opts.incremental_queries {
398 let prev_dep_node_index =
399 tcx.dep_graph.prev_dep_node_index_of(dep_node);
400 let result = Self::try_load_from_disk(tcx.global_tcx(),
401 prev_dep_node_index);
403 // We always expect to find a cached result for things that
404 // can be forced from DepNode.
405 debug_assert!(!dep_node.kind.can_reconstruct_query_key() ||
407 "Missing on-disk cache entry for {:?}",
411 // Some things are never cached on disk.
415 let result = if let Some(result) = result {
418 // We could not load a result from the on-disk cache, so
420 let (result, _ ) = tcx.cycle_check(span, Query::$name(key), || {
421 // The diagnostics for this query have already been
422 // promoted to the current session during
423 // try_mark_green(), so we can ignore them here.
424 tcx.sess.diagnostic().track_diagnostics(|| {
425 // The dep-graph for this computation is already in
427 tcx.dep_graph.with_ignore(|| {
428 Self::compute_result(tcx, key)
435 // If -Zincremental-verify-ich is specified, re-hash results from
436 // the cache and make sure that they have the expected fingerprint.
437 if tcx.sess.opts.debugging_opts.incremental_verify_ich {
438 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
439 use ich::Fingerprint;
441 assert!(Some(tcx.dep_graph.fingerprint_of(dep_node_index)) ==
442 tcx.dep_graph.prev_fingerprint_of(dep_node),
443 "Fingerprint for green query instance not loaded \
444 from cache: {:?}", dep_node);
446 debug!("BEGIN verify_ich({:?})", dep_node);
447 let mut hcx = tcx.create_stable_hashing_context();
448 let mut hasher = StableHasher::new();
450 result.hash_stable(&mut hcx, &mut hasher);
452 let new_hash: Fingerprint = hasher.finish();
453 debug!("END verify_ich({:?})", dep_node);
455 let old_hash = tcx.dep_graph.fingerprint_of(dep_node_index);
457 assert!(new_hash == old_hash, "Found unstable fingerprints \
458 for {:?}", dep_node);
461 if tcx.sess.opts.debugging_opts.query_dep_graph {
462 tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
465 let value = QueryValue::new(result, dep_node_index);
476 fn force(tcx: TyCtxt<'a, $tcx, 'lcx>,
480 -> Result<($V, DepNodeIndex), CycleError<'a, $tcx>> {
481 debug_assert!(tcx.dep_graph.node_color(&dep_node).is_none());
483 profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
484 let res = tcx.cycle_check(span, Query::$name(key), || {
485 tcx.sess.diagnostic().track_diagnostics(|| {
486 if dep_node.kind.is_eval_always() {
487 tcx.dep_graph.with_eval_always_task(dep_node,
490 Self::compute_result)
492 tcx.dep_graph.with_task(dep_node,
495 Self::compute_result)
499 profq_msg!(tcx, ProfileQueriesMsg::ProviderEnd);
501 let ((result, dep_node_index), diagnostics) = res;
503 if tcx.sess.opts.debugging_opts.query_dep_graph {
504 tcx.dep_graph.mark_loaded_from_cache(dep_node_index, false);
507 if dep_node.kind != ::dep_graph::DepKind::Null {
508 tcx.on_disk_query_result_cache
509 .store_diagnostics(dep_node_index, diagnostics);
512 let value = QueryValue::new(result, dep_node_index);
524 pub fn try_get(tcx: TyCtxt<'a, $tcx, 'lcx>, span: Span, key: $K)
525 -> Result<$V, DiagnosticBuilder<'a>> {
526 match Self::try_get_with(tcx, span, key) {
528 Err(e) => Err(tcx.report_cycle(e)),
533 #[derive(Copy, Clone)]
534 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
535 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
539 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
540 type Target = TyCtxt<'a, 'gcx, 'tcx>;
541 fn deref(&self) -> &Self::Target {
546 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
547 /// Return a transparent wrapper for `TyCtxt` which uses
548 /// `span` as the location of queries performed through it.
549 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
557 pub fn $name(self, key: $K) -> $V {
558 self.at(DUMMY_SP).$name(key)
562 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
564 pub fn $name(self, key: $K) -> $V {
565 queries::$name::try_get(self.tcx, self.span, key).unwrap_or_else(|mut e| {
567 Value::from_cycle_error(self.global_tcx())
572 define_provider_struct! {
574 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
577 impl<$tcx> Copy for Providers<$tcx> {}
578 impl<$tcx> Clone for Providers<$tcx> {
579 fn clone(&self) -> Self { *self }
584 macro_rules! define_map_struct {
586 input: ($(([$(modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
587 pub struct Maps<$tcx> {
588 providers: IndexVec<CrateNum, Providers<$tcx>>,
589 query_stack: RefCell<Vec<(Span, Query<$tcx>)>>,
590 $($(#[$attr])* $name: RefCell<QueryMap<$tcx, queries::$name<$tcx>>>,)*
595 macro_rules! define_provider_struct {
597 input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
598 pub struct Providers<$tcx> {
599 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
602 impl<$tcx> Default for Providers<$tcx> {
603 fn default() -> Self {
604 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
605 bug!("tcx.maps.{}({:?}) unsupported by its crate",
606 stringify!($name), key);
608 Providers { $($name),* }
615 /// The red/green evaluation system will try to mark a specific DepNode in the
616 /// dependency graph as green by recursively trying to mark the dependencies of
617 /// that DepNode as green. While doing so, it will sometimes encounter a DepNode
618 /// where we don't know if it is red or green and we therefore actually have
619 /// to recompute its value in order to find out. Since the only piece of
620 /// information that we have at that point is the DepNode we are trying to
621 /// re-evaluate, we need some way to re-run a query from just that. This is what
622 /// `force_from_dep_node()` implements.
624 /// In the general case, a DepNode consists of a DepKind and an opaque
625 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
626 /// is usually constructed by computing a stable hash of the query-key that the
627 /// DepNode corresponds to. Consequently, it is not in general possible to go
628 /// back from hash to query-key (since hash functions are not reversible). For
629 /// this reason `force_from_dep_node()` is expected to fail from time to time
630 /// because we just cannot find out, from the DepNode alone, what the
631 /// corresponding query-key is and therefore cannot re-run the query.
633 /// The system deals with this case letting `try_mark_green` fail which forces
634 /// the root query to be re-evaluated.
636 /// Now, if force_from_dep_node() would always fail, it would be pretty useless.
637 /// Fortunately, we can use some contextual information that will allow us to
638 /// reconstruct query-keys for certain kinds of DepNodes. In particular, we
639 /// enforce by construction that the GUID/fingerprint of certain DepNodes is a
640 /// valid DefPathHash. Since we also always build a huge table that maps every
641 /// DefPathHash in the current codebase to the corresponding DefId, we have
642 /// everything we need to re-run the query.
644 /// Take the `mir_validated` query as an example. Like many other queries, it
645 /// just has a single parameter: the DefId of the item it will compute the
646 /// validated MIR for. Now, when we call `force_from_dep_node()` on a dep-node
647 /// with kind `MirValidated`, we know that the GUID/fingerprint of the dep-node
648 /// is actually a DefPathHash, and can therefore just look up the corresponding
649 /// DefId in `tcx.def_path_hash_to_def_id`.
651 /// When you implement a new query, it will likely have a corresponding new
652 /// DepKind, and you'll have to support it here in `force_from_dep_node()`. As
653 /// a rule of thumb, if your query takes a DefId or DefIndex as sole parameter,
654 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
655 /// add it to the "We don't have enough information to reconstruct..." group in
657 pub fn force_from_dep_node<'a, 'gcx, 'lcx>(tcx: TyCtxt<'a, 'gcx, 'lcx>,
660 use ty::maps::keys::Key;
661 use hir::def_id::LOCAL_CRATE;
663 // We must avoid ever having to call force_from_dep_node() for a
664 // DepNode::CodegenUnit:
665 // Since we cannot reconstruct the query key of a DepNode::CodegenUnit, we
666 // would always end up having to evaluate the first caller of the
667 // `codegen_unit` query that *is* reconstructible. This might very well be
668 // the `compile_codegen_unit` query, thus re-translating the whole CGU just
669 // to re-trigger calling the `codegen_unit` query with the right key. At
670 // that point we would already have re-done all the work we are trying to
671 // avoid doing in the first place.
672 // The solution is simple: Just explicitly call the `codegen_unit` query for
673 // each CGU, right after partitioning. This way `try_mark_green` will always
674 // hit the cache instead of having to go through `force_from_dep_node`.
675 // This assertion makes sure, we actually keep applying the solution above.
676 debug_assert!(dep_node.kind != DepKind::CodegenUnit,
677 "calling force_from_dep_node() on DepKind::CodegenUnit");
679 if !dep_node.kind.can_reconstruct_query_key() {
683 macro_rules! def_id {
685 if let Some(def_id) = dep_node.extract_def_id(tcx) {
688 // return from the whole function
695 () => { (def_id!()).krate }
699 ($query:ident, $key:expr) => {
701 use $crate::util::common::{ProfileQueriesMsg, profq_msg};
703 // FIXME(eddyb) Get more valid Span's on queries.
704 // def_span guard is necessary to prevent a recursive loop,
705 // default_span calls def_span query internally.
706 let span = if stringify!($query) != "def_span" {
707 $key.default_span(tcx)
709 ::syntax_pos::DUMMY_SP
713 ProfileQueriesMsg::QueryBegin(
715 ::ty::maps::QueryMsg::$query(profq_key!(tcx, $key))
719 match ::ty::maps::queries::$query::force(tcx, $key, span, *dep_node) {
722 tcx.report_cycle(e).emit();
729 // FIXME(#45015): We should try move this boilerplate code into a macro
731 match dep_node.kind {
732 // These are inputs that are expected to be pre-allocated and that
733 // should therefore always be red or green already
734 DepKind::AllLocalTraitImpls |
736 DepKind::CrateMetadata |
740 // This are anonymous nodes
741 DepKind::TraitSelect |
743 // We don't have enough information to reconstruct the query key of
751 DepKind::InstanceSymbolName |
753 DepKind::BorrowCheckKrate |
754 DepKind::Specializes |
755 DepKind::ImplementationsOfTrait |
756 DepKind::TypeParamPredicates |
757 DepKind::CodegenUnit |
758 DepKind::CompileCodegenUnit |
759 DepKind::FulfillObligation |
760 DepKind::VtableMethods |
761 DepKind::EraseRegionsTy |
762 DepKind::NormalizeTy |
763 DepKind::SubstituteNormalizeAndTestPredicates |
765 // This one should never occur in this context
767 bug!("force_from_dep_node() - Encountered {:?}", dep_node)
770 // These are not queries
771 DepKind::CoherenceCheckTrait |
772 DepKind::ItemVarianceConstraints => {
776 DepKind::RegionScopeTree => { force!(region_scope_tree, def_id!()); }
778 DepKind::Coherence => { force!(crate_inherent_impls, LOCAL_CRATE); }
779 DepKind::CoherenceInherentImplOverlapCheck => {
780 force!(crate_inherent_impls_overlap_check, LOCAL_CRATE)
782 DepKind::PrivacyAccessLevels => { force!(privacy_access_levels, LOCAL_CRATE); }
783 DepKind::MirBuilt => { force!(mir_built, def_id!()); }
784 DepKind::MirConstQualif => { force!(mir_const_qualif, def_id!()); }
785 DepKind::MirConst => { force!(mir_const, def_id!()); }
786 DepKind::MirValidated => { force!(mir_validated, def_id!()); }
787 DepKind::MirOptimized => { force!(optimized_mir, def_id!()); }
789 DepKind::BorrowCheck => { force!(borrowck, def_id!()); }
790 DepKind::MirBorrowCheck => { force!(mir_borrowck, def_id!()); }
791 DepKind::UnsafetyCheckResult => { force!(unsafety_check_result, def_id!()); }
792 DepKind::UnsafeDeriveOnReprPacked => { force!(unsafe_derive_on_repr_packed, def_id!()); }
793 DepKind::Reachability => { force!(reachable_set, LOCAL_CRATE); }
794 DepKind::MirKeys => { force!(mir_keys, LOCAL_CRATE); }
795 DepKind::CrateVariances => { force!(crate_variances, LOCAL_CRATE); }
796 DepKind::AssociatedItems => { force!(associated_item, def_id!()); }
797 DepKind::TypeOfItem => { force!(type_of, def_id!()); }
798 DepKind::GenericsOfItem => { force!(generics_of, def_id!()); }
799 DepKind::PredicatesOfItem => { force!(predicates_of, def_id!()); }
800 DepKind::InferredOutlivesOf => { force!(inferred_outlives_of, def_id!()); }
801 DepKind::SuperPredicatesOfItem => { force!(super_predicates_of, def_id!()); }
802 DepKind::TraitDefOfItem => { force!(trait_def, def_id!()); }
803 DepKind::AdtDefOfItem => { force!(adt_def, def_id!()); }
804 DepKind::IsAutoImpl => { force!(is_auto_impl, def_id!()); }
805 DepKind::ImplTraitRef => { force!(impl_trait_ref, def_id!()); }
806 DepKind::ImplPolarity => { force!(impl_polarity, def_id!()); }
807 DepKind::FnSignature => { force!(fn_sig, def_id!()); }
808 DepKind::CoerceUnsizedInfo => { force!(coerce_unsized_info, def_id!()); }
809 DepKind::ItemVariances => { force!(variances_of, def_id!()); }
810 DepKind::IsConstFn => { force!(is_const_fn, def_id!()); }
811 DepKind::IsForeignItem => { force!(is_foreign_item, def_id!()); }
812 DepKind::SizedConstraint => { force!(adt_sized_constraint, def_id!()); }
813 DepKind::DtorckConstraint => { force!(adt_dtorck_constraint, def_id!()); }
814 DepKind::AdtDestructor => { force!(adt_destructor, def_id!()); }
815 DepKind::AssociatedItemDefIds => { force!(associated_item_def_ids, def_id!()); }
816 DepKind::InherentImpls => { force!(inherent_impls, def_id!()); }
817 DepKind::TypeckBodiesKrate => { force!(typeck_item_bodies, LOCAL_CRATE); }
818 DepKind::TypeckTables => { force!(typeck_tables_of, def_id!()); }
819 DepKind::UsedTraitImports => { force!(used_trait_imports, def_id!()); }
820 DepKind::HasTypeckTables => { force!(has_typeck_tables, def_id!()); }
821 DepKind::SymbolName => { force!(def_symbol_name, def_id!()); }
822 DepKind::SpecializationGraph => { force!(specialization_graph_of, def_id!()); }
823 DepKind::ObjectSafety => { force!(is_object_safe, def_id!()); }
824 DepKind::TraitImpls => { force!(trait_impls_of, def_id!()); }
825 DepKind::CheckMatch => { force!(check_match, def_id!()); }
827 DepKind::ParamEnv => { force!(param_env, def_id!()); }
828 DepKind::DescribeDef => { force!(describe_def, def_id!()); }
829 DepKind::DefSpan => { force!(def_span, def_id!()); }
830 DepKind::LookupStability => { force!(lookup_stability, def_id!()); }
831 DepKind::LookupDeprecationEntry => {
832 force!(lookup_deprecation_entry, def_id!());
834 DepKind::ItemBodyNestedBodies => { force!(item_body_nested_bodies, def_id!()); }
835 DepKind::ConstIsRvaluePromotableToStatic => {
836 force!(const_is_rvalue_promotable_to_static, def_id!());
838 DepKind::RvaluePromotableMap => { force!(rvalue_promotable_map, def_id!()); }
839 DepKind::ImplParent => { force!(impl_parent, def_id!()); }
840 DepKind::TraitOfItem => { force!(trait_of_item, def_id!()); }
841 DepKind::IsExportedSymbol => { force!(is_exported_symbol, def_id!()); }
842 DepKind::IsMirAvailable => { force!(is_mir_available, def_id!()); }
843 DepKind::ItemAttrs => { force!(item_attrs, def_id!()); }
844 DepKind::FnArgNames => { force!(fn_arg_names, def_id!()); }
845 DepKind::DylibDepFormats => { force!(dylib_dependency_formats, krate!()); }
846 DepKind::IsPanicRuntime => { force!(is_panic_runtime, krate!()); }
847 DepKind::IsCompilerBuiltins => { force!(is_compiler_builtins, krate!()); }
848 DepKind::HasGlobalAllocator => { force!(has_global_allocator, krate!()); }
849 DepKind::ExternCrate => { force!(extern_crate, def_id!()); }
850 DepKind::LintLevels => { force!(lint_levels, LOCAL_CRATE); }
851 DepKind::InScopeTraits => { force!(in_scope_traits_map, def_id!().index); }
852 DepKind::ModuleExports => { force!(module_exports, def_id!()); }
853 DepKind::IsSanitizerRuntime => { force!(is_sanitizer_runtime, krate!()); }
854 DepKind::IsProfilerRuntime => { force!(is_profiler_runtime, krate!()); }
855 DepKind::GetPanicStrategy => { force!(panic_strategy, krate!()); }
856 DepKind::IsNoBuiltins => { force!(is_no_builtins, krate!()); }
857 DepKind::ImplDefaultness => { force!(impl_defaultness, def_id!()); }
858 DepKind::ExportedSymbolIds => { force!(exported_symbol_ids, krate!()); }
859 DepKind::NativeLibraries => { force!(native_libraries, krate!()); }
860 DepKind::PluginRegistrarFn => { force!(plugin_registrar_fn, krate!()); }
861 DepKind::DeriveRegistrarFn => { force!(derive_registrar_fn, krate!()); }
862 DepKind::CrateDisambiguator => { force!(crate_disambiguator, krate!()); }
863 DepKind::CrateHash => { force!(crate_hash, krate!()); }
864 DepKind::OriginalCrateName => { force!(original_crate_name, krate!()); }
866 DepKind::AllTraitImplementations => {
867 force!(all_trait_implementations, krate!());
870 DepKind::IsDllimportForeignItem => {
871 force!(is_dllimport_foreign_item, def_id!());
873 DepKind::IsStaticallyIncludedForeignItem => {
874 force!(is_statically_included_foreign_item, def_id!());
876 DepKind::NativeLibraryKind => { force!(native_library_kind, def_id!()); }
877 DepKind::LinkArgs => { force!(link_args, LOCAL_CRATE); }
879 DepKind::ResolveLifetimes => { force!(resolve_lifetimes, krate!()); }
880 DepKind::NamedRegion => { force!(named_region_map, def_id!().index); }
881 DepKind::IsLateBound => { force!(is_late_bound_map, def_id!().index); }
882 DepKind::ObjectLifetimeDefaults => {
883 force!(object_lifetime_defaults_map, def_id!().index);
886 DepKind::Visibility => { force!(visibility, def_id!()); }
887 DepKind::DepKind => { force!(dep_kind, krate!()); }
888 DepKind::CrateName => { force!(crate_name, krate!()); }
889 DepKind::ItemChildren => { force!(item_children, def_id!()); }
890 DepKind::ExternModStmtCnum => { force!(extern_mod_stmt_cnum, def_id!()); }
891 DepKind::GetLangItems => { force!(get_lang_items, LOCAL_CRATE); }
892 DepKind::DefinedLangItems => { force!(defined_lang_items, krate!()); }
893 DepKind::MissingLangItems => { force!(missing_lang_items, krate!()); }
894 DepKind::ExternConstBody => { force!(extern_const_body, def_id!()); }
895 DepKind::VisibleParentMap => { force!(visible_parent_map, LOCAL_CRATE); }
896 DepKind::MissingExternCrateItem => {
897 force!(missing_extern_crate_item, krate!());
899 DepKind::UsedCrateSource => { force!(used_crate_source, krate!()); }
900 DepKind::PostorderCnums => { force!(postorder_cnums, LOCAL_CRATE); }
901 DepKind::HasCloneClosures => { force!(has_clone_closures, krate!()); }
902 DepKind::HasCopyClosures => { force!(has_copy_closures, krate!()); }
904 DepKind::Freevars => { force!(freevars, def_id!()); }
905 DepKind::MaybeUnusedTraitImport => {
906 force!(maybe_unused_trait_import, def_id!());
908 DepKind::MaybeUnusedExternCrates => { force!(maybe_unused_extern_crates, LOCAL_CRATE); }
909 DepKind::StabilityIndex => { force!(stability_index, LOCAL_CRATE); }
910 DepKind::AllCrateNums => { force!(all_crate_nums, LOCAL_CRATE); }
911 DepKind::ExportedSymbols => { force!(exported_symbols, krate!()); }
912 DepKind::CollectAndPartitionTranslationItems => {
913 force!(collect_and_partition_translation_items, LOCAL_CRATE);
915 DepKind::ExportName => { force!(export_name, def_id!()); }
916 DepKind::ContainsExternIndicator => {
917 force!(contains_extern_indicator, def_id!());
919 DepKind::IsTranslatedFunction => { force!(is_translated_function, def_id!()); }
920 DepKind::OutputFilenames => { force!(output_filenames, LOCAL_CRATE); }
927 // FIXME(#45015): Another piece of boilerplate code that could be generated in
928 // a combined define_dep_nodes!()/define_maps!() macro.
929 macro_rules! impl_load_from_cache {
930 ($($dep_kind:ident => $query_name:ident,)*) => {
932 // Check whether the query invocation corresponding to the given
933 // DepNode is eligible for on-disk-caching.
934 pub fn cache_on_disk(&self, tcx: TyCtxt) -> bool {
935 use ty::maps::queries;
936 use ty::maps::QueryDescription;
939 $(DepKind::$dep_kind => {
940 let def_id = self.extract_def_id(tcx).unwrap();
941 queries::$query_name::cache_on_disk(def_id)
947 // This is method will execute the query corresponding to the given
948 // DepNode. It is only expected to work for DepNodes where the
949 // above `cache_on_disk` methods returns true.
950 // Also, as a sanity check, it expects that the corresponding query
951 // invocation has been marked as green already.
952 pub fn load_from_on_disk_cache(&self, tcx: TyCtxt) {
954 $(DepKind::$dep_kind => {
955 debug_assert!(tcx.dep_graph
957 .map(|c| c.is_green())
960 let def_id = self.extract_def_id(tcx).unwrap();
961 let _ = tcx.$query_name(def_id);
972 impl_load_from_cache!(
973 TypeckTables => typeck_tables_of,
974 MirOptimized => optimized_mir,
975 UnsafetyCheckResult => unsafety_check_result,
976 BorrowCheck => borrowck,
977 MirBorrowCheck => mir_borrowck,
978 MirConstQualif => mir_const_qualif,
979 SymbolName => def_symbol_name,
980 ConstIsRvaluePromotableToStatic => const_is_rvalue_promotable_to_static,
981 ContainsExternIndicator => contains_extern_indicator,
982 CheckMatch => check_match,