1//! This module defines the [`DepNode`] type which the compiler uses to represent
2//! nodes in the [dependency graph]. A `DepNode` consists of a [`DepKind`] (which
3//! specifies the kind of thing it represents, like a piece of HIR, MIR, etc.)
4//! and a [`Fingerprint`], a 128-bit hash value, the exact meaning of which
5//! depends on the node's `DepKind`. Together, the kind and the fingerprint
6//! fully identify a dependency node, even across multiple compilation sessions.
7//! In other words, the value of the fingerprint does not depend on anything
8//! that is specific to a given compilation session, like an unpredictable
9//! interning key (e.g., `NodeId`, `DefId`, `Symbol`) or the numeric value of a
10//! pointer. The concept behind this could be compared to how git commit hashes
11//! uniquely identify a given commit. The fingerprinting approach has
12//! a few advantages:
13//!
14//! * A `DepNode` can simply be serialized to disk and loaded in another session
15//! without the need to do any "rebasing" (like we have to do for Spans and
16//! NodeIds) or "retracing" (like we had to do for `DefId` in earlier
17//! implementations of the dependency graph).
18//! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to
19//! implement `Copy`, `Sync`, `Send`, `Freeze`, etc.
20//! * Since we just have a bit pattern, `DepNode` can be mapped from disk into
21//! memory without any post-processing (e.g., "abomination-style" pointer
22//! reconstruction).
23//! * Because a `DepNode` is self-contained, we can instantiate `DepNodes` that
24//! refer to things that do not exist anymore. In previous implementations
25//! `DepNode` contained a `DefId`. A `DepNode` referring to something that
26//! had been removed between the previous and the current compilation session
27//! could not be instantiated because the current compilation session
28//! contained no `DefId` for thing that had been removed.
29//!
30//! `DepNode` definition happens in `rustc_middle` with the
31//! `define_dep_nodes!()` macro. This macro defines the `DepKind` enum. Each
32//! `DepKind` has its own parameters that are needed at runtime in order to
33//! construct a valid `DepNode` fingerprint. However, only `CompileCodegenUnit`
34//! and `CompileMonoItem` are constructed explicitly (with
35//! `make_compile_codegen_unit` and `make_compile_mono_item`).
36//!
37//! Because the macro sees what parameters a given `DepKind` requires, it can
38//! "infer" some properties for each kind of `DepNode`:
39//!
40//! * Whether a `DepNode` of a given kind has any parameters at all. Some
41//! `DepNode`s could represent global concepts with only one value.
42//! * Whether it is possible, in principle, to reconstruct a query key from a
43//! given `DepNode`. Many `DepKind`s only require a single `DefId` parameter,
44//! in which case it is possible to map the node's fingerprint back to the
45//! `DefId` it was computed from. In other cases, too much information gets
46//! lost during fingerprint computation.
47//!
48//! `make_compile_codegen_unit` and `make_compile_mono_items`, together with
49//! `DepNode::new()`, ensure that only valid `DepNode` instances can be
50//! constructed. For example, the API does not allow for constructing
51//! parameterless `DepNode`s with anything other than a zeroed out fingerprint.
52//! More generally speaking, it relieves the user of the `DepNode` API of
53//! having to know how to compute the expected fingerprint for a given set of
54//! node parameters.
55//!
56//! [dependency graph]: https://rustc-dev-guide.rust-lang.org/query.html
5758use std::fmt;
59use std::hash::Hash;
6061use rustc_data_structures::AtomicRef;
62use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
63use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableOrd, ToStableHashKey};
64use rustc_hir::definitions::DefPathHash;
65use rustc_macros::{Decodable, Encodable};
6667use super::{DepContext, FingerprintStyle, SerializedDepNodeIndex};
68use crate::ich::StableHashingContext;
6970/// This serves as an index into arrays built by `make_dep_kind_array`.
71#[derive(#[automatically_derived]
impl ::core::clone::Clone for DepKind {
#[inline]
fn clone(&self) -> DepKind {
let _: ::core::clone::AssertParamIsClone<u16>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DepKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for DepKind {
#[inline]
fn eq(&self, other: &DepKind) -> bool { self.variant == other.variant }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DepKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u16>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for DepKind {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.variant, state)
}
}Hash)]
72pub struct DepKind {
73 variant: u16,
74}
7576impl DepKind {
77#[inline]
78pub const fn new(variant: u16) -> Self {
79Self { variant }
80 }
8182#[inline]
83pub const fn as_inner(&self) -> u16 {
84self.variant
85 }
8687#[inline]
88pub const fn as_usize(&self) -> usize {
89self.variant as usize90 }
91}
9293pub fn default_dep_kind_debug(kind: DepKind, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94f.debug_struct("DepKind").field("variant", &kind.variant).finish()
95}
9697pub static DEP_KIND_DEBUG: AtomicRef<fn(DepKind, &mut fmt::Formatter<'_>) -> fmt::Result> =
98AtomicRef::new(&(default_dep_kind_debugas fn(_, &mut fmt::Formatter<'_>) -> _));
99100impl fmt::Debugfor DepKind {
101fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 (*DEP_KIND_DEBUG)(*self, f)
103 }
104}
105106#[derive(#[automatically_derived]
impl ::core::clone::Clone for DepNode {
#[inline]
fn clone(&self) -> DepNode {
let _: ::core::clone::AssertParamIsClone<DepKind>;
let _: ::core::clone::AssertParamIsClone<PackedFingerprint>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DepNode { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for DepNode {
#[inline]
fn eq(&self, other: &DepNode) -> bool {
self.kind == other.kind && self.hash == other.hash
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DepNode {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<DepKind>;
let _: ::core::cmp::AssertParamIsEq<PackedFingerprint>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for DepNode {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.kind, state);
::core::hash::Hash::hash(&self.hash, state)
}
}Hash)]
107pub struct DepNode {
108pub kind: DepKind,
109pub hash: PackedFingerprint,
110}
111112impl DepNode {
113/// Creates a new, parameterless DepNode. This method will assert
114 /// that the DepNode corresponding to the given DepKind actually
115 /// does not require any parameters.
116pub fn new_no_params<Tcx>(tcx: Tcx, kind: DepKind) -> DepNode117where
118Tcx: super::DepContext,
119 {
120if true {
match (&tcx.fingerprint_style(kind), &FingerprintStyle::Unit) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(tcx.fingerprint_style(kind), FingerprintStyle::Unit);
121DepNode { kind, hash: Fingerprint::ZERO.into() }
122 }
123124pub fn construct<Tcx, Key>(tcx: Tcx, kind: DepKind, arg: &Key) -> DepNode125where
126Tcx: super::DepContext,
127 Key: DepNodeKey<Tcx>,
128 {
129let hash = arg.to_fingerprint(tcx);
130let dep_node = DepNode { kind, hash: hash.into() };
131132#[cfg(debug_assertions)]
133{
134if !tcx.fingerprint_style(kind).reconstructible()
135 && (tcx.sess().opts.unstable_opts.incremental_info
136 || tcx.sess().opts.unstable_opts.query_dep_graph)
137 {
138tcx.dep_graph().register_dep_node_debug_str(dep_node, || arg.to_debug_str(tcx));
139 }
140 }
141142dep_node143 }
144145/// Construct a DepNode from the given DepKind and DefPathHash. This
146 /// method will assert that the given DepKind actually requires a
147 /// single DefId/DefPathHash parameter.
148pub fn from_def_path_hash<Tcx>(tcx: Tcx, def_path_hash: DefPathHash, kind: DepKind) -> Self
149where
150Tcx: super::DepContext,
151 {
152if true {
if !(tcx.fingerprint_style(kind) == FingerprintStyle::DefPathHash) {
::core::panicking::panic("assertion failed: tcx.fingerprint_style(kind) == FingerprintStyle::DefPathHash")
};
};debug_assert!(tcx.fingerprint_style(kind) == FingerprintStyle::DefPathHash);
153DepNode { kind, hash: def_path_hash.0.into() }
154 }
155}
156157pub fn default_dep_node_debug(node: DepNode, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158f.debug_struct("DepNode").field("kind", &node.kind).field("hash", &node.hash).finish()
159}
160161pub static DEP_NODE_DEBUG: AtomicRef<fn(DepNode, &mut fmt::Formatter<'_>) -> fmt::Result> =
162AtomicRef::new(&(default_dep_node_debugas fn(_, &mut fmt::Formatter<'_>) -> _));
163164impl fmt::Debugfor DepNode {
165fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 (*DEP_NODE_DEBUG)(*self, f)
167 }
168}
169170/// Trait for query keys as seen by dependency-node tracking.
171pub trait DepNodeKey<Tcx: DepContext>: fmt::Debug + Sized {
172fn fingerprint_style() -> FingerprintStyle;
173174/// This method turns a query key into an opaque `Fingerprint` to be used
175 /// in `DepNode`.
176fn to_fingerprint(&self, _: Tcx) -> Fingerprint;
177178fn to_debug_str(&self, tcx: Tcx) -> String;
179180/// This method tries to recover the query key from the given `DepNode`,
181 /// something which is needed when forcing `DepNode`s during red-green
182 /// evaluation. The query system will only call this method if
183 /// `fingerprint_style()` is not `FingerprintStyle::Opaque`.
184 /// It is always valid to return `None` here, in which case incremental
185 /// compilation will treat the query as having changed instead of forcing it.
186fn recover(tcx: Tcx, dep_node: &DepNode) -> Option<Self>;
187}
188189// Blanket impl of `DepNodeKey`, which is specialized by other impls elsewhere.
190impl<Tcx: DepContext, T> DepNodeKey<Tcx> for T
191where
192T: for<'a> HashStable<StableHashingContext<'a>> + fmt::Debug,
193{
194#[inline(always)]
195default fn fingerprint_style() -> FingerprintStyle {
196 FingerprintStyle::Opaque197 }
198199#[inline(always)]
200default fn to_fingerprint(&self, tcx: Tcx) -> Fingerprint {
201tcx.with_stable_hashing_context(|mut hcx| {
202let mut hasher = StableHasher::new();
203self.hash_stable(&mut hcx, &mut hasher);
204hasher.finish()
205 })
206 }
207208#[inline(always)]
209default fn to_debug_str(&self, tcx: Tcx) -> String {
210// Make sure to print dep node params with reduced queries since printing
211 // may themselves call queries, which may lead to (possibly untracked!)
212 // query cycles.
213tcx.with_reduced_queries(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", self))
})format!("{self:?}"))
214 }
215216#[inline(always)]
217default fn recover(_: Tcx, _: &DepNode) -> Option<Self> {
218None219 }
220}
221222/// This struct stores function pointers and other metadata for a particular DepKind.
223///
224/// Information is retrieved by indexing the `DEP_KINDS` array using the integer value
225/// of the `DepKind`. Overall, this allows to implement `DepContext` using this manual
226/// jump table instead of large matches.
227pub struct DepKindVTable<Tcx: DepContext> {
228/// Anonymous queries cannot be replayed from one compiler invocation to the next.
229 /// When their result is needed, it is recomputed. They are useful for fine-grained
230 /// dependency tracking, and caching within one compiler invocation.
231pub is_anon: bool,
232233/// Eval-always queries do not track their dependencies, and are always recomputed, even if
234 /// their inputs have not changed since the last compiler invocation. The result is still
235 /// cached within one compiler invocation.
236pub is_eval_always: bool,
237238/// Indicates whether and how the query key can be recovered from its hashed fingerprint.
239 ///
240 /// The [`DepNodeKey`] trait determines the fingerprint style for each key type.
241pub fingerprint_style: FingerprintStyle,
242243/// The red/green evaluation system will try to mark a specific DepNode in the
244 /// dependency graph as green by recursively trying to mark the dependencies of
245 /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode`
246 /// where we don't know if it is red or green and we therefore actually have
247 /// to recompute its value in order to find out. Since the only piece of
248 /// information that we have at that point is the `DepNode` we are trying to
249 /// re-evaluate, we need some way to re-run a query from just that. This is what
250 /// `force_from_dep_node()` implements.
251 ///
252 /// In the general case, a `DepNode` consists of a `DepKind` and an opaque
253 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
254 /// is usually constructed by computing a stable hash of the query-key that the
255 /// `DepNode` corresponds to. Consequently, it is not in general possible to go
256 /// back from hash to query-key (since hash functions are not reversible). For
257 /// this reason `force_from_dep_node()` is expected to fail from time to time
258 /// because we just cannot find out, from the `DepNode` alone, what the
259 /// corresponding query-key is and therefore cannot re-run the query.
260 ///
261 /// The system deals with this case letting `try_mark_green` fail which forces
262 /// the root query to be re-evaluated.
263 ///
264 /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless.
265 /// Fortunately, we can use some contextual information that will allow us to
266 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
267 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
268 /// valid `DefPathHash`. Since we also always build a huge table that maps every
269 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
270 /// everything we need to re-run the query.
271 ///
272 /// Take the `mir_promoted` query as an example. Like many other queries, it
273 /// just has a single parameter: the `DefId` of the item it will compute the
274 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
275 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
276 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
277 /// `DefId` in `tcx.def_path_hash_to_def_id`.
278pub force_from_dep_node:
279Option<fn(tcx: Tcx, dep_node: DepNode, prev_index: SerializedDepNodeIndex) -> bool>,
280281/// Invoke a query to put the on-disk cached value in memory.
282pub try_load_from_on_disk_cache: Option<fn(Tcx, DepNode)>,
283284/// The name of this dep kind.
285pub name: &'static &'static str,
286}
287288/// A "work product" corresponds to a `.o` (or other) file that we
289/// save in between runs. These IDs do not have a `DefId` but rather
290/// some independent path or string that persists between runs without
291/// the need to be mapped or unmapped. (This ensures we can serialize
292/// them even in the absence of a tcx.)
293#[derive(#[automatically_derived]
impl ::core::clone::Clone for WorkProductId {
#[inline]
fn clone(&self) -> WorkProductId {
let _: ::core::clone::AssertParamIsClone<Fingerprint>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for WorkProductId { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for WorkProductId {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "WorkProductId",
"hash", &&self.hash)
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for WorkProductId {
#[inline]
fn eq(&self, other: &WorkProductId) -> bool { self.hash == other.hash }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for WorkProductId {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Fingerprint>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for WorkProductId {
#[inline]
fn partial_cmp(&self, other: &WorkProductId)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::cmp::PartialOrd::partial_cmp(&self.hash, &other.hash)
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for WorkProductId {
#[inline]
fn cmp(&self, other: &WorkProductId) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.hash, &other.hash)
}
}Ord, #[automatically_derived]
impl ::core::hash::Hash for WorkProductId {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.hash, state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for WorkProductId {
fn encode(&self, __encoder: &mut __E) {
match *self {
WorkProductId { hash: ref __binding_0 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for WorkProductId {
fn decode(__decoder: &mut __D) -> Self {
WorkProductId {
hash: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
294pub struct WorkProductId {
295 hash: Fingerprint,
296}
297298impl WorkProductId {
299pub fn from_cgu_name(cgu_name: &str) -> WorkProductId {
300let mut hasher = StableHasher::new();
301cgu_name.hash(&mut hasher);
302WorkProductId { hash: hasher.finish() }
303 }
304}
305306impl<HCX> HashStable<HCX> for WorkProductId {
307#[inline]
308fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
309self.hash.hash_stable(hcx, hasher)
310 }
311}
312impl<HCX> ToStableHashKey<HCX> for WorkProductId {
313type KeyType = Fingerprint;
314#[inline]
315fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
316self.hash
317 }
318}
319impl StableOrdfor WorkProductId {
320// Fingerprint can use unstable (just a tuple of `u64`s), so WorkProductId can as well
321const CAN_USE_UNSTABLE_SORT: bool = true;
322323// `WorkProductId` sort order is not affected by (de)serialization.
324const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
325}
326327// Some types are used a lot. Make sure they don't unintentionally get bigger.
328#[cfg(target_pointer_width = "64")]
329mod size_asserts {
330use rustc_data_structures::static_assert_size;
331332use super::*;
333// tidy-alphabetical-start
334const _: [(); 2] = [(); ::std::mem::size_of::<DepKind>()];static_assert_size!(DepKind, 2);
335#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
336const _: [(); 18] = [(); ::std::mem::size_of::<DepNode>()];static_assert_size!(DepNode, 18);
337#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
338static_assert_size!(DepNode, 24);
339// tidy-alphabetical-end
340}