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_data_structures::hash_table::HashTable;
8use rustc_data_structures::sharded::Sharded;
9use rustc_span::Span;
10
11use crate::queries::TaggedQueryKey;
12
13/// A value uniquely identifying an active query job.
14#[derive(#[automatically_derived]
impl ::core::marker::Copy for QueryJobId { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for QueryJobId { }
#[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::marker::StructuralPartialEq for QueryJobId { }
#[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)]
15pub struct QueryJobId(pub NonZero<u64>);
16
17/// Represents an active query job.
18#[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)]
19pub struct QueryJob<'tcx> {
20    pub id: QueryJobId,
21
22    /// The span corresponding to the reason for which this query was required.
23    pub span: Span,
24
25    /// The parent query job which created this job and is implicitly waiting on it.
26    pub parent: Option<QueryJobId>,
27
28    /// The latch that is used to wait on this job.
29    pub latch: Option<QueryLatch<'tcx>>,
30}
31
32impl<'tcx> QueryJob<'tcx> {
33    /// Creates a new query job.
34    #[inline]
35    pub fn new(id: QueryJobId, span: Span, parent: Option<QueryJobId>) -> Self {
36        QueryJob { id, span, parent, latch: None }
37    }
38
39    pub fn latch(&mut self) -> QueryLatch<'tcx> {
40        self.latch.get_or_insert_with(QueryLatch::new).clone()
41    }
42
43    /// Signals to waiters that the query is complete.
44    ///
45    /// This does nothing for single threaded rustc,
46    /// as there are no concurrent jobs which could be waiting on us
47    #[inline]
48    pub fn signal_complete(self) {
49        if let Some(latch) = self.latch {
50            latch.set();
51        }
52    }
53}
54
55/// For a particular query and key, tracks the status of a query evaluation
56/// that has started, but has not yet finished successfully.
57///
58/// (Successful query evaluation for a key is represented by an entry in the
59/// query's in-memory cache.)
60pub enum ActiveKeyStatus<'tcx> {
61    /// Some thread is already evaluating the query for this key.
62    ///
63    /// The enclosed [`QueryJob`] can be used to wait for it to finish.
64    Started(QueryJob<'tcx>),
65
66    /// The query panicked. Queries trying to wait on this will raise a fatal error which will
67    /// silently panic.
68    Poisoned,
69}
70
71/// For a particular query, keeps track of "active" keys, i.e. keys whose
72/// evaluation has started but has not yet finished successfully.
73///
74/// (Successful query evaluation for a key is represented by an entry in the
75/// query's in-memory cache.)
76pub struct QueryState<'tcx, K> {
77    pub active: Sharded<HashTable<(K, ActiveKeyStatus<'tcx>)>>,
78}
79
80impl<'tcx, K> Default for QueryState<'tcx, K> {
81    fn default() -> QueryState<'tcx, K> {
82        QueryState { active: Default::default() }
83    }
84}
85
86/// Description of a frame in the query stack.
87///
88/// This is mostly used in case of cycles for error reporting.
89#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryStackFrame<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "QueryStackFrame", "span", &self.span, "tagged_key",
            &&self.tagged_key)
    }
}Debug)]
90pub struct QueryStackFrame<'tcx> {
91    pub span: Span,
92
93    /// The query and key of the query method call that this stack frame
94    /// corresponds to.
95    ///
96    /// Code that doesn't care about the specific key can still use this to
97    /// check which query it's for, or obtain the query's name.
98    pub tagged_key: TaggedQueryKey<'tcx>,
99}
100
101#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for QueryCycle<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "QueryCycle",
            "usage", &self.usage, "frames", &&self.frames)
    }
}Debug)]
102pub struct QueryCycle<'tcx> {
103    /// The query and related span that uses the cycle.
104    pub usage: Option<QueryStackFrame<'tcx>>,
105
106    /// The span here corresponds to the reason for which this query was required.
107    pub frames: Vec<QueryStackFrame<'tcx>>,
108}
109
110#[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)]
111pub struct QueryWaiter<'tcx> {
112    pub parent: Option<QueryJobId>,
113    pub condvar: Condvar,
114    pub span: Span,
115    pub cycle: Mutex<Option<QueryCycle<'tcx>>>,
116}
117
118#[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)]
119pub struct QueryLatch<'tcx> {
120    /// The `Option` is `Some(..)` when the job is active, and `None` once completed.
121    pub waiters: Arc<Mutex<Option<Vec<Arc<QueryWaiter<'tcx>>>>>>,
122}
123
124impl<'tcx> QueryLatch<'tcx> {
125    fn new() -> Self {
126        QueryLatch { waiters: Arc::new(Mutex::new(Some(Vec::new()))) }
127    }
128
129    /// Awaits for the query job to complete.
130    pub fn wait_on(&self, query: Option<QueryJobId>, span: Span) -> Result<(), QueryCycle<'tcx>> {
131        let mut waiters_guard = self.waiters.lock();
132        let Some(waiters) = &mut *waiters_guard else {
133            return Ok(()); // already complete
134        };
135
136        let waiter = Arc::new(QueryWaiter {
137            parent: query,
138            span,
139            cycle: Mutex::new(None),
140            condvar: Condvar::new(),
141        });
142
143        // We push the waiter on to the `waiters` list. It can be accessed inside
144        // the `wait` call below, by 1) the `set` method or 2) by deadlock detection.
145        // Both of these will remove it from the `waiters` list before resuming
146        // this thread.
147        waiters.push(Arc::clone(&waiter));
148
149        // Awaits the caller on this latch by blocking the current thread.
150        // If this detects a deadlock and the deadlock handler wants to resume this thread
151        // we have to be in the `wait` call. This is ensured by the deadlock handler
152        // getting the self.info lock.
153        rustc_thread_pool::mark_blocked_and_wait(|| {
154            waiter.condvar.wait(&mut waiters_guard);
155            // Release the lock before we potentially block when acquiring jobserver token.
156            drop(waiters_guard);
157        });
158
159        // FIXME: Get rid of this lock. We have ownership of the QueryWaiter
160        // although another thread may still have a Arc reference so we cannot
161        // use Arc::get_mut
162        let mut cycle = waiter.cycle.lock();
163        match cycle.take() {
164            None => Ok(()),
165            Some(cycle) => Err(cycle),
166        }
167    }
168
169    /// Sets the latch and resumes all waiters on it
170    fn set(&self) {
171        let mut waiters_guard = self.waiters.lock();
172        let waiters = waiters_guard.take().unwrap(); // mark the latch as complete
173        let registry = rustc_thread_pool::Registry::current();
174        for waiter in waiters {
175            rustc_thread_pool::mark_unblocked(&registry);
176            waiter.condvar.notify_one();
177        }
178    }
179
180    /// Removes a single waiter from the list of waiters.
181    /// This is used to break query cycles.
182    pub fn extract_waiter(&self, waiter: usize) -> Arc<QueryWaiter<'tcx>> {
183        let mut waiters_guard = self.waiters.lock();
184        let waiters = waiters_guard.as_mut().expect("non-empty waiters vec");
185        // Remove the waiter from the list of waiters
186        waiters.remove(waiter)
187    }
188}