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