1 use crate::dep_graph::DepKind;
2 use crate::ty::context::TyCtxt;
3 use crate::ty::query::config::QueryContext;
4 use crate::ty::query::plumbing::CycleError;
5 use crate::ty::query::Query;
8 use rustc_data_structures::fx::FxHashMap;
11 use std::convert::TryFrom;
12 use std::marker::PhantomData;
13 use std::num::NonZeroU32;
15 #[cfg(parallel_compiler)]
17 parking_lot::{Condvar, Mutex},
18 rustc_data_structures::fx::FxHashSet,
19 rustc_data_structures::stable_hasher::{HashStable, StableHasher},
20 rustc_data_structures::sync::Lock,
21 rustc_data_structures::sync::Lrc,
22 rustc_data_structures::{jobserver, OnDrop},
23 rustc_rayon_core as rayon_core,
25 std::iter::FromIterator,
26 std::{mem, process, thread},
29 /// Represents a span and a query key.
30 #[derive(Clone, Debug)]
31 pub struct QueryInfo<CTX: QueryContext> {
32 /// The span corresponding to the reason for which this query was required.
34 pub query: CTX::Query,
37 type QueryMap<'tcx> = FxHashMap<QueryJobId<DepKind>, QueryJobInfo<TyCtxt<'tcx>>>;
39 /// A value uniquely identifiying an active query job within a shard in the query cache.
40 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
41 pub struct QueryShardJobId(pub NonZeroU32);
43 /// A value uniquely identifiying an active query job.
44 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
45 pub struct QueryJobId<K> {
46 /// Which job within a shard is this
47 pub job: QueryShardJobId,
49 /// In which shard is this job
52 /// What kind of query this job is
56 impl QueryJobId<DepKind> {
57 pub fn new(job: QueryShardJobId, shard: usize, kind: DepKind) -> Self {
58 QueryJobId { job, shard: u16::try_from(shard).unwrap(), kind }
61 fn query<'tcx>(self, map: &QueryMap<'tcx>) -> Query<'tcx> {
62 map.get(&self).unwrap().info.query.clone()
65 #[cfg(parallel_compiler)]
66 fn span(self, map: &QueryMap<'_>) -> Span {
67 map.get(&self).unwrap().job.span
70 #[cfg(parallel_compiler)]
71 fn parent(self, map: &QueryMap<'_>) -> Option<QueryJobId<DepKind>> {
72 map.get(&self).unwrap().job.parent
75 #[cfg(parallel_compiler)]
76 fn latch<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> Option<&'a QueryLatch<TyCtxt<'tcx>>> {
77 map.get(&self).unwrap().job.latch.as_ref()
81 pub struct QueryJobInfo<CTX: QueryContext> {
82 pub info: QueryInfo<CTX>,
83 pub job: QueryJob<CTX>,
86 /// Represents an active query job.
88 pub struct QueryJob<CTX: QueryContext> {
89 pub id: QueryShardJobId,
91 /// The span corresponding to the reason for which this query was required.
94 /// The parent query job which created this job and is implicitly waiting on it.
95 pub parent: Option<QueryJobId<CTX::DepKind>>,
97 /// The latch that is used to wait on this job.
98 #[cfg(parallel_compiler)]
99 latch: Option<QueryLatch<CTX>>,
101 dummy: PhantomData<QueryLatch<CTX>>,
104 impl<CTX: QueryContext> QueryJob<CTX> {
105 /// Creates a new query job.
106 pub fn new(id: QueryShardJobId, span: Span, parent: Option<QueryJobId<CTX::DepKind>>) -> Self {
111 #[cfg(parallel_compiler)]
117 #[cfg(parallel_compiler)]
118 pub(super) fn latch(&mut self, _id: QueryJobId<CTX::DepKind>) -> QueryLatch<CTX> {
119 if self.latch.is_none() {
120 self.latch = Some(QueryLatch::new());
122 self.latch.as_ref().unwrap().clone()
125 #[cfg(not(parallel_compiler))]
126 pub(super) fn latch(&mut self, id: QueryJobId<CTX::DepKind>) -> QueryLatch<CTX> {
127 QueryLatch { id, dummy: PhantomData }
130 /// Signals to waiters that the query is complete.
132 /// This does nothing for single threaded rustc,
133 /// as there are no concurrent jobs which could be waiting on us
134 pub fn signal_complete(self) {
135 #[cfg(parallel_compiler)]
136 self.latch.map(|latch| latch.set());
140 #[cfg(not(parallel_compiler))]
142 pub(super) struct QueryLatch<CTX: QueryContext> {
143 id: QueryJobId<CTX::DepKind>,
144 dummy: PhantomData<CTX>,
147 #[cfg(not(parallel_compiler))]
148 impl<'tcx> QueryLatch<TyCtxt<'tcx>> {
149 pub(super) fn find_cycle_in_stack(
153 ) -> CycleError<TyCtxt<'tcx>> {
154 let query_map = tcx.queries.try_collect_active_jobs().unwrap();
156 // Get the current executing query (waiter) and find the waitee amongst its parents
157 let mut current_job = tls::with_related_context(tcx, |icx| icx.query);
158 let mut cycle = Vec::new();
160 while let Some(job) = current_job {
161 let info = query_map.get(&job).unwrap();
162 cycle.push(info.info.clone());
167 // This is the end of the cycle
168 // The span entry we included was for the usage
169 // of the cycle itself, and not part of the cycle
170 // Replace it with the span which caused the cycle to form
171 cycle[0].span = span;
172 // Find out why the cycle itself was used
177 .map(|parent| (info.info.span, parent.query(&query_map)));
178 return CycleError { usage, cycle };
181 current_job = info.job.parent;
184 panic!("did not find a cycle")
188 #[cfg(parallel_compiler)]
189 struct QueryWaiter<CTX: QueryContext> {
190 query: Option<QueryJobId<CTX::DepKind>>,
193 cycle: Lock<Option<CycleError<CTX>>>,
196 #[cfg(parallel_compiler)]
197 impl<CTX: QueryContext> QueryWaiter<CTX> {
198 fn notify(&self, registry: &rayon_core::Registry) {
199 rayon_core::mark_unblocked(registry);
200 self.condvar.notify_one();
204 #[cfg(parallel_compiler)]
205 struct QueryLatchInfo<CTX: QueryContext> {
207 waiters: Vec<Lrc<QueryWaiter<CTX>>>,
210 #[cfg(parallel_compiler)]
212 pub(super) struct QueryLatch<CTX: QueryContext> {
213 info: Lrc<Mutex<QueryLatchInfo<CTX>>>,
216 #[cfg(parallel_compiler)]
217 impl<CTX: QueryContext> QueryLatch<CTX> {
220 info: Lrc::new(Mutex::new(QueryLatchInfo { complete: false, waiters: Vec::new() })),
225 #[cfg(parallel_compiler)]
226 impl<'tcx> QueryLatch<TyCtxt<'tcx>> {
227 /// Awaits for the query job to complete.
228 pub(super) fn wait_on(
232 ) -> Result<(), CycleError<TyCtxt<'tcx>>> {
233 tls::with_related_context(tcx, move |icx| {
234 let waiter = Lrc::new(QueryWaiter {
237 cycle: Lock::new(None),
238 condvar: Condvar::new(),
240 self.wait_on_inner(&waiter);
241 // FIXME: Get rid of this lock. We have ownership of the QueryWaiter
242 // although another thread may still have a Lrc reference so we cannot
244 let mut cycle = waiter.cycle.lock();
247 Some(cycle) => Err(cycle),
253 #[cfg(parallel_compiler)]
254 impl<CTX: QueryContext> QueryLatch<CTX> {
255 /// Awaits the caller on this latch by blocking the current thread.
256 fn wait_on_inner(&self, waiter: &Lrc<QueryWaiter<CTX>>) {
257 let mut info = self.info.lock();
259 // We push the waiter on to the `waiters` list. It can be accessed inside
260 // the `wait` call below, by 1) the `set` method or 2) by deadlock detection.
261 // Both of these will remove it from the `waiters` list before resuming
263 info.waiters.push(waiter.clone());
265 // If this detects a deadlock and the deadlock handler wants to resume this thread
266 // we have to be in the `wait` call. This is ensured by the deadlock handler
267 // getting the self.info lock.
268 rayon_core::mark_blocked();
269 jobserver::release_thread();
270 waiter.condvar.wait(&mut info);
271 // Release the lock before we potentially block in `acquire_thread`
273 jobserver::acquire_thread();
277 /// Sets the latch and resumes all waiters on it
279 let mut info = self.info.lock();
280 debug_assert!(!info.complete);
281 info.complete = true;
282 let registry = rayon_core::Registry::current();
283 for waiter in info.waiters.drain(..) {
284 waiter.notify(®istry);
288 /// Removes a single waiter from the list of waiters.
289 /// This is used to break query cycles.
290 fn extract_waiter(&self, waiter: usize) -> Lrc<QueryWaiter<CTX>> {
291 let mut info = self.info.lock();
292 debug_assert!(!info.complete);
293 // Remove the waiter from the list of waiters
294 info.waiters.remove(waiter)
298 /// A resumable waiter of a query. The usize is the index into waiters in the query's latch
299 #[cfg(parallel_compiler)]
300 type Waiter = (QueryJobId<DepKind>, usize);
302 /// Visits all the non-resumable and resumable waiters of a query.
303 /// Only waiters in a query are visited.
304 /// `visit` is called for every waiter and is passed a query waiting on `query_ref`
305 /// and a span indicating the reason the query waited on `query_ref`.
306 /// If `visit` returns Some, this function returns.
307 /// For visits of non-resumable waiters it returns the return value of `visit`.
308 /// For visits of resumable waiters it returns Some(Some(Waiter)) which has the
309 /// required information to resume the waiter.
310 /// If all `visit` calls returns None, this function also returns None.
311 #[cfg(parallel_compiler)]
312 fn visit_waiters<'tcx, F>(
313 query_map: &QueryMap<'tcx>,
314 query: QueryJobId<DepKind>,
316 ) -> Option<Option<Waiter>>
318 F: FnMut(Span, QueryJobId<DepKind>) -> Option<Option<Waiter>>,
320 // Visit the parent query which is a non-resumable waiter since it's on the same stack
321 if let Some(parent) = query.parent(query_map) {
322 if let Some(cycle) = visit(query.span(query_map), parent) {
327 // Visit the explicit waiters which use condvars and are resumable
328 if let Some(latch) = query.latch(query_map) {
329 for (i, waiter) in latch.info.lock().waiters.iter().enumerate() {
330 if let Some(waiter_query) = waiter.query {
331 if visit(waiter.span, waiter_query).is_some() {
332 // Return a value which indicates that this waiter can be resumed
333 return Some(Some((query, i)));
342 /// Look for query cycles by doing a depth first search starting at `query`.
343 /// `span` is the reason for the `query` to execute. This is initially DUMMY_SP.
344 /// If a cycle is detected, this initial value is replaced with the span causing
346 #[cfg(parallel_compiler)]
347 fn cycle_check<'tcx>(
348 query_map: &QueryMap<'tcx>,
349 query: QueryJobId<DepKind>,
351 stack: &mut Vec<(Span, QueryJobId<DepKind>)>,
352 visited: &mut FxHashSet<QueryJobId<DepKind>>,
353 ) -> Option<Option<Waiter>> {
354 if !visited.insert(query) {
355 return if let Some(p) = stack.iter().position(|q| q.1 == query) {
356 // We detected a query cycle, fix up the initial span and return Some
358 // Remove previous stack entries
360 // Replace the span for the first query with the cycle cause
368 // Query marked as visited is added it to the stack
369 stack.push((span, query));
371 // Visit all the waiters
372 let r = visit_waiters(query_map, query, |span, successor| {
373 cycle_check(query_map, successor, span, stack, visited)
376 // Remove the entry in our stack if we didn't find a cycle
384 /// Finds out if there's a path to the compiler root (aka. code which isn't in a query)
385 /// from `query` without going through any of the queries in `visited`.
386 /// This is achieved with a depth first search.
387 #[cfg(parallel_compiler)]
388 fn connected_to_root<'tcx>(
389 query_map: &QueryMap<'tcx>,
390 query: QueryJobId<DepKind>,
391 visited: &mut FxHashSet<QueryJobId<DepKind>>,
393 // We already visited this or we're deliberately ignoring it
394 if !visited.insert(query) {
398 // This query is connected to the root (it has no query parent), return true
399 if query.parent(query_map).is_none() {
403 visit_waiters(query_map, query, |_, successor| {
404 connected_to_root(query_map, successor, visited).then_some(None)
409 // Deterministically pick an query from a list
410 #[cfg(parallel_compiler)]
411 fn pick_query<'a, 'tcx, T, F: Fn(&T) -> (Span, QueryJobId<DepKind>)>(
412 query_map: &QueryMap<'tcx>,
417 // Deterministically pick an entry point
418 // FIXME: Sort this instead
419 let mut hcx = tcx.create_stable_hashing_context();
423 let (span, query) = f(v);
424 let mut stable_hasher = StableHasher::new();
425 query.query(query_map).hash_stable(&mut hcx, &mut stable_hasher);
426 // Prefer entry points which have valid spans for nicer error messages
427 // We add an integer to the tuple ensuring that entry points
428 // with valid spans are picked first
429 let span_cmp = if span == DUMMY_SP { 1 } else { 0 };
430 (span_cmp, stable_hasher.finish::<u64>())
435 /// Looks for query cycles starting from the last query in `jobs`.
436 /// If a cycle is found, all queries in the cycle is removed from `jobs` and
437 /// the function return true.
438 /// If a cycle was not found, the starting query is removed from `jobs` and
439 /// the function returns false.
440 #[cfg(parallel_compiler)]
441 fn remove_cycle<'tcx>(
442 query_map: &QueryMap<'tcx>,
443 jobs: &mut Vec<QueryJobId<DepKind>>,
444 wakelist: &mut Vec<Lrc<QueryWaiter<TyCtxt<'tcx>>>>,
447 let mut visited = FxHashSet::default();
448 let mut stack = Vec::new();
449 // Look for a cycle starting with the last query in `jobs`
450 if let Some(waiter) =
451 cycle_check(query_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited)
453 // The stack is a vector of pairs of spans and queries; reverse it so that
454 // the earlier entries require later entries
455 let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
457 // Shift the spans so that queries are matched with the span for their waitee
458 spans.rotate_right(1);
460 // Zip them back together
461 let mut stack: Vec<_> = spans.into_iter().zip(queries).collect();
463 // Remove the queries in our cycle from the list of jobs to look at
465 jobs.remove_item(&r.1);
468 // Find the queries in the cycle which are
469 // connected to queries outside the cycle
470 let entry_points = stack
472 .filter_map(|&(span, query)| {
473 if query.parent(query_map).is_none() {
474 // This query is connected to the root (it has no query parent)
475 Some((span, query, None))
477 let mut waiters = Vec::new();
478 // Find all the direct waiters who lead to the root
479 visit_waiters(query_map, query, |span, waiter| {
480 // Mark all the other queries in the cycle as already visited
481 let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
483 if connected_to_root(query_map, waiter, &mut visited) {
484 waiters.push((span, waiter));
489 if waiters.is_empty() {
492 // Deterministically pick one of the waiters to show to the user
493 let waiter = *pick_query(query_map, tcx, &waiters, |s| *s);
494 Some((span, query, Some(waiter)))
498 .collect::<Vec<(Span, QueryJobId<DepKind>, Option<(Span, QueryJobId<DepKind>)>)>>();
500 // Deterministically pick an entry point
501 let (_, entry_point, usage) = pick_query(query_map, tcx, &entry_points, |e| (e.0, e.1));
503 // Shift the stack so that our entry point is first
504 let entry_point_pos = stack.iter().position(|(_, query)| query == entry_point);
505 if let Some(pos) = entry_point_pos {
506 stack.rotate_left(pos);
509 let usage = usage.as_ref().map(|(span, query)| (*span, query.query(query_map)));
511 // Create the cycle error
512 let error = CycleError {
516 .map(|&(s, ref q)| QueryInfo { span: s, query: q.query(query_map) })
520 // We unwrap `waiter` here since there must always be one
521 // edge which is resumeable / waited using a query latch
522 let (waitee_query, waiter_idx) = waiter.unwrap();
524 // Extract the waiter we want to resume
525 let waiter = waitee_query.latch(query_map).unwrap().extract_waiter(waiter_idx);
527 // Set the cycle error so it will be picked up when resumed
528 *waiter.cycle.lock() = Some(error);
530 // Put the waiter on the list of things to resume
531 wakelist.push(waiter);
539 /// Creates a new thread and forwards information in thread locals to it.
540 /// The new thread runs the deadlock handler.
541 /// Must only be called when a deadlock is about to happen.
542 #[cfg(parallel_compiler)]
543 pub unsafe fn handle_deadlock() {
544 let registry = rayon_core::Registry::current();
546 let gcx_ptr = tls::GCX_PTR.with(|gcx_ptr| gcx_ptr as *const _);
547 let gcx_ptr = &*gcx_ptr;
549 let rustc_span_globals =
550 rustc_span::GLOBALS.with(|rustc_span_globals| rustc_span_globals as *const _);
551 let rustc_span_globals = &*rustc_span_globals;
552 let syntax_globals = rustc_ast::attr::GLOBALS.with(|syntax_globals| syntax_globals as *const _);
553 let syntax_globals = &*syntax_globals;
554 thread::spawn(move || {
555 tls::GCX_PTR.set(gcx_ptr, || {
556 rustc_ast::attr::GLOBALS.set(syntax_globals, || {
558 .set(rustc_span_globals, || tls::with_global(|tcx| deadlock(tcx, ®istry)))
564 /// Detects query cycles by using depth first search over all active query jobs.
565 /// If a query cycle is found it will break the cycle by finding an edge which
566 /// uses a query latch and then resuming that waiter.
567 /// There may be multiple cycles involved in a deadlock, so this searches
568 /// all active queries for cycles before finally resuming all the waiters at once.
569 #[cfg(parallel_compiler)]
570 fn deadlock(tcx: TyCtxt<'_>, registry: &rayon_core::Registry) {
571 let on_panic = OnDrop(|| {
572 eprintln!("deadlock handler panicked, aborting process");
576 let mut wakelist = Vec::new();
577 let query_map = tcx.queries.try_collect_active_jobs().unwrap();
578 let mut jobs: Vec<QueryJobId<DepKind>> = query_map.keys().cloned().collect();
580 let mut found_cycle = false;
582 while jobs.len() > 0 {
583 if remove_cycle(&query_map, &mut jobs, &mut wakelist, tcx) {
588 // Check that a cycle was found. It is possible for a deadlock to occur without
589 // a query cycle if a query which can be waited on uses Rayon to do multithreading
590 // internally. Such a query (X) may be executing on 2 threads (A and B) and A may
591 // wait using Rayon on B. Rayon may then switch to executing another query (Y)
592 // which in turn will wait on X causing a deadlock. We have a false dependency from
593 // X to Y due to Rayon waiting and a true dependency from Y to X. The algorithm here
594 // only considers the true dependency and won't detect a cycle.
595 assert!(found_cycle);
597 // FIXME: Ensure this won't cause a deadlock before we return
598 for waiter in wakelist.into_iter() {
599 waiter.notify(registry);