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