rustc_query_system/query/
job.rs

1use std::hash::Hash;
2use std::io::Write;
3use std::iter;
4use std::num::NonZero;
5use std::sync::Arc;
6
7use parking_lot::{Condvar, Mutex};
8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9use rustc_data_structures::jobserver;
10use rustc_errors::{Diag, DiagCtxtHandle};
11use rustc_hir::def::DefKind;
12use rustc_session::Session;
13use rustc_span::{DUMMY_SP, Span};
14
15use crate::dep_graph::DepContext;
16use crate::error::CycleStack;
17use crate::query::plumbing::CycleError;
18use crate::query::{QueryContext, QueryStackFrame};
19
20/// Represents a span and a query key.
21#[derive(Clone, Debug)]
22pub struct QueryInfo {
23    /// The span corresponding to the reason for which this query was required.
24    pub span: Span,
25    pub query: QueryStackFrame,
26}
27
28pub type QueryMap = FxHashMap<QueryJobId, QueryJobInfo>;
29
30/// A value uniquely identifying an active query job.
31#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
32pub struct QueryJobId(pub NonZero<u64>);
33
34impl QueryJobId {
35    fn query(self, map: &QueryMap) -> QueryStackFrame {
36        map.get(&self).unwrap().query.clone()
37    }
38
39    fn span(self, map: &QueryMap) -> Span {
40        map.get(&self).unwrap().job.span
41    }
42
43    fn parent(self, map: &QueryMap) -> Option<QueryJobId> {
44        map.get(&self).unwrap().job.parent
45    }
46
47    fn latch(self, map: &QueryMap) -> Option<&QueryLatch> {
48        map.get(&self).unwrap().job.latch.as_ref()
49    }
50}
51
52#[derive(Clone, Debug)]
53pub struct QueryJobInfo {
54    pub query: QueryStackFrame,
55    pub job: QueryJob,
56}
57
58/// Represents an active query job.
59#[derive(Clone, Debug)]
60pub struct QueryJob {
61    pub id: QueryJobId,
62
63    /// The span corresponding to the reason for which this query was required.
64    pub span: Span,
65
66    /// The parent query job which created this job and is implicitly waiting on it.
67    pub parent: Option<QueryJobId>,
68
69    /// The latch that is used to wait on this job.
70    latch: Option<QueryLatch>,
71}
72
73impl QueryJob {
74    /// Creates a new query job.
75    #[inline]
76    pub fn new(id: QueryJobId, span: Span, parent: Option<QueryJobId>) -> Self {
77        QueryJob { id, span, parent, latch: None }
78    }
79
80    pub(super) fn latch(&mut self) -> QueryLatch {
81        if self.latch.is_none() {
82            self.latch = Some(QueryLatch::new());
83        }
84        self.latch.as_ref().unwrap().clone()
85    }
86
87    /// Signals to waiters that the query is complete.
88    ///
89    /// This does nothing for single threaded rustc,
90    /// as there are no concurrent jobs which could be waiting on us
91    #[inline]
92    pub fn signal_complete(self) {
93        if let Some(latch) = self.latch {
94            latch.set();
95        }
96    }
97}
98
99impl QueryJobId {
100    pub(super) fn find_cycle_in_stack(
101        &self,
102        query_map: QueryMap,
103        current_job: &Option<QueryJobId>,
104        span: Span,
105    ) -> CycleError {
106        // Find the waitee amongst `current_job` parents
107        let mut cycle = Vec::new();
108        let mut current_job = Option::clone(current_job);
109
110        while let Some(job) = current_job {
111            let info = query_map.get(&job).unwrap();
112            cycle.push(QueryInfo { span: info.job.span, query: info.query.clone() });
113
114            if job == *self {
115                cycle.reverse();
116
117                // This is the end of the cycle
118                // The span entry we included was for the usage
119                // of the cycle itself, and not part of the cycle
120                // Replace it with the span which caused the cycle to form
121                cycle[0].span = span;
122                // Find out why the cycle itself was used
123                let usage = info
124                    .job
125                    .parent
126                    .as_ref()
127                    .map(|parent| (info.job.span, parent.query(&query_map)));
128                return CycleError { usage, cycle };
129            }
130
131            current_job = info.job.parent;
132        }
133
134        panic!("did not find a cycle")
135    }
136
137    #[cold]
138    #[inline(never)]
139    pub fn find_dep_kind_root(&self, query_map: QueryMap) -> (QueryJobInfo, usize) {
140        let mut depth = 1;
141        let info = query_map.get(&self).unwrap();
142        let dep_kind = info.query.dep_kind;
143        let mut current_id = info.job.parent;
144        let mut last_layout = (info.clone(), depth);
145
146        while let Some(id) = current_id {
147            let info = query_map.get(&id).unwrap();
148            if info.query.dep_kind == dep_kind {
149                depth += 1;
150                last_layout = (info.clone(), depth);
151            }
152            current_id = info.job.parent;
153        }
154        last_layout
155    }
156}
157
158#[derive(Debug)]
159struct QueryWaiter {
160    query: Option<QueryJobId>,
161    condvar: Condvar,
162    span: Span,
163    cycle: Mutex<Option<CycleError>>,
164}
165
166#[derive(Debug)]
167struct QueryLatchInfo {
168    complete: bool,
169    waiters: Vec<Arc<QueryWaiter>>,
170}
171
172#[derive(Clone, Debug)]
173pub(super) struct QueryLatch {
174    info: Arc<Mutex<QueryLatchInfo>>,
175}
176
177impl QueryLatch {
178    fn new() -> Self {
179        QueryLatch {
180            info: Arc::new(Mutex::new(QueryLatchInfo { complete: false, waiters: Vec::new() })),
181        }
182    }
183
184    /// Awaits for the query job to complete.
185    pub(super) fn wait_on(&self, query: Option<QueryJobId>, span: Span) -> Result<(), CycleError> {
186        let waiter =
187            Arc::new(QueryWaiter { query, span, cycle: Mutex::new(None), condvar: Condvar::new() });
188        self.wait_on_inner(&waiter);
189        // FIXME: Get rid of this lock. We have ownership of the QueryWaiter
190        // although another thread may still have a Arc reference so we cannot
191        // use Arc::get_mut
192        let mut cycle = waiter.cycle.lock();
193        match cycle.take() {
194            None => Ok(()),
195            Some(cycle) => Err(cycle),
196        }
197    }
198
199    /// Awaits the caller on this latch by blocking the current thread.
200    fn wait_on_inner(&self, waiter: &Arc<QueryWaiter>) {
201        let mut info = self.info.lock();
202        if !info.complete {
203            // We push the waiter on to the `waiters` list. It can be accessed inside
204            // the `wait` call below, by 1) the `set` method or 2) by deadlock detection.
205            // Both of these will remove it from the `waiters` list before resuming
206            // this thread.
207            info.waiters.push(Arc::clone(waiter));
208
209            // If this detects a deadlock and the deadlock handler wants to resume this thread
210            // we have to be in the `wait` call. This is ensured by the deadlock handler
211            // getting the self.info lock.
212            rayon_core::mark_blocked();
213            jobserver::release_thread();
214            waiter.condvar.wait(&mut info);
215            // Release the lock before we potentially block in `acquire_thread`
216            drop(info);
217            jobserver::acquire_thread();
218        }
219    }
220
221    /// Sets the latch and resumes all waiters on it
222    fn set(&self) {
223        let mut info = self.info.lock();
224        debug_assert!(!info.complete);
225        info.complete = true;
226        let registry = rayon_core::Registry::current();
227        for waiter in info.waiters.drain(..) {
228            rayon_core::mark_unblocked(&registry);
229            waiter.condvar.notify_one();
230        }
231    }
232
233    /// Removes a single waiter from the list of waiters.
234    /// This is used to break query cycles.
235    fn extract_waiter(&self, waiter: usize) -> Arc<QueryWaiter> {
236        let mut info = self.info.lock();
237        debug_assert!(!info.complete);
238        // Remove the waiter from the list of waiters
239        info.waiters.remove(waiter)
240    }
241}
242
243/// A resumable waiter of a query. The usize is the index into waiters in the query's latch
244type Waiter = (QueryJobId, usize);
245
246/// Visits all the non-resumable and resumable waiters of a query.
247/// Only waiters in a query are visited.
248/// `visit` is called for every waiter and is passed a query waiting on `query_ref`
249/// and a span indicating the reason the query waited on `query_ref`.
250/// If `visit` returns Some, this function returns.
251/// For visits of non-resumable waiters it returns the return value of `visit`.
252/// For visits of resumable waiters it returns Some(Some(Waiter)) which has the
253/// required information to resume the waiter.
254/// If all `visit` calls returns None, this function also returns None.
255fn visit_waiters<F>(query_map: &QueryMap, query: QueryJobId, mut visit: F) -> Option<Option<Waiter>>
256where
257    F: FnMut(Span, QueryJobId) -> Option<Option<Waiter>>,
258{
259    // Visit the parent query which is a non-resumable waiter since it's on the same stack
260    if let Some(parent) = query.parent(query_map) {
261        if let Some(cycle) = visit(query.span(query_map), parent) {
262            return Some(cycle);
263        }
264    }
265
266    // Visit the explicit waiters which use condvars and are resumable
267    if let Some(latch) = query.latch(query_map) {
268        for (i, waiter) in latch.info.lock().waiters.iter().enumerate() {
269            if let Some(waiter_query) = waiter.query {
270                if visit(waiter.span, waiter_query).is_some() {
271                    // Return a value which indicates that this waiter can be resumed
272                    return Some(Some((query, i)));
273                }
274            }
275        }
276    }
277
278    None
279}
280
281/// Look for query cycles by doing a depth first search starting at `query`.
282/// `span` is the reason for the `query` to execute. This is initially DUMMY_SP.
283/// If a cycle is detected, this initial value is replaced with the span causing
284/// the cycle.
285fn cycle_check(
286    query_map: &QueryMap,
287    query: QueryJobId,
288    span: Span,
289    stack: &mut Vec<(Span, QueryJobId)>,
290    visited: &mut FxHashSet<QueryJobId>,
291) -> Option<Option<Waiter>> {
292    if !visited.insert(query) {
293        return if let Some(p) = stack.iter().position(|q| q.1 == query) {
294            // We detected a query cycle, fix up the initial span and return Some
295
296            // Remove previous stack entries
297            stack.drain(0..p);
298            // Replace the span for the first query with the cycle cause
299            stack[0].0 = span;
300            Some(None)
301        } else {
302            None
303        };
304    }
305
306    // Query marked as visited is added it to the stack
307    stack.push((span, query));
308
309    // Visit all the waiters
310    let r = visit_waiters(query_map, query, |span, successor| {
311        cycle_check(query_map, successor, span, stack, visited)
312    });
313
314    // Remove the entry in our stack if we didn't find a cycle
315    if r.is_none() {
316        stack.pop();
317    }
318
319    r
320}
321
322/// Finds out if there's a path to the compiler root (aka. code which isn't in a query)
323/// from `query` without going through any of the queries in `visited`.
324/// This is achieved with a depth first search.
325fn connected_to_root(
326    query_map: &QueryMap,
327    query: QueryJobId,
328    visited: &mut FxHashSet<QueryJobId>,
329) -> bool {
330    // We already visited this or we're deliberately ignoring it
331    if !visited.insert(query) {
332        return false;
333    }
334
335    // This query is connected to the root (it has no query parent), return true
336    if query.parent(query_map).is_none() {
337        return true;
338    }
339
340    visit_waiters(query_map, query, |_, successor| {
341        connected_to_root(query_map, successor, visited).then_some(None)
342    })
343    .is_some()
344}
345
346// Deterministically pick an query from a list
347fn pick_query<'a, T, F>(query_map: &QueryMap, queries: &'a [T], f: F) -> &'a T
348where
349    F: Fn(&T) -> (Span, QueryJobId),
350{
351    // Deterministically pick an entry point
352    // FIXME: Sort this instead
353    queries
354        .iter()
355        .min_by_key(|v| {
356            let (span, query) = f(v);
357            let hash = query.query(query_map).hash;
358            // Prefer entry points which have valid spans for nicer error messages
359            // We add an integer to the tuple ensuring that entry points
360            // with valid spans are picked first
361            let span_cmp = if span == DUMMY_SP { 1 } else { 0 };
362            (span_cmp, hash)
363        })
364        .unwrap()
365}
366
367/// Looks for query cycles starting from the last query in `jobs`.
368/// If a cycle is found, all queries in the cycle is removed from `jobs` and
369/// the function return true.
370/// If a cycle was not found, the starting query is removed from `jobs` and
371/// the function returns false.
372fn remove_cycle(
373    query_map: &QueryMap,
374    jobs: &mut Vec<QueryJobId>,
375    wakelist: &mut Vec<Arc<QueryWaiter>>,
376) -> bool {
377    let mut visited = FxHashSet::default();
378    let mut stack = Vec::new();
379    // Look for a cycle starting with the last query in `jobs`
380    if let Some(waiter) =
381        cycle_check(query_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited)
382    {
383        // The stack is a vector of pairs of spans and queries; reverse it so that
384        // the earlier entries require later entries
385        let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
386
387        // Shift the spans so that queries are matched with the span for their waitee
388        spans.rotate_right(1);
389
390        // Zip them back together
391        let mut stack: Vec<_> = iter::zip(spans, queries).collect();
392
393        // Remove the queries in our cycle from the list of jobs to look at
394        for r in &stack {
395            if let Some(pos) = jobs.iter().position(|j| j == &r.1) {
396                jobs.remove(pos);
397            }
398        }
399
400        // Find the queries in the cycle which are
401        // connected to queries outside the cycle
402        let entry_points = stack
403            .iter()
404            .filter_map(|&(span, query)| {
405                if query.parent(query_map).is_none() {
406                    // This query is connected to the root (it has no query parent)
407                    Some((span, query, None))
408                } else {
409                    let mut waiters = Vec::new();
410                    // Find all the direct waiters who lead to the root
411                    visit_waiters(query_map, query, |span, waiter| {
412                        // Mark all the other queries in the cycle as already visited
413                        let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
414
415                        if connected_to_root(query_map, waiter, &mut visited) {
416                            waiters.push((span, waiter));
417                        }
418
419                        None
420                    });
421                    if waiters.is_empty() {
422                        None
423                    } else {
424                        // Deterministically pick one of the waiters to show to the user
425                        let waiter = *pick_query(query_map, &waiters, |s| *s);
426                        Some((span, query, Some(waiter)))
427                    }
428                }
429            })
430            .collect::<Vec<(Span, QueryJobId, Option<(Span, QueryJobId)>)>>();
431
432        // Deterministically pick an entry point
433        let (_, entry_point, usage) = pick_query(query_map, &entry_points, |e| (e.0, e.1));
434
435        // Shift the stack so that our entry point is first
436        let entry_point_pos = stack.iter().position(|(_, query)| query == entry_point);
437        if let Some(pos) = entry_point_pos {
438            stack.rotate_left(pos);
439        }
440
441        let usage = usage.as_ref().map(|(span, query)| (*span, query.query(query_map)));
442
443        // Create the cycle error
444        let error = CycleError {
445            usage,
446            cycle: stack
447                .iter()
448                .map(|&(s, ref q)| QueryInfo { span: s, query: q.query(query_map) })
449                .collect(),
450        };
451
452        // We unwrap `waiter` here since there must always be one
453        // edge which is resumable / waited using a query latch
454        let (waitee_query, waiter_idx) = waiter.unwrap();
455
456        // Extract the waiter we want to resume
457        let waiter = waitee_query.latch(query_map).unwrap().extract_waiter(waiter_idx);
458
459        // Set the cycle error so it will be picked up when resumed
460        *waiter.cycle.lock() = Some(error);
461
462        // Put the waiter on the list of things to resume
463        wakelist.push(waiter);
464
465        true
466    } else {
467        false
468    }
469}
470
471/// Detects query cycles by using depth first search over all active query jobs.
472/// If a query cycle is found it will break the cycle by finding an edge which
473/// uses a query latch and then resuming that waiter.
474/// There may be multiple cycles involved in a deadlock, so this searches
475/// all active queries for cycles before finally resuming all the waiters at once.
476pub fn break_query_cycles(query_map: QueryMap, registry: &rayon_core::Registry) {
477    let mut wakelist = Vec::new();
478    let mut jobs: Vec<QueryJobId> = query_map.keys().cloned().collect();
479
480    let mut found_cycle = false;
481
482    while jobs.len() > 0 {
483        if remove_cycle(&query_map, &mut jobs, &mut wakelist) {
484            found_cycle = true;
485        }
486    }
487
488    // Check that a cycle was found. It is possible for a deadlock to occur without
489    // a query cycle if a query which can be waited on uses Rayon to do multithreading
490    // internally. Such a query (X) may be executing on 2 threads (A and B) and A may
491    // wait using Rayon on B. Rayon may then switch to executing another query (Y)
492    // which in turn will wait on X causing a deadlock. We have a false dependency from
493    // X to Y due to Rayon waiting and a true dependency from Y to X. The algorithm here
494    // only considers the true dependency and won't detect a cycle.
495    if !found_cycle {
496        panic!(
497            "deadlock detected as we're unable to find a query cycle to break\n\
498            current query map:\n{:#?}",
499            query_map
500        );
501    }
502
503    // Mark all the thread we're about to wake up as unblocked. This needs to be done before
504    // we wake the threads up as otherwise Rayon could detect a deadlock if a thread we
505    // resumed fell asleep and this thread had yet to mark the remaining threads as unblocked.
506    for _ in 0..wakelist.len() {
507        rayon_core::mark_unblocked(registry);
508    }
509
510    for waiter in wakelist.into_iter() {
511        waiter.condvar.notify_one();
512    }
513}
514
515#[inline(never)]
516#[cold]
517pub fn report_cycle<'a>(
518    sess: &'a Session,
519    CycleError { usage, cycle: stack }: &CycleError,
520) -> Diag<'a> {
521    assert!(!stack.is_empty());
522
523    let span = stack[0].query.default_span(stack[1 % stack.len()].span);
524
525    let mut cycle_stack = Vec::new();
526
527    use crate::error::StackCount;
528    let stack_count = if stack.len() == 1 { StackCount::Single } else { StackCount::Multiple };
529
530    for i in 1..stack.len() {
531        let query = &stack[i].query;
532        let span = query.default_span(stack[(i + 1) % stack.len()].span);
533        cycle_stack.push(CycleStack { span, desc: query.description.to_owned() });
534    }
535
536    let mut cycle_usage = None;
537    if let Some((span, ref query)) = *usage {
538        cycle_usage = Some(crate::error::CycleUsage {
539            span: query.default_span(span),
540            usage: query.description.to_string(),
541        });
542    }
543
544    let alias = if stack.iter().all(|entry| matches!(entry.query.def_kind, Some(DefKind::TyAlias)))
545    {
546        Some(crate::error::Alias::Ty)
547    } else if stack.iter().all(|entry| entry.query.def_kind == Some(DefKind::TraitAlias)) {
548        Some(crate::error::Alias::Trait)
549    } else {
550        None
551    };
552
553    let cycle_diag = crate::error::Cycle {
554        span,
555        cycle_stack,
556        stack_bottom: stack[0].query.description.to_owned(),
557        alias,
558        cycle_usage,
559        stack_count,
560        note_span: (),
561    };
562
563    sess.dcx().create_err(cycle_diag)
564}
565
566pub fn print_query_stack<Qcx: QueryContext>(
567    qcx: Qcx,
568    mut current_query: Option<QueryJobId>,
569    dcx: DiagCtxtHandle<'_>,
570    limit_frames: Option<usize>,
571    mut file: Option<std::fs::File>,
572) -> usize {
573    // Be careful relying on global state here: this code is called from
574    // a panic hook, which means that the global `DiagCtxt` may be in a weird
575    // state if it was responsible for triggering the panic.
576    let mut count_printed = 0;
577    let mut count_total = 0;
578
579    // Make use of a partial query map if we fail to take locks collecting active queries.
580    let query_map = match qcx.collect_active_jobs() {
581        Ok(query_map) => query_map,
582        Err(query_map) => query_map,
583    };
584
585    if let Some(ref mut file) = file {
586        let _ = writeln!(file, "\n\nquery stack during panic:");
587    }
588    while let Some(query) = current_query {
589        let Some(query_info) = query_map.get(&query) else {
590            break;
591        };
592        if Some(count_printed) < limit_frames || limit_frames.is_none() {
593            // Only print to stderr as many stack frames as `num_frames` when present.
594            // FIXME: needs translation
595            #[allow(rustc::diagnostic_outside_of_impl)]
596            #[allow(rustc::untranslatable_diagnostic)]
597            dcx.struct_failure_note(format!(
598                "#{} [{:?}] {}",
599                count_printed, query_info.query.dep_kind, query_info.query.description
600            ))
601            .with_span(query_info.job.span)
602            .emit();
603            count_printed += 1;
604        }
605
606        if let Some(ref mut file) = file {
607            let _ = writeln!(
608                file,
609                "#{} [{}] {}",
610                count_total,
611                qcx.dep_context().dep_kind_info(query_info.query.dep_kind).name,
612                query_info.query.description
613            );
614        }
615
616        current_query = query_info.job.parent;
617        count_total += 1;
618    }
619
620    if let Some(ref mut file) = file {
621        let _ = writeln!(file, "end of query stack");
622    }
623    count_total
624}