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: DepNodeParams<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}
169170pub trait DepNodeParams<Tcx: DepContext>: fmt::Debug + Sized {
171fn fingerprint_style() -> FingerprintStyle;
172173/// This method turns the parameters of a DepNodeConstructor into an opaque
174 /// Fingerprint to be used in DepNode.
175 /// Not all DepNodeParams support being turned into a Fingerprint (they
176 /// don't need to if the corresponding DepNode is anonymous).
177fn to_fingerprint(&self, _: Tcx) -> Fingerprint {
178{
::core::panicking::panic_fmt(format_args!("Not implemented. Accidentally called on anonymous node?"));
}panic!("Not implemented. Accidentally called on anonymous node?")179 }
180181fn to_debug_str(&self, tcx: Tcx) -> String;
182183/// This method tries to recover the query key from the given `DepNode`,
184 /// something which is needed when forcing `DepNode`s during red-green
185 /// evaluation. The query system will only call this method if
186 /// `fingerprint_style()` is not `FingerprintStyle::Opaque`.
187 /// It is always valid to return `None` here, in which case incremental
188 /// compilation will treat the query as having changed instead of forcing it.
189fn recover(tcx: Tcx, dep_node: &DepNode) -> Option<Self>;
190}
191192impl<Tcx: DepContext, T> DepNodeParams<Tcx> for T
193where
194T: for<'a> HashStable<StableHashingContext<'a>> + fmt::Debug,
195{
196#[inline(always)]
197default fn fingerprint_style() -> FingerprintStyle {
198 FingerprintStyle::Opaque199 }
200201#[inline(always)]
202default fn to_fingerprint(&self, tcx: Tcx) -> Fingerprint {
203tcx.with_stable_hashing_context(|mut hcx| {
204let mut hasher = StableHasher::new();
205self.hash_stable(&mut hcx, &mut hasher);
206hasher.finish()
207 })
208 }
209210#[inline(always)]
211default fn to_debug_str(&self, tcx: Tcx) -> String {
212// Make sure to print dep node params with reduced queries since printing
213 // may themselves call queries, which may lead to (possibly untracked!)
214 // query cycles.
215tcx.with_reduced_queries(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", self))
})format!("{self:?}"))
216 }
217218#[inline(always)]
219default fn recover(_: Tcx, _: &DepNode) -> Option<Self> {
220None221 }
222}
223224/// This struct stores function pointers and other metadata for a particular DepKind.
225///
226/// Information is retrieved by indexing the `DEP_KINDS` array using the integer value
227/// of the `DepKind`. Overall, this allows to implement `DepContext` using this manual
228/// jump table instead of large matches.
229pub struct DepKindVTable<Tcx: DepContext> {
230/// Anonymous queries cannot be replayed from one compiler invocation to the next.
231 /// When their result is needed, it is recomputed. They are useful for fine-grained
232 /// dependency tracking, and caching within one compiler invocation.
233pub is_anon: bool,
234235/// Eval-always queries do not track their dependencies, and are always recomputed, even if
236 /// their inputs have not changed since the last compiler invocation. The result is still
237 /// cached within one compiler invocation.
238pub is_eval_always: bool,
239240/// Whether the query key can be recovered from the hashed fingerprint.
241 /// See [DepNodeParams] trait for the behaviour of each key type.
242pub fingerprint_style: FingerprintStyle,
243244/// The red/green evaluation system will try to mark a specific DepNode in the
245 /// dependency graph as green by recursively trying to mark the dependencies of
246 /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode`
247 /// where we don't know if it is red or green and we therefore actually have
248 /// to recompute its value in order to find out. Since the only piece of
249 /// information that we have at that point is the `DepNode` we are trying to
250 /// re-evaluate, we need some way to re-run a query from just that. This is what
251 /// `force_from_dep_node()` implements.
252 ///
253 /// In the general case, a `DepNode` consists of a `DepKind` and an opaque
254 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
255 /// is usually constructed by computing a stable hash of the query-key that the
256 /// `DepNode` corresponds to. Consequently, it is not in general possible to go
257 /// back from hash to query-key (since hash functions are not reversible). For
258 /// this reason `force_from_dep_node()` is expected to fail from time to time
259 /// because we just cannot find out, from the `DepNode` alone, what the
260 /// corresponding query-key is and therefore cannot re-run the query.
261 ///
262 /// The system deals with this case letting `try_mark_green` fail which forces
263 /// the root query to be re-evaluated.
264 ///
265 /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless.
266 /// Fortunately, we can use some contextual information that will allow us to
267 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
268 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
269 /// valid `DefPathHash`. Since we also always build a huge table that maps every
270 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
271 /// everything we need to re-run the query.
272 ///
273 /// Take the `mir_promoted` query as an example. Like many other queries, it
274 /// just has a single parameter: the `DefId` of the item it will compute the
275 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
276 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
277 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
278 /// `DefId` in `tcx.def_path_hash_to_def_id`.
279pub force_from_dep_node:
280Option<fn(tcx: Tcx, dep_node: DepNode, prev_index: SerializedDepNodeIndex) -> bool>,
281282/// Invoke a query to put the on-disk cached value in memory.
283pub try_load_from_on_disk_cache: Option<fn(Tcx, DepNode)>,
284285/// The name of this dep kind.
286pub name: &'static &'static str,
287}
288289/// A "work product" corresponds to a `.o` (or other) file that we
290/// save in between runs. These IDs do not have a `DefId` but rather
291/// some independent path or string that persists between runs without
292/// the need to be mapped or unmapped. (This ensures we can serialize
293/// them even in the absence of a tcx.)
294#[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)]
295pub struct WorkProductId {
296 hash: Fingerprint,
297}
298299impl WorkProductId {
300pub fn from_cgu_name(cgu_name: &str) -> WorkProductId {
301let mut hasher = StableHasher::new();
302cgu_name.hash(&mut hasher);
303WorkProductId { hash: hasher.finish() }
304 }
305}
306307impl<HCX> HashStable<HCX> for WorkProductId {
308#[inline]
309fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
310self.hash.hash_stable(hcx, hasher)
311 }
312}
313impl<HCX> ToStableHashKey<HCX> for WorkProductId {
314type KeyType = Fingerprint;
315#[inline]
316fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
317self.hash
318 }
319}
320impl StableOrdfor WorkProductId {
321// Fingerprint can use unstable (just a tuple of `u64`s), so WorkProductId can as well
322const CAN_USE_UNSTABLE_SORT: bool = true;
323324// `WorkProductId` sort order is not affected by (de)serialization.
325const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
326}
327328// Some types are used a lot. Make sure they don't unintentionally get bigger.
329#[cfg(target_pointer_width = "64")]
330mod size_asserts {
331use rustc_data_structures::static_assert_size;
332333use super::*;
334// tidy-alphabetical-start
335const _: [(); 2] = [(); ::std::mem::size_of::<DepKind>()];static_assert_size!(DepKind, 2);
336#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
337const _: [(); 18] = [(); ::std::mem::size_of::<DepNode>()];static_assert_size!(DepNode, 18);
338#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
339static_assert_size!(DepNode, 24);
340// tidy-alphabetical-end
341}