]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/query/mod.rs
54e80b4dc0b154cbf241186b4fb75400ffe835e2
[rust.git] / src / librustc / ty / query / mod.rs
1 use crate::dep_graph::{self, DepConstructor, DepNode, DepNodeParams};
2 use crate::hir::exports::Export;
3 use crate::hir::map;
4 use crate::hir::{HirOwner, HirOwnerItems};
5 use crate::infer::canonical::{self, Canonical};
6 use crate::lint::LintLevelMap;
7 use crate::middle::codegen_fn_attrs::CodegenFnAttrs;
8 use crate::middle::cstore::{CrateSource, DepKind, NativeLibraryKind};
9 use crate::middle::cstore::{ExternCrate, ForeignModule, LinkagePreference, NativeLibrary};
10 use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
11 use crate::middle::lang_items::{LangItem, LanguageItems};
12 use crate::middle::lib_features::LibFeatures;
13 use crate::middle::privacy::AccessLevels;
14 use crate::middle::region;
15 use crate::middle::resolve_lifetime::{ObjectLifetimeDefault, Region, ResolveLifetimes};
16 use crate::middle::stability::{self, DeprecationEntry};
17 use crate::mir;
18 use crate::mir::interpret::GlobalId;
19 use crate::mir::interpret::{ConstEvalRawResult, ConstEvalResult, ConstValue};
20 use crate::mir::interpret::{LitToConstError, LitToConstInput};
21 use crate::mir::mono::CodegenUnit;
22 use crate::session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
23 use crate::session::CrateDisambiguator;
24 use crate::traits::query::{
25     CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,
26     CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpNormalizeGoal,
27     CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpSubtypeGoal, NoSolution,
28 };
29 use crate::traits::query::{
30     DropckOutlivesResult, DtorckConstraint, MethodAutoderefStepsResult, NormalizationResult,
31     OutlivesBound,
32 };
33 use crate::traits::specialization_graph;
34 use crate::traits::Clauses;
35 use crate::traits::{self, Vtable};
36 use crate::ty::steal::Steal;
37 use crate::ty::subst::SubstsRef;
38 use crate::ty::util::AlwaysRequiresDrop;
39 use crate::ty::{self, AdtSizedConstraint, CrateInherentImpls, ParamEnvAnd, Ty, TyCtxt};
40 use crate::util::common::ErrorReported;
41 use rustc_data_structures::fingerprint::Fingerprint;
42 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
43 use rustc_data_structures::profiling::ProfileCategory::*;
44 use rustc_data_structures::stable_hasher::StableVec;
45 use rustc_data_structures::svh::Svh;
46 use rustc_data_structures::sync::Lrc;
47 use rustc_hir as hir;
48 use rustc_hir::def::DefKind;
49 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, DefIndex};
50 use rustc_hir::{Crate, HirIdSet, ItemLocalId, TraitCandidate};
51 use rustc_index::vec::IndexVec;
52 use rustc_target::spec::PanicStrategy;
53
54 use rustc_ast::ast;
55 use rustc_attr as attr;
56 use rustc_span::symbol::Symbol;
57 use rustc_span::{Span, DUMMY_SP};
58 use std::borrow::Cow;
59 use std::collections::BTreeMap;
60 use std::ops::Deref;
61 use std::sync::Arc;
62
63 #[macro_use]
64 mod plumbing;
65 pub use self::plumbing::CycleError;
66 use self::plumbing::*;
67
68 mod stats;
69 pub use self::stats::print_stats;
70
71 mod job;
72 #[cfg(parallel_compiler)]
73 pub use self::job::handle_deadlock;
74 use self::job::QueryJobInfo;
75 pub use self::job::{QueryInfo, QueryJob, QueryJobId};
76
77 mod keys;
78 use self::keys::Key;
79
80 mod values;
81 use self::values::Value;
82
83 mod caches;
84 use self::caches::CacheSelector;
85
86 mod config;
87 use self::config::QueryAccessors;
88 pub use self::config::QueryConfig;
89 pub(crate) use self::config::QueryDescription;
90
91 mod on_disk_cache;
92 pub use self::on_disk_cache::OnDiskCache;
93
94 mod profiling_support;
95 pub use self::profiling_support::{IntoSelfProfilingString, QueryKeyStringBuilder};
96
97 // Each of these queries corresponds to a function pointer field in the
98 // `Providers` struct for requesting a value of that type, and a method
99 // on `tcx: TyCtxt` (and `tcx.at(span)`) for doing that request in a way
100 // which memoizes and does dep-graph tracking, wrapping around the actual
101 // `Providers` that the driver creates (using several `rustc_*` crates).
102 //
103 // The result type of each query must implement `Clone`, and additionally
104 // `ty::query::values::Value`, which produces an appropriate placeholder
105 // (error) value if the query resulted in a query cycle.
106 // Queries marked with `fatal_cycle` do not need the latter implementation,
107 // as they will raise an fatal error on query cycles instead.
108
109 rustc_query_append! { [define_queries!][<'tcx>] }
110
111 /// The red/green evaluation system will try to mark a specific DepNode in the
112 /// dependency graph as green by recursively trying to mark the dependencies of
113 /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode`
114 /// where we don't know if it is red or green and we therefore actually have
115 /// to recompute its value in order to find out. Since the only piece of
116 /// information that we have at that point is the `DepNode` we are trying to
117 /// re-evaluate, we need some way to re-run a query from just that. This is what
118 /// `force_from_dep_node()` implements.
119 ///
120 /// In the general case, a `DepNode` consists of a `DepKind` and an opaque
121 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
122 /// is usually constructed by computing a stable hash of the query-key that the
123 /// `DepNode` corresponds to. Consequently, it is not in general possible to go
124 /// back from hash to query-key (since hash functions are not reversible). For
125 /// this reason `force_from_dep_node()` is expected to fail from time to time
126 /// because we just cannot find out, from the `DepNode` alone, what the
127 /// corresponding query-key is and therefore cannot re-run the query.
128 ///
129 /// The system deals with this case letting `try_mark_green` fail which forces
130 /// the root query to be re-evaluated.
131 ///
132 /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless.
133 /// Fortunately, we can use some contextual information that will allow us to
134 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
135 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
136 /// valid `DefPathHash`. Since we also always build a huge table that maps every
137 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
138 /// everything we need to re-run the query.
139 ///
140 /// Take the `mir_validated` query as an example. Like many other queries, it
141 /// just has a single parameter: the `DefId` of the item it will compute the
142 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
143 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
144 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
145 /// `DefId` in `tcx.def_path_hash_to_def_id`.
146 ///
147 /// When you implement a new query, it will likely have a corresponding new
148 /// `DepKind`, and you'll have to support it here in `force_from_dep_node()`. As
149 /// a rule of thumb, if your query takes a `DefId` or `DefIndex` as sole parameter,
150 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
151 /// add it to the "We don't have enough information to reconstruct..." group in
152 /// the match below.
153 pub fn force_from_dep_node<'tcx>(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> bool {
154     use crate::dep_graph::DepKind;
155
156     // We must avoid ever having to call `force_from_dep_node()` for a
157     // `DepNode::codegen_unit`:
158     // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we
159     // would always end up having to evaluate the first caller of the
160     // `codegen_unit` query that *is* reconstructible. This might very well be
161     // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
162     // to re-trigger calling the `codegen_unit` query with the right key. At
163     // that point we would already have re-done all the work we are trying to
164     // avoid doing in the first place.
165     // The solution is simple: Just explicitly call the `codegen_unit` query for
166     // each CGU, right after partitioning. This way `try_mark_green` will always
167     // hit the cache instead of having to go through `force_from_dep_node`.
168     // This assertion makes sure, we actually keep applying the solution above.
169     debug_assert!(
170         dep_node.kind != DepKind::codegen_unit,
171         "calling force_from_dep_node() on DepKind::codegen_unit"
172     );
173
174     if !dep_node.kind.can_reconstruct_query_key() {
175         return false;
176     }
177
178     rustc_dep_node_force!([dep_node, tcx]
179         // These are inputs that are expected to be pre-allocated and that
180         // should therefore always be red or green already.
181         DepKind::CrateMetadata |
182
183         // These are anonymous nodes.
184         DepKind::TraitSelect |
185
186         // We don't have enough information to reconstruct the query key of
187         // these.
188         DepKind::CompileCodegenUnit => {
189             bug!("force_from_dep_node: encountered {:?}", dep_node)
190         }
191     );
192
193     false
194 }
195
196 impl DepNode {
197     /// Check whether the query invocation corresponding to the given
198     /// DepNode is eligible for on-disk-caching. If so, this is method
199     /// will execute the query corresponding to the given DepNode.
200     /// Also, as a sanity check, it expects that the corresponding query
201     /// invocation has been marked as green already.
202     pub fn try_load_from_on_disk_cache<'tcx>(&self, tcx: TyCtxt<'tcx>) {
203         use crate::dep_graph::DepKind;
204
205         rustc_dep_node_try_load_from_on_disk_cache!(self, tcx)
206     }
207 }