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