]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_query_system/src/dep_graph/dep_node.rs
Merge 'rust-clippy/master' into clippyup
[rust.git] / compiler / rustc_query_system / src / dep_graph / dep_node.rs
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 `rustc_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
45 use super::{DepContext, DepKind, FingerprintStyle};
46 use crate::ich::StableHashingContext;
47
48 use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
49 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
50 use std::fmt;
51 use std::hash::Hash;
52
53 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
54 pub struct DepNode<K> {
55     pub kind: K,
56     pub hash: PackedFingerprint,
57 }
58
59 impl<K: DepKind> DepNode<K> {
60     /// Creates a new, parameterless DepNode. This method will assert
61     /// that the DepNode corresponding to the given DepKind actually
62     /// does not require any parameters.
63     pub fn new_no_params<Ctxt>(tcx: Ctxt, kind: K) -> DepNode<K>
64     where
65         Ctxt: super::DepContext<DepKind = K>,
66     {
67         debug_assert_eq!(tcx.fingerprint_style(kind), FingerprintStyle::Unit);
68         DepNode { kind, hash: Fingerprint::ZERO.into() }
69     }
70
71     pub fn construct<Ctxt, Key>(tcx: Ctxt, kind: K, arg: &Key) -> DepNode<K>
72     where
73         Ctxt: super::DepContext<DepKind = K>,
74         Key: DepNodeParams<Ctxt>,
75     {
76         let hash = arg.to_fingerprint(tcx);
77         let dep_node = DepNode { kind, hash: hash.into() };
78
79         #[cfg(debug_assertions)]
80         {
81             if !tcx.fingerprint_style(kind).reconstructible()
82                 && (tcx.sess().opts.debugging_opts.incremental_info
83                     || tcx.sess().opts.debugging_opts.query_dep_graph)
84             {
85                 tcx.dep_graph().register_dep_node_debug_str(dep_node, || arg.to_debug_str(tcx));
86             }
87         }
88
89         dep_node
90     }
91 }
92
93 impl<K: DepKind> fmt::Debug for DepNode<K> {
94     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95         K::debug_node(self, f)
96     }
97 }
98
99 pub trait DepNodeParams<Ctxt: DepContext>: fmt::Debug + Sized {
100     fn fingerprint_style() -> FingerprintStyle;
101
102     /// This method turns the parameters of a DepNodeConstructor into an opaque
103     /// Fingerprint to be used in DepNode.
104     /// Not all DepNodeParams support being turned into a Fingerprint (they
105     /// don't need to if the corresponding DepNode is anonymous).
106     fn to_fingerprint(&self, _: Ctxt) -> Fingerprint {
107         panic!("Not implemented. Accidentally called on anonymous node?")
108     }
109
110     fn to_debug_str(&self, _: Ctxt) -> String {
111         format!("{:?}", self)
112     }
113
114     /// This method tries to recover the query key from the given `DepNode`,
115     /// something which is needed when forcing `DepNode`s during red-green
116     /// evaluation. The query system will only call this method if
117     /// `fingerprint_style()` is not `FingerprintStyle::Opaque`.
118     /// It is always valid to return `None` here, in which case incremental
119     /// compilation will treat the query as having changed instead of forcing it.
120     fn recover(tcx: Ctxt, dep_node: &DepNode<Ctxt::DepKind>) -> Option<Self>;
121 }
122
123 impl<Ctxt: DepContext, T> DepNodeParams<Ctxt> for T
124 where
125     T: for<'a> HashStable<StableHashingContext<'a>> + fmt::Debug,
126 {
127     #[inline(always)]
128     default fn fingerprint_style() -> FingerprintStyle {
129         FingerprintStyle::Opaque
130     }
131
132     #[inline(always)]
133     default fn to_fingerprint(&self, tcx: Ctxt) -> Fingerprint {
134         let mut hcx = tcx.create_stable_hashing_context();
135         let mut hasher = StableHasher::new();
136
137         self.hash_stable(&mut hcx, &mut hasher);
138
139         hasher.finish()
140     }
141
142     #[inline(always)]
143     default fn to_debug_str(&self, _: Ctxt) -> String {
144         format!("{:?}", *self)
145     }
146
147     #[inline(always)]
148     default fn recover(_: Ctxt, _: &DepNode<Ctxt::DepKind>) -> Option<Self> {
149         None
150     }
151 }
152
153 /// A "work product" corresponds to a `.o` (or other) file that we
154 /// save in between runs. These IDs do not have a `DefId` but rather
155 /// some independent path or string that persists between runs without
156 /// the need to be mapped or unmapped. (This ensures we can serialize
157 /// them even in the absence of a tcx.)
158 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
159 #[derive(Encodable, Decodable)]
160 pub struct WorkProductId {
161     hash: Fingerprint,
162 }
163
164 impl WorkProductId {
165     pub fn from_cgu_name(cgu_name: &str) -> WorkProductId {
166         let mut hasher = StableHasher::new();
167         cgu_name.len().hash(&mut hasher);
168         cgu_name.hash(&mut hasher);
169         WorkProductId { hash: hasher.finish() }
170     }
171 }
172
173 impl<HCX> HashStable<HCX> for WorkProductId {
174     #[inline]
175     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
176         self.hash.hash_stable(hcx, hasher)
177     }
178 }