]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_query_system/src/dep_graph/dep_node.rs
Merge tag 'debian/1.52.1+dfsg1-1_exp2' into proxmox/buster
[rustc.git] / compiler / rustc_query_system / src / dep_graph / dep_node.rs
CommitLineData
ba9703b0
XL
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 and has a few advantages:
12//!
13//! * A `DepNode` can simply be serialized to disk and loaded in another session
14//! without the need to do any "rebasing (like we have to do for Spans and
15//! NodeIds) or "retracing" like we had to do for `DefId` in earlier
16//! implementations of the dependency graph.
17//! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to
18//! implement `Copy`, `Sync`, `Send`, `Freeze`, etc.
19//! * Since we just have a bit pattern, `DepNode` can be mapped from disk into
20//! memory without any post-processing (e.g., "abomination-style" pointer
21//! reconstruction).
22//! * Because a `DepNode` is self-contained, we can instantiate `DepNodes` that
23//! refer to things that do not exist anymore. In previous implementations
24//! `DepNode` contained a `DefId`. A `DepNode` referring to something that
25//! had been removed between the previous and the current compilation session
26//! could not be instantiated because the current compilation session
27//! contained no `DefId` for thing that had been removed.
28//!
29//! `DepNode` definition happens in `librustc_middle` with the `define_dep_nodes!()` macro.
30//! This macro defines the `DepKind` enum and a corresponding `DepConstructor` enum. The
31//! `DepConstructor` enum links a `DepKind` to the parameters that are needed at runtime in order
32//! to construct a valid `DepNode` fingerprint.
33//!
34//! Because the macro sees what parameters a given `DepKind` requires, it can
35//! "infer" some properties for each kind of `DepNode`:
36//!
37//! * Whether a `DepNode` of a given kind has any parameters at all. Some
38//! `DepNode`s could represent global concepts with only one value.
39//! * Whether it is possible, in principle, to reconstruct a query key from a
40//! given `DepNode`. Many `DepKind`s only require a single `DefId` parameter,
41//! in which case it is possible to map the node's fingerprint back to the
42//! `DefId` it was computed from. In other cases, too much information gets
43//! lost during fingerprint computation.
44
45use super::{DepContext, DepKind};
46
fc512014 47use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
ba9703b0
XL
48use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
49
50use std::fmt;
51use std::hash::Hash;
52
3dfed10e 53#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
ba9703b0
XL
54pub struct DepNode<K> {
55 pub kind: K,
fc512014
XL
56 // Important - whenever a `DepNode` is constructed, we need to make
57 // sure to register a `DefPathHash -> DefId` mapping if needed.
58 // This is currently done in two places:
59 //
60 // * When a `DepNode::construct` is called, `arg.to_fingerprint()`
61 // is responsible for calling `OnDiskCache::store_foreign_def_id_hash`
62 // if needed
63 // * When we serialize the on-disk cache, `OnDiskCache::serialize` is
64 // responsible for calling `DepGraph::register_reused_dep_nodes`.
65 //
66 // FIXME: Enforce this by preventing manual construction of `DefNode`
67 // (e.g. add a `_priv: ()` field)
68 pub hash: PackedFingerprint,
ba9703b0
XL
69}
70
71impl<K: DepKind> DepNode<K> {
72 /// Creates a new, parameterless DepNode. This method will assert
73 /// that the DepNode corresponding to the given DepKind actually
74 /// does not require any parameters.
75 pub fn new_no_params(kind: K) -> DepNode<K> {
76 debug_assert!(!kind.has_params());
fc512014 77 DepNode { kind, hash: Fingerprint::ZERO.into() }
ba9703b0 78 }
f9f354fc
XL
79
80 pub fn construct<Ctxt, Key>(tcx: Ctxt, kind: K, arg: &Key) -> DepNode<K>
81 where
6a06907d 82 Ctxt: super::DepContext<DepKind = K>,
f9f354fc
XL
83 Key: DepNodeParams<Ctxt>,
84 {
85 let hash = arg.to_fingerprint(tcx);
fc512014 86 let dep_node = DepNode { kind, hash: hash.into() };
f9f354fc
XL
87
88 #[cfg(debug_assertions)]
89 {
6a06907d
XL
90 if !kind.can_reconstruct_query_key()
91 && (tcx.sess().opts.debugging_opts.incremental_info
92 || tcx.sess().opts.debugging_opts.query_dep_graph)
93 {
f9f354fc
XL
94 tcx.dep_graph().register_dep_node_debug_str(dep_node, || arg.to_debug_str(tcx));
95 }
96 }
97
98 dep_node
99 }
ba9703b0
XL
100}
101
102impl<K: DepKind> fmt::Debug for DepNode<K> {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 K::debug_node(self, f)
105 }
106}
107
108pub trait DepNodeParams<Ctxt: DepContext>: fmt::Debug + Sized {
f035d41b 109 fn can_reconstruct_query_key() -> bool;
ba9703b0
XL
110
111 /// This method turns the parameters of a DepNodeConstructor into an opaque
112 /// Fingerprint to be used in DepNode.
113 /// Not all DepNodeParams support being turned into a Fingerprint (they
114 /// don't need to if the corresponding DepNode is anonymous).
115 fn to_fingerprint(&self, _: Ctxt) -> Fingerprint {
116 panic!("Not implemented. Accidentally called on anonymous node?")
117 }
118
119 fn to_debug_str(&self, _: Ctxt) -> String {
120 format!("{:?}", self)
121 }
122
123 /// This method tries to recover the query key from the given `DepNode`,
124 /// something which is needed when forcing `DepNode`s during red-green
125 /// evaluation. The query system will only call this method if
f035d41b 126 /// `can_reconstruct_query_key()` is `true`.
ba9703b0
XL
127 /// It is always valid to return `None` here, in which case incremental
128 /// compilation will treat the query as having changed instead of forcing it.
129 fn recover(tcx: Ctxt, dep_node: &DepNode<Ctxt::DepKind>) -> Option<Self>;
130}
131
132impl<Ctxt: DepContext, T> DepNodeParams<Ctxt> for T
133where
134 T: HashStable<Ctxt::StableHashingContext> + fmt::Debug,
135{
f035d41b
XL
136 #[inline]
137 default fn can_reconstruct_query_key() -> bool {
138 false
139 }
ba9703b0
XL
140
141 default fn to_fingerprint(&self, tcx: Ctxt) -> Fingerprint {
142 let mut hcx = tcx.create_stable_hashing_context();
143 let mut hasher = StableHasher::new();
144
145 self.hash_stable(&mut hcx, &mut hasher);
146
147 hasher.finish()
148 }
149
150 default fn to_debug_str(&self, _: Ctxt) -> String {
151 format!("{:?}", *self)
152 }
153
154 default fn recover(_: Ctxt, _: &DepNode<Ctxt::DepKind>) -> Option<Self> {
155 None
156 }
157}
158
159/// A "work product" corresponds to a `.o` (or other) file that we
160/// save in between runs. These IDs do not have a `DefId` but rather
161/// some independent path or string that persists between runs without
162/// the need to be mapped or unmapped. (This ensures we can serialize
163/// them even in the absence of a tcx.)
3dfed10e
XL
164#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
165#[derive(Encodable, Decodable)]
ba9703b0
XL
166pub struct WorkProductId {
167 hash: Fingerprint,
168}
169
170impl WorkProductId {
171 pub fn from_cgu_name(cgu_name: &str) -> WorkProductId {
172 let mut hasher = StableHasher::new();
173 cgu_name.len().hash(&mut hasher);
174 cgu_name.hash(&mut hasher);
175 WorkProductId { hash: hasher.finish() }
176 }
ba9703b0
XL
177}
178
179impl<HCX> HashStable<HCX> for WorkProductId {
180 #[inline]
181 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
182 self.hash.hash_stable(hcx, hasher)
183 }
184}