Skip to main content

rustc_middle/query/
job.rs

1use std::fmt::Debug;
2use std::hash::Hash;
3use std::num::NonZero;
4use std::sync::Arc;
5
6use parking_lot::{Condvar, Mutex};
7use rustc_span::Span;
8
9use crate::query::Cycle;
10
11/// A value uniquely identifying an active query job.
12#[derive(#[automatically_derived]
impl ::core::marker::Copy for QueryJobId { }Copy, #[automatically_derived]
impl ::core::clone::Clone for QueryJobId {
    #[inline]
    fn clone(&self) -> QueryJobId {
        let _: ::core::clone::AssertParamIsClone<NonZero<u64>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for QueryJobId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NonZero<u64>>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for QueryJobId {
    #[inline]
    fn eq(&self, other: &QueryJobId) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for QueryJobId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for QueryJobId {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "QueryJobId",
            &&self.0)
    }
}Debug)]
13pub struct QueryJobId(pub NonZero<u64>);
14
15/// Represents an active query job.
16#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for QueryJob<'tcx> {
    #[inline]
    fn clone(&self) -> QueryJob<'tcx> {
        QueryJob {
            id: ::core::clone::Clone::clone(&self.id),
            span: ::core::clone::Clone::clone(&self.span),
            parent: ::core::clone::Clone::clone(&self.parent),
            latch: ::core::clone::Clone::clone(&self.latch),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryJob<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "QueryJob",
            "id", &self.id, "span", &self.span, "parent", &self.parent,
            "latch", &&self.latch)
    }
}Debug)]
17pub struct QueryJob<'tcx> {
18    pub id: QueryJobId,
19
20    /// The span corresponding to the reason for which this query was required.
21    pub span: Span,
22
23    /// The parent query job which created this job and is implicitly waiting on it.
24    pub parent: Option<QueryJobId>,
25
26    /// The latch that is used to wait on this job.
27    pub latch: Option<QueryLatch<'tcx>>,
28}
29
30impl<'tcx> QueryJob<'tcx> {
31    /// Creates a new query job.
32    #[inline]
33    pub fn new(id: QueryJobId, span: Span, parent: Option<QueryJobId>) -> Self {
34        QueryJob { id, span, parent, latch: None }
35    }
36
37    pub fn latch(&mut self) -> QueryLatch<'tcx> {
38        self.latch.get_or_insert_with(QueryLatch::new).clone()
39    }
40
41    /// Signals to waiters that the query is complete.
42    ///
43    /// This does nothing for single threaded rustc,
44    /// as there are no concurrent jobs which could be waiting on us
45    #[inline]
46    pub fn signal_complete(self) {
47        if let Some(latch) = self.latch {
48            latch.set();
49        }
50    }
51}
52
53#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryWaiter<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "QueryWaiter",
            "parent", &self.parent, "condvar", &self.condvar, "span",
            &self.span, "cycle", &&self.cycle)
    }
}Debug)]
54pub struct QueryWaiter<'tcx> {
55    pub parent: Option<QueryJobId>,
56    pub condvar: Condvar,
57    pub span: Span,
58    pub cycle: Mutex<Option<Cycle<'tcx>>>,
59}
60
61#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for QueryLatch<'tcx> {
    #[inline]
    fn clone(&self) -> QueryLatch<'tcx> {
        QueryLatch { waiters: ::core::clone::Clone::clone(&self.waiters) }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryLatch<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "QueryLatch",
            "waiters", &&self.waiters)
    }
}Debug)]
62pub struct QueryLatch<'tcx> {
63    /// The `Option` is `Some(..)` when the job is active, and `None` once completed.
64    pub waiters: Arc<Mutex<Option<Vec<Arc<QueryWaiter<'tcx>>>>>>,
65}
66
67impl<'tcx> QueryLatch<'tcx> {
68    fn new() -> Self {
69        QueryLatch { waiters: Arc::new(Mutex::new(Some(Vec::new()))) }
70    }
71
72    /// Awaits for the query job to complete.
73    pub fn wait_on(&self, query: Option<QueryJobId>, span: Span) -> Result<(), Cycle<'tcx>> {
74        let mut waiters_guard = self.waiters.lock();
75        let Some(waiters) = &mut *waiters_guard else {
76            return Ok(()); // already complete
77        };
78
79        let waiter = Arc::new(QueryWaiter {
80            parent: query,
81            span,
82            cycle: Mutex::new(None),
83            condvar: Condvar::new(),
84        });
85
86        // We push the waiter on to the `waiters` list. It can be accessed inside
87        // the `wait` call below, by 1) the `set` method or 2) by deadlock detection.
88        // Both of these will remove it from the `waiters` list before resuming
89        // this thread.
90        waiters.push(Arc::clone(&waiter));
91
92        // Awaits the caller on this latch by blocking the current thread.
93        // If this detects a deadlock and the deadlock handler wants to resume this thread
94        // we have to be in the `wait` call. This is ensured by the deadlock handler
95        // getting the self.info lock.
96        rustc_thread_pool::mark_blocked_and_wait(|| {
97            waiter.condvar.wait(&mut waiters_guard);
98            // Release the lock before we potentially block when acquiring jobserver token.
99            drop(waiters_guard);
100        });
101
102        // FIXME: Get rid of this lock. We have ownership of the QueryWaiter
103        // although another thread may still have a Arc reference so we cannot
104        // use Arc::get_mut
105        let mut cycle = waiter.cycle.lock();
106        match cycle.take() {
107            None => Ok(()),
108            Some(cycle) => Err(cycle),
109        }
110    }
111
112    /// Sets the latch and resumes all waiters on it
113    fn set(&self) {
114        let mut waiters_guard = self.waiters.lock();
115        let waiters = waiters_guard.take().unwrap(); // mark the latch as complete
116        let registry = rustc_thread_pool::Registry::current();
117        for waiter in waiters {
118            rustc_thread_pool::mark_unblocked(&registry);
119            waiter.condvar.notify_one();
120        }
121    }
122
123    /// Removes a single waiter from the list of waiters.
124    /// This is used to break query cycles.
125    pub fn extract_waiter(&self, waiter: usize) -> Arc<QueryWaiter<'tcx>> {
126        let mut waiters_guard = self.waiters.lock();
127        let waiters = waiters_guard.as_mut().expect("non-empty waiters vec");
128        // Remove the waiter from the list of waiters
129        waiters.remove(waiter)
130    }
131}