]> git.lizzy.rs Git - rust.git/blob - src/librustc_query_system/dep_graph/graph.rs
7352551559cf4835c4eb32288b51d4e114ac5e8f
[rust.git] / src / librustc_query_system / dep_graph / graph.rs
1 use rustc_data_structures::fingerprint::Fingerprint;
2 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
3 use rustc_data_structures::profiling::QueryInvocationId;
4 use rustc_data_structures::sharded::{self, Sharded};
5 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 use rustc_data_structures::sync::{AtomicU32, AtomicU64, Lock, Lrc, Ordering};
7 use rustc_data_structures::unlikely;
8 use rustc_errors::Diagnostic;
9 use rustc_index::vec::{Idx, IndexVec};
10
11 use parking_lot::{Condvar, Mutex};
12 use smallvec::{smallvec, SmallVec};
13 use std::collections::hash_map::Entry;
14 use std::env;
15 use std::hash::Hash;
16 use std::marker::PhantomData;
17 use std::mem;
18 use std::sync::atomic::Ordering::Relaxed;
19
20 use super::debug::EdgeFilter;
21 use super::prev::PreviousDepGraph;
22 use super::query::DepGraphQuery;
23 use super::safe::DepGraphSafe;
24 use super::serialized::{SerializedDepGraph, SerializedDepNodeIndex};
25 use super::{DepContext, DepKind, DepNode, WorkProductId};
26 use crate::{HashStableContext, HashStableContextProvider};
27
28 #[derive(Clone)]
29 pub struct DepGraph<K: DepKind> {
30     data: Option<Lrc<DepGraphData<K>>>,
31
32     /// This field is used for assigning DepNodeIndices when running in
33     /// non-incremental mode. Even in non-incremental mode we make sure that
34     /// each task has a `DepNodeIndex` that uniquely identifies it. This unique
35     /// ID is used for self-profiling.
36     virtual_dep_node_index: Lrc<AtomicU32>,
37 }
38
39 rustc_index::newtype_index! {
40     pub struct DepNodeIndex { .. }
41 }
42
43 impl DepNodeIndex {
44     pub const INVALID: DepNodeIndex = DepNodeIndex::MAX;
45 }
46
47 impl std::convert::From<DepNodeIndex> for QueryInvocationId {
48     #[inline]
49     fn from(dep_node_index: DepNodeIndex) -> Self {
50         QueryInvocationId(dep_node_index.as_u32())
51     }
52 }
53
54 #[derive(PartialEq)]
55 pub enum DepNodeColor {
56     Red,
57     Green(DepNodeIndex),
58 }
59
60 impl DepNodeColor {
61     pub fn is_green(self) -> bool {
62         match self {
63             DepNodeColor::Red => false,
64             DepNodeColor::Green(_) => true,
65         }
66     }
67 }
68
69 struct DepGraphData<K: DepKind> {
70     /// The new encoding of the dependency graph, optimized for red/green
71     /// tracking. The `current` field is the dependency graph of only the
72     /// current compilation session: We don't merge the previous dep-graph into
73     /// current one anymore.
74     current: CurrentDepGraph<K>,
75
76     /// The dep-graph from the previous compilation session. It contains all
77     /// nodes and edges as well as all fingerprints of nodes that have them.
78     previous: PreviousDepGraph<K>,
79
80     colors: DepNodeColorMap,
81
82     /// A set of loaded diagnostics that is in the progress of being emitted.
83     emitting_diagnostics: Mutex<FxHashSet<DepNodeIndex>>,
84
85     /// Used to wait for diagnostics to be emitted.
86     emitting_diagnostics_cond_var: Condvar,
87
88     /// When we load, there may be `.o` files, cached MIR, or other such
89     /// things available to us. If we find that they are not dirty, we
90     /// load the path to the file storing those work-products here into
91     /// this map. We can later look for and extract that data.
92     previous_work_products: FxHashMap<WorkProductId, WorkProduct>,
93
94     dep_node_debug: Lock<FxHashMap<DepNode<K>, String>>,
95 }
96
97 pub fn hash_result<HashCtxt, R>(hcx: &mut HashCtxt, result: &R) -> Option<Fingerprint>
98 where
99     R: HashStable<HashCtxt>,
100 {
101     let mut stable_hasher = StableHasher::new();
102     result.hash_stable(hcx, &mut stable_hasher);
103
104     Some(stable_hasher.finish())
105 }
106
107 impl<K: DepKind> DepGraph<K> {
108     pub fn new(
109         prev_graph: PreviousDepGraph<K>,
110         prev_work_products: FxHashMap<WorkProductId, WorkProduct>,
111     ) -> DepGraph<K> {
112         let prev_graph_node_count = prev_graph.node_count();
113
114         DepGraph {
115             data: Some(Lrc::new(DepGraphData {
116                 previous_work_products: prev_work_products,
117                 dep_node_debug: Default::default(),
118                 current: CurrentDepGraph::new(prev_graph_node_count),
119                 emitting_diagnostics: Default::default(),
120                 emitting_diagnostics_cond_var: Condvar::new(),
121                 previous: prev_graph,
122                 colors: DepNodeColorMap::new(prev_graph_node_count),
123             })),
124             virtual_dep_node_index: Lrc::new(AtomicU32::new(0)),
125         }
126     }
127
128     pub fn new_disabled() -> DepGraph<K> {
129         DepGraph { data: None, virtual_dep_node_index: Lrc::new(AtomicU32::new(0)) }
130     }
131
132     /// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
133     #[inline]
134     pub fn is_fully_enabled(&self) -> bool {
135         self.data.is_some()
136     }
137
138     pub fn query(&self) -> DepGraphQuery<K> {
139         let data = self.data.as_ref().unwrap().current.data.lock();
140         let nodes: Vec<_> = data.iter().map(|n| n.node).collect();
141         let mut edges = Vec::new();
142         for (from, edge_targets) in data.iter().map(|d| (d.node, &d.edges)) {
143             for &edge_target in edge_targets.iter() {
144                 let to = data[edge_target].node;
145                 edges.push((from, to));
146             }
147         }
148
149         DepGraphQuery::new(&nodes[..], &edges[..])
150     }
151
152     pub fn assert_ignored(&self) {
153         if let Some(..) = self.data {
154             K::read_deps(|task_deps| {
155                 assert!(task_deps.is_none(), "expected no task dependency tracking");
156             })
157         }
158     }
159
160     pub fn with_ignore<OP, R>(&self, op: OP) -> R
161     where
162         OP: FnOnce() -> R,
163     {
164         K::with_deps(None, op)
165     }
166
167     /// Starts a new dep-graph task. Dep-graph tasks are specified
168     /// using a free function (`task`) and **not** a closure -- this
169     /// is intentional because we want to exercise tight control over
170     /// what state they have access to. In particular, we want to
171     /// prevent implicit 'leaks' of tracked state into the task (which
172     /// could then be read without generating correct edges in the
173     /// dep-graph -- see the [rustc dev guide] for more details on
174     /// the dep-graph). To this end, the task function gets exactly two
175     /// pieces of state: the context `cx` and an argument `arg`. Both
176     /// of these bits of state must be of some type that implements
177     /// `DepGraphSafe` and hence does not leak.
178     ///
179     /// The choice of two arguments is not fundamental. One argument
180     /// would work just as well, since multiple values can be
181     /// collected using tuples. However, using two arguments works out
182     /// to be quite convenient, since it is common to need a context
183     /// (`cx`) and some argument (e.g., a `DefId` identifying what
184     /// item to process).
185     ///
186     /// For cases where you need some other number of arguments:
187     ///
188     /// - If you only need one argument, just use `()` for the `arg`
189     ///   parameter.
190     /// - If you need 3+ arguments, use a tuple for the
191     ///   `arg` parameter.
192     ///
193     /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/incremental-compilation.html
194     pub fn with_task<H, C, A, R>(
195         &self,
196         key: DepNode<K>,
197         cx: C,
198         arg: A,
199         task: fn(C, A) -> R,
200         hash_result: impl FnOnce(&mut H, &R) -> Option<Fingerprint>,
201     ) -> (R, DepNodeIndex)
202     where
203         C: DepGraphSafe + HashStableContextProvider<H>,
204         H: HashStableContext,
205     {
206         self.with_task_impl(
207             key,
208             cx,
209             arg,
210             false,
211             task,
212             |_key| {
213                 Some(TaskDeps {
214                     #[cfg(debug_assertions)]
215                     node: Some(_key),
216                     reads: SmallVec::new(),
217                     read_set: Default::default(),
218                     phantom_data: PhantomData,
219                 })
220             },
221             |data, key, fingerprint, task| data.complete_task(key, task.unwrap(), fingerprint),
222             hash_result,
223         )
224     }
225
226     fn with_task_impl<H, C, A, R>(
227         &self,
228         key: DepNode<K>,
229         cx: C,
230         arg: A,
231         no_tcx: bool,
232         task: fn(C, A) -> R,
233         create_task: fn(DepNode<K>) -> Option<TaskDeps<K>>,
234         finish_task_and_alloc_depnode: fn(
235             &CurrentDepGraph<K>,
236             DepNode<K>,
237             Fingerprint,
238             Option<TaskDeps<K>>,
239         ) -> DepNodeIndex,
240         hash_result: impl FnOnce(&mut H, &R) -> Option<Fingerprint>,
241     ) -> (R, DepNodeIndex)
242     where
243         C: DepGraphSafe + HashStableContextProvider<H>,
244         H: HashStableContext,
245     {
246         if let Some(ref data) = self.data {
247             let task_deps = create_task(key).map(Lock::new);
248
249             // In incremental mode, hash the result of the task. We don't
250             // do anything with the hash yet, but we are computing it
251             // anyway so that
252             //  - we make sure that the infrastructure works and
253             //  - we can get an idea of the runtime cost.
254             let mut hcx = cx.get_stable_hashing_context();
255
256             let result = if no_tcx {
257                 task(cx, arg)
258             } else {
259                 K::with_deps(task_deps.as_ref(), || task(cx, arg))
260             };
261
262             let current_fingerprint = hash_result(&mut hcx, &result);
263
264             let dep_node_index = finish_task_and_alloc_depnode(
265                 &data.current,
266                 key,
267                 current_fingerprint.unwrap_or(Fingerprint::ZERO),
268                 task_deps.map(|lock| lock.into_inner()),
269             );
270
271             let print_status = cfg!(debug_assertions) && hcx.debug_dep_tasks();
272
273             // Determine the color of the new DepNode.
274             if let Some(prev_index) = data.previous.node_to_index_opt(&key) {
275                 let prev_fingerprint = data.previous.fingerprint_by_index(prev_index);
276
277                 let color = if let Some(current_fingerprint) = current_fingerprint {
278                     if current_fingerprint == prev_fingerprint {
279                         if print_status {
280                             eprintln!("[task::green] {:?}", key);
281                         }
282                         DepNodeColor::Green(dep_node_index)
283                     } else {
284                         if print_status {
285                             eprintln!("[task::red] {:?}", key);
286                         }
287                         DepNodeColor::Red
288                     }
289                 } else {
290                     if print_status {
291                         eprintln!("[task::unknown] {:?}", key);
292                     }
293                     // Mark the node as Red if we can't hash the result
294                     DepNodeColor::Red
295                 };
296
297                 debug_assert!(
298                     data.colors.get(prev_index).is_none(),
299                     "DepGraph::with_task() - Duplicate DepNodeColor \
300                             insertion for {:?}",
301                     key
302                 );
303
304                 data.colors.insert(prev_index, color);
305             } else {
306                 if print_status {
307                     eprintln!("[task::new] {:?}", key);
308                 }
309             }
310
311             (result, dep_node_index)
312         } else {
313             (task(cx, arg), self.next_virtual_depnode_index())
314         }
315     }
316
317     /// Executes something within an "anonymous" task, that is, a task the
318     /// `DepNode` of which is determined by the list of inputs it read from.
319     pub fn with_anon_task<OP, R>(&self, dep_kind: K, op: OP) -> (R, DepNodeIndex)
320     where
321         OP: FnOnce() -> R,
322     {
323         if let Some(ref data) = self.data {
324             let task_deps = Lock::new(TaskDeps::default());
325
326             let result = K::with_deps(Some(&task_deps), op);
327             let task_deps = task_deps.into_inner();
328
329             let dep_node_index = data.current.complete_anon_task(dep_kind, task_deps);
330             (result, dep_node_index)
331         } else {
332             (op(), self.next_virtual_depnode_index())
333         }
334     }
335
336     /// Executes something within an "eval-always" task which is a task
337     /// that runs whenever anything changes.
338     pub fn with_eval_always_task<H, C, A, R>(
339         &self,
340         key: DepNode<K>,
341         cx: C,
342         arg: A,
343         task: fn(C, A) -> R,
344         hash_result: impl FnOnce(&mut H, &R) -> Option<Fingerprint>,
345     ) -> (R, DepNodeIndex)
346     where
347         C: DepGraphSafe + HashStableContextProvider<H>,
348         H: HashStableContext,
349     {
350         self.with_task_impl(
351             key,
352             cx,
353             arg,
354             false,
355             task,
356             |_| None,
357             |data, key, fingerprint, _| data.alloc_node(key, smallvec![], fingerprint),
358             hash_result,
359         )
360     }
361
362     #[inline]
363     pub fn read(&self, v: DepNode<K>) {
364         if let Some(ref data) = self.data {
365             let map = data.current.node_to_node_index.get_shard_by_value(&v).lock();
366             if let Some(dep_node_index) = map.get(&v).copied() {
367                 std::mem::drop(map);
368                 data.read_index(dep_node_index);
369             } else {
370                 panic!("DepKind {:?} should be pre-allocated but isn't.", v.kind)
371             }
372         }
373     }
374
375     #[inline]
376     pub fn read_index(&self, dep_node_index: DepNodeIndex) {
377         if let Some(ref data) = self.data {
378             data.read_index(dep_node_index);
379         }
380     }
381
382     #[inline]
383     pub fn dep_node_index_of(&self, dep_node: &DepNode<K>) -> DepNodeIndex {
384         self.data
385             .as_ref()
386             .unwrap()
387             .current
388             .node_to_node_index
389             .get_shard_by_value(dep_node)
390             .lock()
391             .get(dep_node)
392             .cloned()
393             .unwrap()
394     }
395
396     #[inline]
397     pub fn dep_node_exists(&self, dep_node: &DepNode<K>) -> bool {
398         if let Some(ref data) = self.data {
399             data.current
400                 .node_to_node_index
401                 .get_shard_by_value(&dep_node)
402                 .lock()
403                 .contains_key(dep_node)
404         } else {
405             false
406         }
407     }
408
409     #[inline]
410     pub fn fingerprint_of(&self, dep_node_index: DepNodeIndex) -> Fingerprint {
411         let data = self.data.as_ref().expect("dep graph enabled").current.data.lock();
412         data[dep_node_index].fingerprint
413     }
414
415     pub fn prev_fingerprint_of(&self, dep_node: &DepNode<K>) -> Option<Fingerprint> {
416         self.data.as_ref().unwrap().previous.fingerprint_of(dep_node)
417     }
418
419     #[inline]
420     pub fn prev_dep_node_index_of(&self, dep_node: &DepNode<K>) -> SerializedDepNodeIndex {
421         self.data.as_ref().unwrap().previous.node_to_index(dep_node)
422     }
423
424     /// Checks whether a previous work product exists for `v` and, if
425     /// so, return the path that leads to it. Used to skip doing work.
426     pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
427         self.data.as_ref().and_then(|data| data.previous_work_products.get(v).cloned())
428     }
429
430     /// Access the map of work-products created during the cached run. Only
431     /// used during saving of the dep-graph.
432     pub fn previous_work_products(&self) -> &FxHashMap<WorkProductId, WorkProduct> {
433         &self.data.as_ref().unwrap().previous_work_products
434     }
435
436     #[inline(always)]
437     pub fn register_dep_node_debug_str<F>(&self, dep_node: DepNode<K>, debug_str_gen: F)
438     where
439         F: FnOnce() -> String,
440     {
441         let dep_node_debug = &self.data.as_ref().unwrap().dep_node_debug;
442
443         if dep_node_debug.borrow().contains_key(&dep_node) {
444             return;
445         }
446         let debug_str = debug_str_gen();
447         dep_node_debug.borrow_mut().insert(dep_node, debug_str);
448     }
449
450     pub fn dep_node_debug_str(&self, dep_node: DepNode<K>) -> Option<String> {
451         self.data.as_ref()?.dep_node_debug.borrow().get(&dep_node).cloned()
452     }
453
454     pub fn edge_deduplication_data(&self) -> Option<(u64, u64)> {
455         if cfg!(debug_assertions) {
456             let current_dep_graph = &self.data.as_ref().unwrap().current;
457
458             Some((
459                 current_dep_graph.total_read_count.load(Relaxed),
460                 current_dep_graph.total_duplicate_read_count.load(Relaxed),
461             ))
462         } else {
463             None
464         }
465     }
466
467     pub fn serialize(&self) -> SerializedDepGraph<K> {
468         let data = self.data.as_ref().unwrap().current.data.lock();
469
470         let fingerprints: IndexVec<SerializedDepNodeIndex, _> =
471             data.iter().map(|d| d.fingerprint).collect();
472         let nodes: IndexVec<SerializedDepNodeIndex, _> = data.iter().map(|d| d.node).collect();
473
474         let total_edge_count: usize = data.iter().map(|d| d.edges.len()).sum();
475
476         let mut edge_list_indices = IndexVec::with_capacity(nodes.len());
477         let mut edge_list_data = Vec::with_capacity(total_edge_count);
478
479         for (current_dep_node_index, edges) in data.iter_enumerated().map(|(i, d)| (i, &d.edges)) {
480             let start = edge_list_data.len() as u32;
481             // This should really just be a memcpy :/
482             edge_list_data.extend(edges.iter().map(|i| SerializedDepNodeIndex::new(i.index())));
483             let end = edge_list_data.len() as u32;
484
485             debug_assert_eq!(current_dep_node_index.index(), edge_list_indices.len());
486             edge_list_indices.push((start, end));
487         }
488
489         debug_assert!(edge_list_data.len() <= u32::MAX as usize);
490         debug_assert_eq!(edge_list_data.len(), total_edge_count);
491
492         SerializedDepGraph { nodes, fingerprints, edge_list_indices, edge_list_data }
493     }
494
495     pub fn node_color(&self, dep_node: &DepNode<K>) -> Option<DepNodeColor> {
496         if let Some(ref data) = self.data {
497             if let Some(prev_index) = data.previous.node_to_index_opt(dep_node) {
498                 return data.colors.get(prev_index);
499             } else {
500                 // This is a node that did not exist in the previous compilation
501                 // session, so we consider it to be red.
502                 return Some(DepNodeColor::Red);
503             }
504         }
505
506         None
507     }
508
509     /// Try to read a node index for the node dep_node.
510     /// A node will have an index, when it's already been marked green, or when we can mark it
511     /// green. This function will mark the current task as a reader of the specified node, when
512     /// a node index can be found for that node.
513     pub fn try_mark_green_and_read<Ctxt: DepContext<DepKind = K>>(
514         &self,
515         tcx: Ctxt,
516         dep_node: &DepNode<K>,
517     ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
518         self.try_mark_green(tcx, dep_node).map(|(prev_index, dep_node_index)| {
519             debug_assert!(self.is_green(&dep_node));
520             self.read_index(dep_node_index);
521             (prev_index, dep_node_index)
522         })
523     }
524
525     pub fn try_mark_green<Ctxt: DepContext<DepKind = K>>(
526         &self,
527         tcx: Ctxt,
528         dep_node: &DepNode<K>,
529     ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
530         debug_assert!(!dep_node.kind.is_eval_always());
531
532         // Return None if the dep graph is disabled
533         let data = self.data.as_ref()?;
534
535         // Return None if the dep node didn't exist in the previous session
536         let prev_index = data.previous.node_to_index_opt(dep_node)?;
537
538         match data.colors.get(prev_index) {
539             Some(DepNodeColor::Green(dep_node_index)) => Some((prev_index, dep_node_index)),
540             Some(DepNodeColor::Red) => None,
541             None => {
542                 // This DepNode and the corresponding query invocation existed
543                 // in the previous compilation session too, so we can try to
544                 // mark it as green by recursively marking all of its
545                 // dependencies green.
546                 self.try_mark_previous_green(tcx, data, prev_index, &dep_node)
547                     .map(|dep_node_index| (prev_index, dep_node_index))
548             }
549         }
550     }
551
552     /// Try to mark a dep-node which existed in the previous compilation session as green.
553     fn try_mark_previous_green<Ctxt: DepContext<DepKind = K>>(
554         &self,
555         tcx: Ctxt,
556         data: &DepGraphData<K>,
557         prev_dep_node_index: SerializedDepNodeIndex,
558         dep_node: &DepNode<K>,
559     ) -> Option<DepNodeIndex> {
560         debug!("try_mark_previous_green({:?}) - BEGIN", dep_node);
561
562         #[cfg(not(parallel_compiler))]
563         {
564             debug_assert!(
565                 !data
566                     .current
567                     .node_to_node_index
568                     .get_shard_by_value(dep_node)
569                     .lock()
570                     .contains_key(dep_node)
571             );
572             debug_assert!(data.colors.get(prev_dep_node_index).is_none());
573         }
574
575         // We never try to mark eval_always nodes as green
576         debug_assert!(!dep_node.kind.is_eval_always());
577
578         debug_assert_eq!(data.previous.index_to_node(prev_dep_node_index), *dep_node);
579
580         let prev_deps = data.previous.edge_targets_from(prev_dep_node_index);
581
582         let mut current_deps = SmallVec::new();
583
584         for &dep_dep_node_index in prev_deps {
585             let dep_dep_node_color = data.colors.get(dep_dep_node_index);
586
587             match dep_dep_node_color {
588                 Some(DepNodeColor::Green(node_index)) => {
589                     // This dependency has been marked as green before, we are
590                     // still fine and can continue with checking the other
591                     // dependencies.
592                     debug!(
593                         "try_mark_previous_green({:?}) --- found dependency {:?} to \
594                             be immediately green",
595                         dep_node,
596                         data.previous.index_to_node(dep_dep_node_index)
597                     );
598                     current_deps.push(node_index);
599                 }
600                 Some(DepNodeColor::Red) => {
601                     // We found a dependency the value of which has changed
602                     // compared to the previous compilation session. We cannot
603                     // mark the DepNode as green and also don't need to bother
604                     // with checking any of the other dependencies.
605                     debug!(
606                         "try_mark_previous_green({:?}) - END - dependency {:?} was \
607                             immediately red",
608                         dep_node,
609                         data.previous.index_to_node(dep_dep_node_index)
610                     );
611                     return None;
612                 }
613                 None => {
614                     let dep_dep_node = &data.previous.index_to_node(dep_dep_node_index);
615
616                     // We don't know the state of this dependency. If it isn't
617                     // an eval_always node, let's try to mark it green recursively.
618                     if !dep_dep_node.kind.is_eval_always() {
619                         debug!(
620                             "try_mark_previous_green({:?}) --- state of dependency {:?} \
621                                  is unknown, trying to mark it green",
622                             dep_node, dep_dep_node
623                         );
624
625                         let node_index = self.try_mark_previous_green(
626                             tcx,
627                             data,
628                             dep_dep_node_index,
629                             dep_dep_node,
630                         );
631                         if let Some(node_index) = node_index {
632                             debug!(
633                                 "try_mark_previous_green({:?}) --- managed to MARK \
634                                     dependency {:?} as green",
635                                 dep_node, dep_dep_node
636                             );
637                             current_deps.push(node_index);
638                             continue;
639                         }
640                     }
641
642                     // We failed to mark it green, so we try to force the query.
643                     debug!(
644                         "try_mark_previous_green({:?}) --- trying to force \
645                             dependency {:?}",
646                         dep_node, dep_dep_node
647                     );
648                     if tcx.try_force_from_dep_node(dep_dep_node) {
649                         let dep_dep_node_color = data.colors.get(dep_dep_node_index);
650
651                         match dep_dep_node_color {
652                             Some(DepNodeColor::Green(node_index)) => {
653                                 debug!(
654                                     "try_mark_previous_green({:?}) --- managed to \
655                                         FORCE dependency {:?} to green",
656                                     dep_node, dep_dep_node
657                                 );
658                                 current_deps.push(node_index);
659                             }
660                             Some(DepNodeColor::Red) => {
661                                 debug!(
662                                     "try_mark_previous_green({:?}) - END - \
663                                         dependency {:?} was red after forcing",
664                                     dep_node, dep_dep_node
665                                 );
666                                 return None;
667                             }
668                             None => {
669                                 if !tcx.has_errors_or_delayed_span_bugs() {
670                                     panic!(
671                                         "try_mark_previous_green() - Forcing the DepNode \
672                                           should have set its color"
673                                     )
674                                 } else {
675                                     // If the query we just forced has resulted in
676                                     // some kind of compilation error, we cannot rely on
677                                     // the dep-node color having been properly updated.
678                                     // This means that the query system has reached an
679                                     // invalid state. We let the compiler continue (by
680                                     // returning `None`) so it can emit error messages
681                                     // and wind down, but rely on the fact that this
682                                     // invalid state will not be persisted to the
683                                     // incremental compilation cache because of
684                                     // compilation errors being present.
685                                     debug!(
686                                         "try_mark_previous_green({:?}) - END - \
687                                             dependency {:?} resulted in compilation error",
688                                         dep_node, dep_dep_node
689                                     );
690                                     return None;
691                                 }
692                             }
693                         }
694                     } else {
695                         // The DepNode could not be forced.
696                         debug!(
697                             "try_mark_previous_green({:?}) - END - dependency {:?} \
698                                 could not be forced",
699                             dep_node, dep_dep_node
700                         );
701                         return None;
702                     }
703                 }
704             }
705         }
706
707         // If we got here without hitting a `return` that means that all
708         // dependencies of this DepNode could be marked as green. Therefore we
709         // can also mark this DepNode as green.
710
711         // There may be multiple threads trying to mark the same dep node green concurrently
712
713         let dep_node_index = {
714             // Copy the fingerprint from the previous graph,
715             // so we don't have to recompute it
716             let fingerprint = data.previous.fingerprint_by_index(prev_dep_node_index);
717
718             // We allocating an entry for the node in the current dependency graph and
719             // adding all the appropriate edges imported from the previous graph
720             data.current.intern_node(*dep_node, current_deps, fingerprint)
721         };
722
723         // ... emitting any stored diagnostic ...
724
725         // FIXME: Store the fact that a node has diagnostics in a bit in the dep graph somewhere
726         // Maybe store a list on disk and encode this fact in the DepNodeState
727         let diagnostics = tcx.load_diagnostics(prev_dep_node_index);
728
729         #[cfg(not(parallel_compiler))]
730         debug_assert!(
731             data.colors.get(prev_dep_node_index).is_none(),
732             "DepGraph::try_mark_previous_green() - Duplicate DepNodeColor \
733                       insertion for {:?}",
734             dep_node
735         );
736
737         if unlikely!(!diagnostics.is_empty()) {
738             self.emit_diagnostics(tcx, data, dep_node_index, prev_dep_node_index, diagnostics);
739         }
740
741         // ... and finally storing a "Green" entry in the color map.
742         // Multiple threads can all write the same color here
743         data.colors.insert(prev_dep_node_index, DepNodeColor::Green(dep_node_index));
744
745         debug!("try_mark_previous_green({:?}) - END - successfully marked as green", dep_node);
746         Some(dep_node_index)
747     }
748
749     /// Atomically emits some loaded diagnostics.
750     /// This may be called concurrently on multiple threads for the same dep node.
751     #[cold]
752     #[inline(never)]
753     fn emit_diagnostics<Ctxt: DepContext<DepKind = K>>(
754         &self,
755         tcx: Ctxt,
756         data: &DepGraphData<K>,
757         dep_node_index: DepNodeIndex,
758         prev_dep_node_index: SerializedDepNodeIndex,
759         diagnostics: Vec<Diagnostic>,
760     ) {
761         let mut emitting = data.emitting_diagnostics.lock();
762
763         if data.colors.get(prev_dep_node_index) == Some(DepNodeColor::Green(dep_node_index)) {
764             // The node is already green so diagnostics must have been emitted already
765             return;
766         }
767
768         if emitting.insert(dep_node_index) {
769             // We were the first to insert the node in the set so this thread
770             // must emit the diagnostics and signal other potentially waiting
771             // threads after.
772             mem::drop(emitting);
773
774             // Promote the previous diagnostics to the current session.
775             tcx.store_diagnostics(dep_node_index, diagnostics.clone().into());
776
777             let handle = tcx.diagnostic();
778
779             for diagnostic in diagnostics {
780                 handle.emit_diagnostic(&diagnostic);
781             }
782
783             // Mark the node as green now that diagnostics are emitted
784             data.colors.insert(prev_dep_node_index, DepNodeColor::Green(dep_node_index));
785
786             // Remove the node from the set
787             data.emitting_diagnostics.lock().remove(&dep_node_index);
788
789             // Wake up waiters
790             data.emitting_diagnostics_cond_var.notify_all();
791         } else {
792             // We must wait for the other thread to finish emitting the diagnostic
793
794             loop {
795                 data.emitting_diagnostics_cond_var.wait(&mut emitting);
796                 if data.colors.get(prev_dep_node_index) == Some(DepNodeColor::Green(dep_node_index))
797                 {
798                     break;
799                 }
800             }
801         }
802     }
803
804     // Returns true if the given node has been marked as green during the
805     // current compilation session. Used in various assertions
806     pub fn is_green(&self, dep_node: &DepNode<K>) -> bool {
807         self.node_color(dep_node).map(|c| c.is_green()).unwrap_or(false)
808     }
809
810     // This method loads all on-disk cacheable query results into memory, so
811     // they can be written out to the new cache file again. Most query results
812     // will already be in memory but in the case where we marked something as
813     // green but then did not need the value, that value will never have been
814     // loaded from disk.
815     //
816     // This method will only load queries that will end up in the disk cache.
817     // Other queries will not be executed.
818     pub fn exec_cache_promotions<Ctxt: DepContext<DepKind = K>>(&self, tcx: Ctxt) {
819         let _prof_timer = tcx.profiler().generic_activity("incr_comp_query_cache_promotion");
820
821         let data = self.data.as_ref().unwrap();
822         for prev_index in data.colors.values.indices() {
823             match data.colors.get(prev_index) {
824                 Some(DepNodeColor::Green(_)) => {
825                     let dep_node = data.previous.index_to_node(prev_index);
826                     tcx.try_load_from_on_disk_cache(&dep_node);
827                 }
828                 None | Some(DepNodeColor::Red) => {
829                     // We can skip red nodes because a node can only be marked
830                     // as red if the query result was recomputed and thus is
831                     // already in memory.
832                 }
833             }
834         }
835     }
836
837     fn next_virtual_depnode_index(&self) -> DepNodeIndex {
838         let index = self.virtual_dep_node_index.fetch_add(1, Relaxed);
839         DepNodeIndex::from_u32(index)
840     }
841 }
842
843 /// A "work product" is an intermediate result that we save into the
844 /// incremental directory for later re-use. The primary example are
845 /// the object files that we save for each partition at code
846 /// generation time.
847 ///
848 /// Each work product is associated with a dep-node, representing the
849 /// process that produced the work-product. If that dep-node is found
850 /// to be dirty when we load up, then we will delete the work-product
851 /// at load time. If the work-product is found to be clean, then we
852 /// will keep a record in the `previous_work_products` list.
853 ///
854 /// In addition, work products have an associated hash. This hash is
855 /// an extra hash that can be used to decide if the work-product from
856 /// a previous compilation can be re-used (in addition to the dirty
857 /// edges check).
858 ///
859 /// As the primary example, consider the object files we generate for
860 /// each partition. In the first run, we create partitions based on
861 /// the symbols that need to be compiled. For each partition P, we
862 /// hash the symbols in P and create a `WorkProduct` record associated
863 /// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
864 /// in P.
865 ///
866 /// The next time we compile, if the `DepNode::CodegenUnit(P)` is
867 /// judged to be clean (which means none of the things we read to
868 /// generate the partition were found to be dirty), it will be loaded
869 /// into previous work products. We will then regenerate the set of
870 /// symbols in the partition P and hash them (note that new symbols
871 /// may be added -- for example, new monomorphizations -- even if
872 /// nothing in P changed!). We will compare that hash against the
873 /// previous hash. If it matches up, we can reuse the object file.
874 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
875 pub struct WorkProduct {
876     pub cgu_name: String,
877     /// Saved files associated with this CGU.
878     pub saved_files: Vec<(WorkProductFileKind, String)>,
879 }
880
881 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, PartialEq)]
882 pub enum WorkProductFileKind {
883     Object,
884     Bytecode,
885     BytecodeCompressed,
886 }
887
888 #[derive(Clone)]
889 struct DepNodeData<K> {
890     node: DepNode<K>,
891     edges: EdgesVec,
892     fingerprint: Fingerprint,
893 }
894
895 /// `CurrentDepGraph` stores the dependency graph for the current session.
896 /// It will be populated as we run queries or tasks.
897 ///
898 /// The nodes in it are identified by an index (`DepNodeIndex`).
899 /// The data for each node is stored in its `DepNodeData`, found in the `data` field.
900 ///
901 /// We never remove nodes from the graph: they are only added.
902 ///
903 /// This struct uses two locks internally. The `data` and `node_to_node_index` fields are
904 /// locked separately. Operations that take a `DepNodeIndex` typically just access
905 /// the data field.
906 ///
907 /// The only operation that must manipulate both locks is adding new nodes, in which case
908 /// we first acquire the `node_to_node_index` lock and then, once a new node is to be inserted,
909 /// acquire the lock on `data.`
910 pub(super) struct CurrentDepGraph<K> {
911     data: Lock<IndexVec<DepNodeIndex, DepNodeData<K>>>,
912     node_to_node_index: Sharded<FxHashMap<DepNode<K>, DepNodeIndex>>,
913
914     /// Used to trap when a specific edge is added to the graph.
915     /// This is used for debug purposes and is only active with `debug_assertions`.
916     #[allow(dead_code)]
917     forbidden_edge: Option<EdgeFilter>,
918
919     /// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
920     /// their edges. This has the beneficial side-effect that multiple anonymous
921     /// nodes can be coalesced into one without changing the semantics of the
922     /// dependency graph. However, the merging of nodes can lead to a subtle
923     /// problem during red-green marking: The color of an anonymous node from
924     /// the current session might "shadow" the color of the node with the same
925     /// ID from the previous session. In order to side-step this problem, we make
926     /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
927     /// This is implemented by mixing a session-key into the ID fingerprint of
928     /// each anon node. The session-key is just a random number generated when
929     /// the `DepGraph` is created.
930     anon_id_seed: Fingerprint,
931
932     /// These are simple counters that are for profiling and
933     /// debugging and only active with `debug_assertions`.
934     total_read_count: AtomicU64,
935     total_duplicate_read_count: AtomicU64,
936 }
937
938 impl<K: DepKind> CurrentDepGraph<K> {
939     fn new(prev_graph_node_count: usize) -> CurrentDepGraph<K> {
940         use std::time::{SystemTime, UNIX_EPOCH};
941
942         let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
943         let nanos = duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64;
944         let mut stable_hasher = StableHasher::new();
945         nanos.hash(&mut stable_hasher);
946
947         let forbidden_edge = if cfg!(debug_assertions) {
948             match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
949                 Ok(s) => match EdgeFilter::new(&s) {
950                     Ok(f) => Some(f),
951                     Err(err) => panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
952                 },
953                 Err(_) => None,
954             }
955         } else {
956             None
957         };
958
959         // Pre-allocate the dep node structures. We over-allocate a little so
960         // that we hopefully don't have to re-allocate during this compilation
961         // session. The over-allocation is 2% plus a small constant to account
962         // for the fact that in very small crates 2% might not be enough.
963         let new_node_count_estimate = (prev_graph_node_count * 102) / 100 + 200;
964
965         CurrentDepGraph {
966             data: Lock::new(IndexVec::with_capacity(new_node_count_estimate)),
967             node_to_node_index: Sharded::new(|| {
968                 FxHashMap::with_capacity_and_hasher(
969                     new_node_count_estimate / sharded::SHARDS,
970                     Default::default(),
971                 )
972             }),
973             anon_id_seed: stable_hasher.finish(),
974             forbidden_edge,
975             total_read_count: AtomicU64::new(0),
976             total_duplicate_read_count: AtomicU64::new(0),
977         }
978     }
979
980     fn complete_task(
981         &self,
982         node: DepNode<K>,
983         task_deps: TaskDeps<K>,
984         fingerprint: Fingerprint,
985     ) -> DepNodeIndex {
986         self.alloc_node(node, task_deps.reads, fingerprint)
987     }
988
989     fn complete_anon_task(&self, kind: K, task_deps: TaskDeps<K>) -> DepNodeIndex {
990         debug_assert!(!kind.is_eval_always());
991
992         let mut hasher = StableHasher::new();
993
994         // The dep node indices are hashed here instead of hashing the dep nodes of the
995         // dependencies. These indices may refer to different nodes per session, but this isn't
996         // a problem here because we that ensure the final dep node hash is per session only by
997         // combining it with the per session random number `anon_id_seed`. This hash only need
998         // to map the dependencies to a single value on a per session basis.
999         task_deps.reads.hash(&mut hasher);
1000
1001         let target_dep_node = DepNode {
1002             kind,
1003
1004             // Fingerprint::combine() is faster than sending Fingerprint
1005             // through the StableHasher (at least as long as StableHasher
1006             // is so slow).
1007             hash: self.anon_id_seed.combine(hasher.finish()),
1008         };
1009
1010         self.intern_node(target_dep_node, task_deps.reads, Fingerprint::ZERO)
1011     }
1012
1013     fn alloc_node(
1014         &self,
1015         dep_node: DepNode<K>,
1016         edges: EdgesVec,
1017         fingerprint: Fingerprint,
1018     ) -> DepNodeIndex {
1019         debug_assert!(
1020             !self.node_to_node_index.get_shard_by_value(&dep_node).lock().contains_key(&dep_node)
1021         );
1022         self.intern_node(dep_node, edges, fingerprint)
1023     }
1024
1025     fn intern_node(
1026         &self,
1027         dep_node: DepNode<K>,
1028         edges: EdgesVec,
1029         fingerprint: Fingerprint,
1030     ) -> DepNodeIndex {
1031         match self.node_to_node_index.get_shard_by_value(&dep_node).lock().entry(dep_node) {
1032             Entry::Occupied(entry) => *entry.get(),
1033             Entry::Vacant(entry) => {
1034                 let mut data = self.data.lock();
1035                 let dep_node_index = DepNodeIndex::new(data.len());
1036                 data.push(DepNodeData { node: dep_node, edges, fingerprint });
1037                 entry.insert(dep_node_index);
1038                 dep_node_index
1039             }
1040         }
1041     }
1042 }
1043
1044 impl<K: DepKind> DepGraphData<K> {
1045     #[inline(never)]
1046     fn read_index(&self, source: DepNodeIndex) {
1047         K::read_deps(|task_deps| {
1048             if let Some(task_deps) = task_deps {
1049                 let mut task_deps = task_deps.lock();
1050                 let task_deps = &mut *task_deps;
1051                 if cfg!(debug_assertions) {
1052                     self.current.total_read_count.fetch_add(1, Relaxed);
1053                 }
1054
1055                 // As long as we only have a low number of reads we can avoid doing a hash
1056                 // insert and potentially allocating/reallocating the hashmap
1057                 let new_read = if task_deps.reads.len() < TASK_DEPS_READS_CAP {
1058                     task_deps.reads.iter().all(|other| *other != source)
1059                 } else {
1060                     task_deps.read_set.insert(source)
1061                 };
1062                 if new_read {
1063                     task_deps.reads.push(source);
1064                     if task_deps.reads.len() == TASK_DEPS_READS_CAP {
1065                         // Fill `read_set` with what we have so far so we can use the hashset next
1066                         // time
1067                         task_deps.read_set.extend(task_deps.reads.iter().copied());
1068                     }
1069
1070                     #[cfg(debug_assertions)]
1071                     {
1072                         if let Some(target) = task_deps.node {
1073                             let data = self.current.data.lock();
1074                             if let Some(ref forbidden_edge) = self.current.forbidden_edge {
1075                                 let source = data[source].node;
1076                                 if forbidden_edge.test(&source, &target) {
1077                                     panic!("forbidden edge {:?} -> {:?} created", source, target)
1078                                 }
1079                             }
1080                         }
1081                     }
1082                 } else if cfg!(debug_assertions) {
1083                     self.current.total_duplicate_read_count.fetch_add(1, Relaxed);
1084                 }
1085             }
1086         })
1087     }
1088 }
1089
1090 /// The capacity of the `reads` field `SmallVec`
1091 const TASK_DEPS_READS_CAP: usize = 8;
1092 type EdgesVec = SmallVec<[DepNodeIndex; TASK_DEPS_READS_CAP]>;
1093
1094 pub struct TaskDeps<K> {
1095     #[cfg(debug_assertions)]
1096     node: Option<DepNode<K>>,
1097     reads: EdgesVec,
1098     read_set: FxHashSet<DepNodeIndex>,
1099     phantom_data: PhantomData<DepNode<K>>,
1100 }
1101
1102 impl<K> Default for TaskDeps<K> {
1103     fn default() -> Self {
1104         Self {
1105             #[cfg(debug_assertions)]
1106             node: None,
1107             reads: EdgesVec::new(),
1108             read_set: FxHashSet::default(),
1109             phantom_data: PhantomData,
1110         }
1111     }
1112 }
1113
1114 // A data structure that stores Option<DepNodeColor> values as a contiguous
1115 // array, using one u32 per entry.
1116 struct DepNodeColorMap {
1117     values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1118 }
1119
1120 const COMPRESSED_NONE: u32 = 0;
1121 const COMPRESSED_RED: u32 = 1;
1122 const COMPRESSED_FIRST_GREEN: u32 = 2;
1123
1124 impl DepNodeColorMap {
1125     fn new(size: usize) -> DepNodeColorMap {
1126         DepNodeColorMap { values: (0..size).map(|_| AtomicU32::new(COMPRESSED_NONE)).collect() }
1127     }
1128
1129     fn get(&self, index: SerializedDepNodeIndex) -> Option<DepNodeColor> {
1130         match self.values[index].load(Ordering::Acquire) {
1131             COMPRESSED_NONE => None,
1132             COMPRESSED_RED => Some(DepNodeColor::Red),
1133             value => {
1134                 Some(DepNodeColor::Green(DepNodeIndex::from_u32(value - COMPRESSED_FIRST_GREEN)))
1135             }
1136         }
1137     }
1138
1139     fn insert(&self, index: SerializedDepNodeIndex, color: DepNodeColor) {
1140         self.values[index].store(
1141             match color {
1142                 DepNodeColor::Red => COMPRESSED_RED,
1143                 DepNodeColor::Green(index) => index.as_u32() + COMPRESSED_FIRST_GREEN,
1144             },
1145             Ordering::Release,
1146         )
1147     }
1148 }