]> git.lizzy.rs Git - rust.git/blob - src/librustc/dep_graph/dep_node.rs
4a763d4144edcbf8a044a2cc5a1b6e2ba9085241
[rust.git] / src / librustc / dep_graph / dep_node.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 //! This module defines the `DepNode` type which the compiler uses to represent
13 //! nodes in the dependency graph. A `DepNode` consists of a `DepKind` (which
14 //! specifies the kind of thing it represents, like a piece of HIR, MIR, etc)
15 //! and a `Fingerprint`, a 128 bit hash value the exact meaning of which
16 //! depends on the node's `DepKind`. Together, the kind and the fingerprint
17 //! fully identify a dependency node, even across multiple compilation sessions.
18 //! In other words, the value of the fingerprint does not depend on anything
19 //! that is specific to a given compilation session, like an unpredictable
20 //! interning key (e.g. NodeId, DefId, Symbol) or the numeric value of a
21 //! pointer. The concept behind this could be compared to how git commit hashes
22 //! uniquely identify a given commit and has a few advantages:
23 //!
24 //! * A `DepNode` can simply be serialized to disk and loaded in another session
25 //!   without the need to do any "rebasing (like we have to do for Spans and
26 //!   NodeIds) or "retracing" like we had to do for `DefId` in earlier
27 //!   implementations of the dependency graph.
28 //! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to
29 //!   implement `Copy`, `Sync`, `Send`, `Freeze`, etc.
30 //! * Since we just have a bit pattern, `DepNode` can be mapped from disk into
31 //!   memory without any post-processing (e.g. "abomination-style" pointer
32 //!   reconstruction).
33 //! * Because a `DepNode` is self-contained, we can instantiate `DepNodes` that
34 //!   refer to things that do not exist anymore. In previous implementations
35 //!   `DepNode` contained a `DefId`. A `DepNode` referring to something that
36 //!   had been removed between the previous and the current compilation session
37 //!   could not be instantiated because the current compilation session
38 //!   contained no `DefId` for thing that had been removed.
39 //!
40 //! `DepNode` definition happens in the `define_dep_nodes!()` macro. This macro
41 //! defines the `DepKind` enum and a corresponding `DepConstructor` enum. The
42 //! `DepConstructor` enum links a `DepKind` to the parameters that are needed at
43 //! runtime in order to construct a valid `DepNode` fingerprint.
44 //!
45 //! Because the macro sees what parameters a given `DepKind` requires, it can
46 //! "infer" some properties for each kind of `DepNode`:
47 //!
48 //! * Whether a `DepNode` of a given kind has any parameters at all. Some
49 //!   `DepNode`s, like `Krate`, represent global concepts with only one value.
50 //! * Whether it is possible, in principle, to reconstruct a query key from a
51 //!   given `DepNode`. Many `DepKind`s only require a single `DefId` parameter,
52 //!   in which case it is possible to map the node's fingerprint back to the
53 //!   `DefId` it was computed from. In other cases, too much information gets
54 //!   lost during fingerprint computation.
55 //!
56 //! The `DepConstructor` enum, together with `DepNode::new()` ensures that only
57 //! valid `DepNode` instances can be constructed. For example, the API does not
58 //! allow for constructing parameterless `DepNode`s with anything other
59 //! than a zeroed out fingerprint. More generally speaking, it relieves the
60 //! user of the `DepNode` API of having to know how to compute the expected
61 //! fingerprint for a given set of node parameters.
62
63 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX};
64 use hir::map::DefPathHash;
65 use hir::{HirId, ItemLocalId};
66
67 use ich::Fingerprint;
68 use ty::{TyCtxt, Instance, InstanceDef, ParamEnv, ParamEnvAnd, PolyTraitRef, Ty};
69 use ty::subst::Substs;
70 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
71 use ich::StableHashingContext;
72 use std::fmt;
73 use std::hash::Hash;
74 use syntax_pos::symbol::InternedString;
75
76 // erase!() just makes tokens go away. It's used to specify which macro argument
77 // is repeated (i.e. which sub-expression of the macro we are in) but don't need
78 // to actually use any of the arguments.
79 macro_rules! erase {
80     ($x:tt) => ({})
81 }
82
83 macro_rules! is_anon_attr {
84     (anon) => (true);
85     ($attr:ident) => (false);
86 }
87
88 macro_rules! is_input_attr {
89     (input) => (true);
90     ($attr:ident) => (false);
91 }
92
93 macro_rules! is_eval_always_attr {
94     (eval_always) => (true);
95     ($attr:ident) => (false);
96 }
97
98 macro_rules! contains_anon_attr {
99     ($($attr:ident),*) => ({$(is_anon_attr!($attr) | )* false});
100 }
101
102 macro_rules! contains_input_attr {
103     ($($attr:ident),*) => ({$(is_input_attr!($attr) | )* false});
104 }
105
106 macro_rules! contains_eval_always_attr {
107     ($($attr:ident),*) => ({$(is_eval_always_attr!($attr) | )* false});
108 }
109
110 macro_rules! define_dep_nodes {
111     (<$tcx:tt>
112     $(
113         [$($attr:ident),* ]
114         $variant:ident $(( $($tuple_arg:tt),* ))*
115                        $({ $($struct_arg_name:ident : $struct_arg_ty:ty),* })*
116       ,)*
117     ) => (
118         #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
119                  RustcEncodable, RustcDecodable)]
120         pub enum DepKind {
121             $($variant),*
122         }
123
124         impl DepKind {
125             #[allow(unreachable_code)]
126             #[inline]
127             pub fn can_reconstruct_query_key<$tcx>(&self) -> bool {
128                 match *self {
129                     $(
130                         DepKind :: $variant => {
131                             if contains_anon_attr!($($attr),*) {
132                                 return false;
133                             }
134
135                             // tuple args
136                             $({
137                                 return <( $($tuple_arg,)* ) as DepNodeParams>
138                                     ::CAN_RECONSTRUCT_QUERY_KEY;
139                             })*
140
141                             // struct args
142                             $({
143
144                                 return <( $($struct_arg_ty,)* ) as DepNodeParams>
145                                     ::CAN_RECONSTRUCT_QUERY_KEY;
146                             })*
147
148                             true
149                         }
150                     )*
151                 }
152             }
153
154             #[inline]
155             pub fn is_anon(&self) -> bool {
156                 match *self {
157                     $(
158                         DepKind :: $variant => { contains_anon_attr!($($attr),*) }
159                     )*
160                 }
161             }
162
163             #[inline]
164             pub fn is_input(&self) -> bool {
165                 match *self {
166                     $(
167                         DepKind :: $variant => { contains_input_attr!($($attr),*) }
168                     )*
169                 }
170             }
171
172             #[inline]
173             pub fn is_eval_always(&self) -> bool {
174                 match *self {
175                     $(
176                         DepKind :: $variant => { contains_eval_always_attr!($($attr), *) }
177                     )*
178                 }
179             }
180
181             #[allow(unreachable_code)]
182             #[inline]
183             pub fn has_params(&self) -> bool {
184                 match *self {
185                     $(
186                         DepKind :: $variant => {
187                             // tuple args
188                             $({
189                                 $(erase!($tuple_arg);)*
190                                 return true;
191                             })*
192
193                             // struct args
194                             $({
195                                 $(erase!($struct_arg_name);)*
196                                 return true;
197                             })*
198
199                             false
200                         }
201                     )*
202                 }
203             }
204         }
205
206         pub enum DepConstructor<$tcx> {
207             $(
208                 $variant $(( $($tuple_arg),* ))*
209                          $({ $($struct_arg_name : $struct_arg_ty),* })*
210             ),*
211         }
212
213         #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
214                  RustcEncodable, RustcDecodable)]
215         pub struct DepNode {
216             pub kind: DepKind,
217             pub hash: Fingerprint,
218         }
219
220         impl DepNode {
221             #[allow(unreachable_code, non_snake_case)]
222             pub fn new<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
223                                        dep: DepConstructor<'gcx>)
224                                        -> DepNode
225                 where 'gcx: 'a + 'tcx,
226                       'tcx: 'a
227             {
228                 match dep {
229                     $(
230                         DepConstructor :: $variant $(( $($tuple_arg),* ))*
231                                                    $({ $($struct_arg_name),* })*
232                             =>
233                         {
234                             // tuple args
235                             $({
236                                 let tupled_args = ( $($tuple_arg,)* );
237                                 let hash = DepNodeParams::to_fingerprint(&tupled_args,
238                                                                          tcx);
239                                 let dep_node = DepNode {
240                                     kind: DepKind::$variant,
241                                     hash
242                                 };
243
244                                 if cfg!(debug_assertions) &&
245                                    !dep_node.kind.can_reconstruct_query_key() &&
246                                    (tcx.sess.opts.debugging_opts.incremental_info ||
247                                     tcx.sess.opts.debugging_opts.query_dep_graph)
248                                 {
249                                     tcx.dep_graph.register_dep_node_debug_str(dep_node, || {
250                                         tupled_args.to_debug_str(tcx)
251                                     });
252                                 }
253
254                                 return dep_node;
255                             })*
256
257                             // struct args
258                             $({
259                                 let tupled_args = ( $($struct_arg_name,)* );
260                                 let hash = DepNodeParams::to_fingerprint(&tupled_args,
261                                                                          tcx);
262                                 let dep_node = DepNode {
263                                     kind: DepKind::$variant,
264                                     hash
265                                 };
266
267                                 if cfg!(debug_assertions) &&
268                                    !dep_node.kind.can_reconstruct_query_key() &&
269                                    (tcx.sess.opts.debugging_opts.incremental_info ||
270                                     tcx.sess.opts.debugging_opts.query_dep_graph)
271                                 {
272                                     tcx.dep_graph.register_dep_node_debug_str(dep_node, || {
273                                         tupled_args.to_debug_str(tcx)
274                                     });
275                                 }
276
277                                 return dep_node;
278                             })*
279
280                             DepNode {
281                                 kind: DepKind::$variant,
282                                 hash: Fingerprint::zero(),
283                             }
284                         }
285                     )*
286                 }
287             }
288
289             /// Construct a DepNode from the given DepKind and DefPathHash. This
290             /// method will assert that the given DepKind actually requires a
291             /// single DefId/DefPathHash parameter.
292             #[inline]
293             pub fn from_def_path_hash(kind: DepKind,
294                                       def_path_hash: DefPathHash)
295                                       -> DepNode {
296                 assert!(kind.can_reconstruct_query_key() && kind.has_params());
297                 DepNode {
298                     kind,
299                     hash: def_path_hash.0,
300                 }
301             }
302
303             /// Create a new, parameterless DepNode. This method will assert
304             /// that the DepNode corresponding to the given DepKind actually
305             /// does not require any parameters.
306             #[inline]
307             pub fn new_no_params(kind: DepKind) -> DepNode {
308                 assert!(!kind.has_params());
309                 DepNode {
310                     kind,
311                     hash: Fingerprint::zero(),
312                 }
313             }
314
315             /// Extract the DefId corresponding to this DepNode. This will work
316             /// if two conditions are met:
317             ///
318             /// 1. The Fingerprint of the DepNode actually is a DefPathHash, and
319             /// 2. the item that the DefPath refers to exists in the current tcx.
320             ///
321             /// Condition (1) is determined by the DepKind variant of the
322             /// DepNode. Condition (2) might not be fulfilled if a DepNode
323             /// refers to something from the previous compilation session that
324             /// has been removed.
325             #[inline]
326             pub fn extract_def_id(&self, tcx: TyCtxt) -> Option<DefId> {
327                 if self.kind.can_reconstruct_query_key() {
328                     let def_path_hash = DefPathHash(self.hash);
329                     if let Some(ref def_path_map) = tcx.def_path_hash_to_def_id.as_ref() {
330                         def_path_map.get(&def_path_hash).cloned()
331                     } else {
332                        None
333                     }
334                 } else {
335                     None
336                 }
337             }
338
339             /// Used in testing
340             pub fn from_label_string(label: &str,
341                                      def_path_hash: DefPathHash)
342                                      -> Result<DepNode, ()> {
343                 let kind = match label {
344                     $(
345                         stringify!($variant) => DepKind::$variant,
346                     )*
347                     _ => return Err(()),
348                 };
349
350                 if !kind.can_reconstruct_query_key() {
351                     return Err(());
352                 }
353
354                 if kind.has_params() {
355                     Ok(def_path_hash.to_dep_node(kind))
356                 } else {
357                     Ok(DepNode::new_no_params(kind))
358                 }
359             }
360
361             /// Used in testing
362             pub fn has_label_string(label: &str) -> bool {
363                 match label {
364                     $(
365                         stringify!($variant) => true,
366                     )*
367                     _ => false,
368                 }
369             }
370         }
371
372         /// Contains variant => str representations for constructing
373         /// DepNode groups for tests.
374         #[allow(dead_code, non_upper_case_globals)]
375         pub mod label_strs {
376            $(
377                 pub const $variant: &'static str = stringify!($variant);
378             )*
379         }
380     );
381 }
382
383 impl fmt::Debug for DepNode {
384     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
385         write!(f, "{:?}", self.kind)?;
386
387         if !self.kind.has_params() && !self.kind.is_anon() {
388             return Ok(());
389         }
390
391         write!(f, "(")?;
392
393         ::ty::tls::with_opt(|opt_tcx| {
394             if let Some(tcx) = opt_tcx {
395                 if let Some(def_id) = self.extract_def_id(tcx) {
396                     write!(f, "{}", tcx.def_path_debug_str(def_id))?;
397                 } else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(*self) {
398                     write!(f, "{}", s)?;
399                 } else {
400                     write!(f, "{}", self.hash)?;
401                 }
402             } else {
403                 write!(f, "{}", self.hash)?;
404             }
405             Ok(())
406         })?;
407
408         write!(f, ")")
409     }
410 }
411
412
413 impl DefPathHash {
414     #[inline]
415     pub fn to_dep_node(self, kind: DepKind) -> DepNode {
416         DepNode::from_def_path_hash(kind, self)
417     }
418 }
419
420 impl DefId {
421     #[inline]
422     pub fn to_dep_node(self, tcx: TyCtxt, kind: DepKind) -> DepNode {
423         DepNode::from_def_path_hash(kind, tcx.def_path_hash(self))
424     }
425 }
426
427 impl DepKind {
428     #[inline]
429     pub fn fingerprint_needed_for_crate_hash(self) -> bool {
430         match self {
431             DepKind::HirBody |
432             DepKind::Krate => true,
433             _ => false,
434         }
435     }
436 }
437
438 define_dep_nodes!( <'tcx>
439     // Represents the `Krate` as a whole (the `hir::Krate` value) (as
440     // distinct from the krate module). This is basically a hash of
441     // the entire krate, so if you read from `Krate` (e.g., by calling
442     // `tcx.hir.krate()`), we will have to assume that any change
443     // means that you need to be recompiled. This is because the
444     // `Krate` value gives you access to all other items. To avoid
445     // this fate, do not call `tcx.hir.krate()`; instead, prefer
446     // wrappers like `tcx.visit_all_items_in_krate()`.  If there is no
447     // suitable wrapper, you can use `tcx.dep_graph.ignore()` to gain
448     // access to the krate, but you must remember to add suitable
449     // edges yourself for the individual items that you read.
450     [input] Krate,
451
452     // Represents the body of a function or method. The def-id is that of the
453     // function/method.
454     [input] HirBody(DefId),
455
456     // Represents the HIR node with the given node-id
457     [input] Hir(DefId),
458
459     // Represents metadata from an extern crate.
460     [input] CrateMetadata(CrateNum),
461
462     // Represents some artifact that we save to disk. Note that these
463     // do not have a def-id as part of their identifier.
464     [] WorkProduct(WorkProductId),
465
466     // Represents different phases in the compiler.
467     [] RegionScopeTree(DefId),
468     [eval_always] Coherence,
469     [eval_always] CoherenceInherentImplOverlapCheck,
470     [] CoherenceCheckTrait(DefId),
471     [eval_always] PrivacyAccessLevels(CrateNum),
472
473     // Represents the MIR for a fn; also used as the task node for
474     // things read/modify that MIR.
475     [] MirConstQualif(DefId),
476     [] MirConst(DefId),
477     [] MirValidated(DefId),
478     [] MirOptimized(DefId),
479     [] MirShim { instance_def: InstanceDef<'tcx> },
480
481     [] BorrowCheckKrate,
482     [] BorrowCheck(DefId),
483     [] MirBorrowCheck(DefId),
484     [] UnsafetyViolations(DefId),
485
486     [] Reachability,
487     [] MirKeys,
488     [eval_always] CrateVariances,
489
490     // Nodes representing bits of computed IR in the tcx. Each shared
491     // table in the tcx (or elsewhere) maps to one of these
492     // nodes.
493     [] AssociatedItems(DefId),
494     [] TypeOfItem(DefId),
495     [] GenericsOfItem(DefId),
496     [] PredicatesOfItem(DefId),
497     [] InferredOutlivesOf(DefId),
498     [] SuperPredicatesOfItem(DefId),
499     [] TraitDefOfItem(DefId),
500     [] AdtDefOfItem(DefId),
501     [] IsDefaultImpl(DefId),
502     [] ImplTraitRef(DefId),
503     [] ImplPolarity(DefId),
504     [] ClosureKind(DefId),
505     [] FnSignature(DefId),
506     [] GenSignature(DefId),
507     [] CoerceUnsizedInfo(DefId),
508
509     [] ItemVarianceConstraints(DefId),
510     [] ItemVariances(DefId),
511     [] IsConstFn(DefId),
512     [] IsForeignItem(DefId),
513     [] TypeParamPredicates { item_id: DefId, param_id: DefId },
514     [] SizedConstraint(DefId),
515     [] DtorckConstraint(DefId),
516     [] AdtDestructor(DefId),
517     [] AssociatedItemDefIds(DefId),
518     [eval_always] InherentImpls(DefId),
519     [] TypeckBodiesKrate,
520     [] TypeckTables(DefId),
521     [] UsedTraitImports(DefId),
522     [] HasTypeckTables(DefId),
523     [] ConstEval { param_env: ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)> },
524     [] SymbolName(DefId),
525     [] InstanceSymbolName { instance: Instance<'tcx> },
526     [] SpecializationGraph(DefId),
527     [] ObjectSafety(DefId),
528     [] FulfillObligation { param_env: ParamEnv<'tcx>, trait_ref: PolyTraitRef<'tcx> },
529     [] VtableMethods { trait_ref: PolyTraitRef<'tcx> },
530
531     [] IsCopy { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
532     [] IsSized { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
533     [] IsFreeze { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
534     [] NeedsDrop { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
535     [] Layout { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
536
537     // The set of impls for a given trait.
538     [] TraitImpls(DefId),
539
540     [] AllLocalTraitImpls,
541
542     // Trait selection cache is a little funny. Given a trait
543     // reference like `Foo: SomeTrait<Bar>`, there could be
544     // arbitrarily many def-ids to map on in there (e.g., `Foo`,
545     // `SomeTrait`, `Bar`). We could have a vector of them, but it
546     // requires heap-allocation, and trait sel in general can be a
547     // surprisingly hot path. So instead we pick two def-ids: the
548     // trait def-id, and the first def-id in the input types. If there
549     // is no def-id in the input types, then we use the trait def-id
550     // again. So for example:
551     //
552     // - `i32: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Clone }`
553     // - `u32: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Clone }`
554     // - `Clone: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Clone }`
555     // - `Vec<i32>: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Vec }`
556     // - `String: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: String }`
557     // - `Foo: Trait<Bar>` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
558     // - `Foo: Trait<i32>` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
559     // - `(Foo, Bar): Trait` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
560     // - `i32: Trait<Foo>` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
561     //
562     // You can see that we map many trait refs to the same
563     // trait-select node.  This is not a problem, it just means
564     // imprecision in our dep-graph tracking.  The important thing is
565     // that for any given trait-ref, we always map to the **same**
566     // trait-select node.
567     [anon] TraitSelect,
568
569     [] ParamEnv(DefId),
570     [] DescribeDef(DefId),
571     [] DefSpan(DefId),
572     [] LookupStability(DefId),
573     [] LookupDeprecationEntry(DefId),
574     [] ItemBodyNestedBodies(DefId),
575     [] ConstIsRvaluePromotableToStatic(DefId),
576     [] RvaluePromotableMap(DefId),
577     [] ImplParent(DefId),
578     [] TraitOfItem(DefId),
579     [] IsExportedSymbol(DefId),
580     [] IsMirAvailable(DefId),
581     [] ItemAttrs(DefId),
582     [] FnArgNames(DefId),
583     [] DylibDepFormats(CrateNum),
584     [] IsPanicRuntime(CrateNum),
585     [] IsCompilerBuiltins(CrateNum),
586     [] HasGlobalAllocator(CrateNum),
587     [] ExternCrate(DefId),
588     [eval_always] LintLevels,
589     [] Specializes { impl1: DefId, impl2: DefId },
590     [input] InScopeTraits(DefIndex),
591     [] ModuleExports(DefId),
592     [] IsSanitizerRuntime(CrateNum),
593     [] IsProfilerRuntime(CrateNum),
594     [] GetPanicStrategy(CrateNum),
595     [] IsNoBuiltins(CrateNum),
596     [] ImplDefaultness(DefId),
597     [] ExportedSymbolIds(CrateNum),
598     [] NativeLibraries(CrateNum),
599     [] PluginRegistrarFn(CrateNum),
600     [] DeriveRegistrarFn(CrateNum),
601     [] CrateDisambiguator(CrateNum),
602     [] CrateHash(CrateNum),
603     [] OriginalCrateName(CrateNum),
604
605     [] ImplementationsOfTrait { krate: CrateNum, trait_id: DefId },
606     [] AllTraitImplementations(CrateNum),
607
608     [] IsDllimportForeignItem(DefId),
609     [] IsStaticallyIncludedForeignItem(DefId),
610     [] NativeLibraryKind(DefId),
611     [] LinkArgs,
612
613     [] NamedRegion(DefIndex),
614     [] IsLateBound(DefIndex),
615     [] ObjectLifetimeDefaults(DefIndex),
616
617     [] Visibility(DefId),
618     [] DepKind(CrateNum),
619     [] CrateName(CrateNum),
620     [] ItemChildren(DefId),
621     [] ExternModStmtCnum(DefId),
622     [] GetLangItems,
623     [] DefinedLangItems(CrateNum),
624     [] MissingLangItems(CrateNum),
625     [] ExternConstBody(DefId),
626     [] VisibleParentMap,
627     [] MissingExternCrateItem(CrateNum),
628     [] UsedCrateSource(CrateNum),
629     [] PostorderCnums,
630     [] HasCloneClosures(CrateNum),
631     [] HasCopyClosures(CrateNum),
632
633     // This query is not expected to have inputs -- as a result, it's
634     // not a good candidate for "replay" because it's essentially a
635     // pure function of its input (and hence the expectation is that
636     // no caller would be green **apart** from just this
637     // query). Making it anonymous avoids hashing the result, which
638     // may save a bit of time.
639     [anon] EraseRegionsTy { ty: Ty<'tcx> },
640
641     [] Freevars(DefId),
642     [] MaybeUnusedTraitImport(DefId),
643     [] MaybeUnusedExternCrates,
644     [] StabilityIndex,
645     [] AllCrateNums,
646     [] ExportedSymbols(CrateNum),
647     [eval_always] CollectAndPartitionTranslationItems,
648     [] ExportName(DefId),
649     [] ContainsExternIndicator(DefId),
650     [] IsTranslatedFunction(DefId),
651     [] CodegenUnit(InternedString),
652     [] CompileCodegenUnit(InternedString),
653     [] OutputFilenames,
654     [anon] NormalizeTy,
655     // We use this for most things when incr. comp. is turned off.
656     [] Null,
657 );
658
659 trait DepNodeParams<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> : fmt::Debug {
660     const CAN_RECONSTRUCT_QUERY_KEY: bool;
661
662     /// This method turns the parameters of a DepNodeConstructor into an opaque
663     /// Fingerprint to be used in DepNode.
664     /// Not all DepNodeParams support being turned into a Fingerprint (they
665     /// don't need to if the corresponding DepNode is anonymous).
666     fn to_fingerprint(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
667         panic!("Not implemented. Accidentally called on anonymous node?")
668     }
669
670     fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
671         format!("{:?}", self)
672     }
673 }
674
675 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a, T> DepNodeParams<'a, 'gcx, 'tcx> for T
676     where T: HashStable<StableHashingContext<'gcx>> + fmt::Debug
677 {
678     default const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
679
680     default fn to_fingerprint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
681         let mut hcx = tcx.create_stable_hashing_context();
682         let mut hasher = StableHasher::new();
683
684         self.hash_stable(&mut hcx, &mut hasher);
685
686         hasher.finish()
687     }
688
689     default fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
690         format!("{:?}", *self)
691     }
692 }
693
694 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (DefId,) {
695     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
696
697     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
698         tcx.def_path_hash(self.0).0
699     }
700
701     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
702         tcx.item_path_str(self.0)
703     }
704 }
705
706 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (DefIndex,) {
707     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
708
709     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
710         tcx.hir.definitions().def_path_hash(self.0).0
711     }
712
713     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
714         tcx.item_path_str(DefId::local(self.0))
715     }
716 }
717
718 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (CrateNum,) {
719     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
720
721     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
722         let def_id = DefId {
723             krate: self.0,
724             index: CRATE_DEF_INDEX,
725         };
726         tcx.def_path_hash(def_id).0
727     }
728
729     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
730         tcx.crate_name(self.0).as_str().to_string()
731     }
732 }
733
734 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (DefId, DefId) {
735     const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
736
737     // We actually would not need to specialize the implementation of this
738     // method but it's faster to combine the hashes than to instantiate a full
739     // hashing context and stable-hashing state.
740     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
741         let (def_id_0, def_id_1) = *self;
742
743         let def_path_hash_0 = tcx.def_path_hash(def_id_0);
744         let def_path_hash_1 = tcx.def_path_hash(def_id_1);
745
746         def_path_hash_0.0.combine(def_path_hash_1.0)
747     }
748
749     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
750         let (def_id_0, def_id_1) = *self;
751
752         format!("({}, {})",
753                 tcx.def_path_debug_str(def_id_0),
754                 tcx.def_path_debug_str(def_id_1))
755     }
756 }
757
758 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (HirId,) {
759     const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
760
761     // We actually would not need to specialize the implementation of this
762     // method but it's faster to combine the hashes than to instantiate a full
763     // hashing context and stable-hashing state.
764     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
765         let (HirId {
766             owner,
767             local_id: ItemLocalId(local_id),
768         },) = *self;
769
770         let def_path_hash = tcx.def_path_hash(DefId::local(owner));
771         let local_id = Fingerprint::from_smaller_hash(local_id as u64);
772
773         def_path_hash.0.combine(local_id)
774     }
775 }
776
777 /// A "work product" corresponds to a `.o` (or other) file that we
778 /// save in between runs. These ids do not have a DefId but rather
779 /// some independent path or string that persists between runs without
780 /// the need to be mapped or unmapped. (This ensures we can serialize
781 /// them even in the absence of a tcx.)
782 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
783          RustcEncodable, RustcDecodable)]
784 pub struct WorkProductId {
785     hash: Fingerprint
786 }
787
788 impl WorkProductId {
789     pub fn from_cgu_name(cgu_name: &str) -> WorkProductId {
790         let mut hasher = StableHasher::new();
791         cgu_name.len().hash(&mut hasher);
792         cgu_name.hash(&mut hasher);
793         WorkProductId {
794             hash: hasher.finish()
795         }
796     }
797
798     pub fn from_fingerprint(fingerprint: Fingerprint) -> WorkProductId {
799         WorkProductId {
800             hash: fingerprint
801         }
802     }
803
804     pub fn to_dep_node(self) -> DepNode {
805         DepNode {
806             kind: DepKind::WorkProduct,
807             hash: self.hash,
808         }
809     }
810 }
811
812 impl_stable_hash_for!(struct ::dep_graph::WorkProductId {
813     hash
814 });
815