rust/src/librustc/ty/query/job.rs

604 lines
21 KiB
Rust
Raw Normal View History

use crate::dep_graph::DepKind;
use crate::ty::context::TyCtxt;
2020-03-08 12:20:18 -05:00
use crate::ty::query::config::QueryContext;
use crate::ty::query::plumbing::CycleError;
use crate::ty::query::Query;
use crate::ty::tls;
2019-02-05 11:20:45 -06:00
2020-01-30 21:00:03 -06:00
use rustc_data_structures::fx::FxHashMap;
use rustc_span::Span;
2019-02-05 11:20:45 -06:00
2020-02-12 07:24:38 -06:00
use std::convert::TryFrom;
2020-01-30 21:00:03 -06:00
use std::marker::PhantomData;
use std::num::NonZeroU32;
#[cfg(parallel_compiler)]
use {
2019-12-22 16:42:04 -06:00
parking_lot::{Condvar, Mutex},
rustc_data_structures::fx::FxHashSet,
2019-12-22 16:42:04 -06:00
rustc_data_structures::stable_hasher::{HashStable, StableHasher},
rustc_data_structures::sync::Lock,
2020-01-30 21:00:03 -06:00
rustc_data_structures::sync::Lrc,
2019-12-22 16:42:04 -06:00
rustc_data_structures::{jobserver, OnDrop},
rustc_rayon_core as rayon_core,
rustc_span::DUMMY_SP,
std::iter::FromIterator,
2019-12-22 16:42:04 -06:00
std::{mem, process, thread},
};
2019-02-08 07:53:55 -06:00
/// Represents a span and a query key.
#[derive(Clone, Debug)]
2020-03-08 12:20:18 -05:00
pub struct QueryInfo<CTX: QueryContext> {
2019-02-08 07:53:55 -06:00
/// The span corresponding to the reason for which this query was required.
pub span: Span,
2020-03-08 12:20:18 -05:00
pub query: CTX::Query,
}
2020-03-18 14:30:02 -05:00
type QueryMap<'tcx> = FxHashMap<QueryJobId<DepKind>, QueryJobInfo<TyCtxt<'tcx>>>;
/// A value uniquely identifiying an active query job within a shard in the query cache.
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct QueryShardJobId(pub NonZeroU32);
2020-01-30 21:00:03 -06:00
/// A value uniquely identifiying an active query job.
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
2020-03-18 14:30:02 -05:00
pub struct QueryJobId<K> {
/// Which job within a shard is this
pub job: QueryShardJobId,
2020-01-30 21:00:03 -06:00
/// In which shard is this job
pub shard: u16,
/// What kind of query this job is
2020-03-18 14:30:02 -05:00
pub kind: K,
}
2020-01-30 21:00:03 -06:00
2020-03-18 14:30:02 -05:00
impl QueryJobId<DepKind> {
2020-02-12 07:24:38 -06:00
pub fn new(job: QueryShardJobId, shard: usize, kind: DepKind) -> Self {
QueryJobId { job, shard: u16::try_from(shard).unwrap(), kind }
}
2020-01-30 21:00:03 -06:00
fn query<'tcx>(self, map: &QueryMap<'tcx>) -> Query<'tcx> {
map.get(&self).unwrap().info.query.clone()
}
#[cfg(parallel_compiler)]
fn span(self, map: &QueryMap<'_>) -> Span {
map.get(&self).unwrap().job.span
}
#[cfg(parallel_compiler)]
2020-03-18 14:30:02 -05:00
fn parent(self, map: &QueryMap<'_>) -> Option<QueryJobId<DepKind>> {
2020-01-30 21:00:03 -06:00
map.get(&self).unwrap().job.parent
}
#[cfg(parallel_compiler)]
2020-03-08 12:20:18 -05:00
fn latch<'a, 'tcx>(self, map: &'a QueryMap<'tcx>) -> Option<&'a QueryLatch<TyCtxt<'tcx>>> {
2020-01-30 21:00:03 -06:00
map.get(&self).unwrap().job.latch.as_ref()
}
}
2020-03-08 12:20:18 -05:00
pub struct QueryJobInfo<CTX: QueryContext> {
pub info: QueryInfo<CTX>,
pub job: QueryJob<CTX>,
2020-01-30 21:00:03 -06:00
}
/// Represents an active query job.
#[derive(Clone)]
2020-03-08 12:20:18 -05:00
pub struct QueryJob<CTX: QueryContext> {
pub id: QueryShardJobId,
2020-01-30 21:00:03 -06:00
/// The span corresponding to the reason for which this query was required.
pub span: Span,
2018-03-24 00:19:20 -05:00
/// The parent query job which created this job and is implicitly waiting on it.
2020-03-18 14:30:02 -05:00
pub parent: Option<QueryJobId<CTX::DepKind>>,
2018-03-24 00:19:20 -05:00
2019-02-08 07:53:55 -06:00
/// The latch that is used to wait on this job.
#[cfg(parallel_compiler)]
2020-03-08 12:20:18 -05:00
latch: Option<QueryLatch<CTX>>,
2020-01-30 21:00:03 -06:00
2020-03-08 12:20:18 -05:00
dummy: PhantomData<QueryLatch<CTX>>,
}
2020-03-08 12:20:18 -05:00
impl<CTX: QueryContext> QueryJob<CTX> {
2019-02-08 07:53:55 -06:00
/// Creates a new query job.
2020-03-18 14:30:02 -05:00
pub fn new(id: QueryShardJobId, span: Span, parent: Option<QueryJobId<CTX::DepKind>>) -> Self {
QueryJob {
id,
2020-01-30 21:00:03 -06:00
span,
parent,
#[cfg(parallel_compiler)]
2020-01-30 21:00:03 -06:00
latch: None,
dummy: PhantomData,
}
}
#[cfg(parallel_compiler)]
2020-03-18 14:30:02 -05:00
pub(super) fn latch(&mut self, _id: QueryJobId<CTX::DepKind>) -> QueryLatch<CTX> {
2020-01-30 21:00:03 -06:00
if self.latch.is_none() {
self.latch = Some(QueryLatch::new());
}
self.latch.as_ref().unwrap().clone()
}
#[cfg(not(parallel_compiler))]
2020-03-18 14:30:02 -05:00
pub(super) fn latch(&mut self, id: QueryJobId<CTX::DepKind>) -> QueryLatch<CTX> {
QueryLatch { id, dummy: PhantomData }
2020-01-30 21:00:03 -06:00
}
/// Signals to waiters that the query is complete.
///
/// This does nothing for single threaded rustc,
/// as there are no concurrent jobs which could be waiting on us
pub fn signal_complete(self) {
#[cfg(parallel_compiler)]
self.latch.map(|latch| latch.set());
}
}
#[cfg(not(parallel_compiler))]
#[derive(Clone)]
2020-03-18 14:30:02 -05:00
pub(super) struct QueryLatch<CTX: QueryContext> {
id: QueryJobId<CTX::DepKind>,
2020-03-08 12:20:18 -05:00
dummy: PhantomData<CTX>,
2020-01-30 21:00:03 -06:00
}
#[cfg(not(parallel_compiler))]
2020-03-08 12:20:18 -05:00
impl<'tcx> QueryLatch<TyCtxt<'tcx>> {
pub(super) fn find_cycle_in_stack(
&self,
tcx: TyCtxt<'tcx>,
span: Span,
) -> CycleError<TyCtxt<'tcx>> {
2020-01-30 21:00:03 -06:00
let query_map = tcx.queries.try_collect_active_jobs().unwrap();
2018-03-24 00:19:20 -05:00
// Get the current executing query (waiter) and find the waitee amongst its parents
2020-01-30 21:00:03 -06:00
let mut current_job = tls::with_related_context(tcx, |icx| icx.query);
let mut cycle = Vec::new();
while let Some(job) = current_job {
2020-01-30 21:00:03 -06:00
let info = query_map.get(&job).unwrap();
cycle.push(info.info.clone());
if job == self.id {
cycle.reverse();
2018-04-13 15:20:10 -05:00
// This is the end of the cycle
// The span entry we included was for the usage
// of the cycle itself, and not part of the cycle
// Replace it with the span which caused the cycle to form
cycle[0].span = span;
// Find out why the cycle itself was used
2020-01-30 21:00:03 -06:00
let usage = info
.job
.parent
.as_ref()
.map(|parent| (info.info.span, parent.query(&query_map)));
2018-12-04 09:26:34 -06:00
return CycleError { usage, cycle };
}
current_job = info.job.parent;
}
2018-04-13 15:20:10 -05:00
panic!("did not find a cycle")
}
}
#[cfg(parallel_compiler)]
2020-03-08 12:20:18 -05:00
struct QueryWaiter<CTX: QueryContext> {
2020-03-18 14:30:02 -05:00
query: Option<QueryJobId<CTX::DepKind>>,
condvar: Condvar,
span: Span,
2020-03-08 12:20:18 -05:00
cycle: Lock<Option<CycleError<CTX>>>,
}
#[cfg(parallel_compiler)]
2020-03-08 12:20:18 -05:00
impl<CTX: QueryContext> QueryWaiter<CTX> {
2018-05-27 02:01:57 -05:00
fn notify(&self, registry: &rayon_core::Registry) {
rayon_core::mark_unblocked(registry);
self.condvar.notify_one();
}
}
#[cfg(parallel_compiler)]
2020-03-08 12:20:18 -05:00
struct QueryLatchInfo<CTX: QueryContext> {
complete: bool,
2020-03-08 12:20:18 -05:00
waiters: Vec<Lrc<QueryWaiter<CTX>>>,
}
#[cfg(parallel_compiler)]
2020-01-30 21:00:03 -06:00
#[derive(Clone)]
2020-03-08 12:20:18 -05:00
pub(super) struct QueryLatch<CTX: QueryContext> {
info: Lrc<Mutex<QueryLatchInfo<CTX>>>,
}
#[cfg(parallel_compiler)]
2020-03-08 12:20:18 -05:00
impl<CTX: QueryContext> QueryLatch<CTX> {
fn new() -> Self {
2020-01-30 21:00:03 -06:00
QueryLatch {
info: Lrc::new(Mutex::new(QueryLatchInfo { complete: false, waiters: Vec::new() })),
}
}
2020-03-08 12:20:18 -05:00
}
2020-01-30 21:00:03 -06:00
2020-03-08 12:20:18 -05:00
#[cfg(parallel_compiler)]
impl<'tcx> QueryLatch<TyCtxt<'tcx>> {
2020-01-30 21:00:03 -06:00
/// Awaits for the query job to complete.
2020-03-08 12:20:18 -05:00
pub(super) fn wait_on(
&self,
tcx: TyCtxt<'tcx>,
span: Span,
) -> Result<(), CycleError<TyCtxt<'tcx>>> {
2020-01-30 21:00:03 -06:00
tls::with_related_context(tcx, move |icx| {
let waiter = Lrc::new(QueryWaiter {
query: icx.query,
span,
cycle: Lock::new(None),
condvar: Condvar::new(),
});
self.wait_on_inner(&waiter);
// FIXME: Get rid of this lock. We have ownership of the QueryWaiter
// although another thread may still have a Lrc reference so we cannot
// use Lrc::get_mut
let mut cycle = waiter.cycle.lock();
match cycle.take() {
None => Ok(()),
Some(cycle) => Err(cycle),
}
})
}
2020-03-08 12:20:18 -05:00
}
2020-03-08 12:20:18 -05:00
#[cfg(parallel_compiler)]
impl<CTX: QueryContext> QueryLatch<CTX> {
2018-05-27 06:05:41 -05:00
/// Awaits the caller on this latch by blocking the current thread.
2020-03-08 12:20:18 -05:00
fn wait_on_inner(&self, waiter: &Lrc<QueryWaiter<CTX>>) {
let mut info = self.info.lock();
if !info.complete {
2018-05-27 06:05:41 -05:00
// We push the waiter on to the `waiters` list. It can be accessed inside
// the `wait` call below, by 1) the `set` method or 2) by deadlock detection.
// Both of these will remove it from the `waiters` list before resuming
// this thread.
2018-05-31 13:24:56 -05:00
info.waiters.push(waiter.clone());
2018-05-27 06:05:41 -05:00
2018-05-31 16:04:21 -05:00
// If this detects a deadlock and the deadlock handler wants to resume this thread
// we have to be in the `wait` call. This is ensured by the deadlock handler
// getting the self.info lock.
rayon_core::mark_blocked();
jobserver::release_thread();
2018-05-27 06:05:41 -05:00
waiter.condvar.wait(&mut info);
// Release the lock before we potentially block in `acquire_thread`
mem::drop(info);
jobserver::acquire_thread();
}
}
2018-05-27 06:05:41 -05:00
/// Sets the latch and resumes all waiters on it
2018-05-27 02:01:57 -05:00
fn set(&self) {
let mut info = self.info.lock();
debug_assert!(!info.complete);
info.complete = true;
let registry = rayon_core::Registry::current();
for waiter in info.waiters.drain(..) {
2018-05-31 13:24:56 -05:00
waiter.notify(&registry);
}
}
2019-02-08 07:53:55 -06:00
/// Removes a single waiter from the list of waiters.
2018-05-27 06:05:41 -05:00
/// This is used to break query cycles.
2020-03-08 12:20:18 -05:00
fn extract_waiter(&self, waiter: usize) -> Lrc<QueryWaiter<CTX>> {
let mut info = self.info.lock();
debug_assert!(!info.complete);
// Remove the waiter from the list of waiters
2018-05-27 06:05:41 -05:00
info.waiters.remove(waiter)
}
}
2018-05-27 06:05:41 -05:00
/// A resumable waiter of a query. The usize is the index into waiters in the query's latch
#[cfg(parallel_compiler)]
2020-03-18 14:30:02 -05:00
type Waiter = (QueryJobId<DepKind>, usize);
2018-05-27 06:05:41 -05:00
/// Visits all the non-resumable and resumable waiters of a query.
/// Only waiters in a query are visited.
/// `visit` is called for every waiter and is passed a query waiting on `query_ref`
/// and a span indicating the reason the query waited on `query_ref`.
/// If `visit` returns Some, this function returns.
/// For visits of non-resumable waiters it returns the return value of `visit`.
/// For visits of resumable waiters it returns Some(Some(Waiter)) which has the
/// required information to resume the waiter.
/// If all `visit` calls returns None, this function also returns None.
#[cfg(parallel_compiler)]
2020-01-30 21:00:03 -06:00
fn visit_waiters<'tcx, F>(
query_map: &QueryMap<'tcx>,
2020-03-18 14:30:02 -05:00
query: QueryJobId<DepKind>,
2020-01-30 21:00:03 -06:00
mut visit: F,
) -> Option<Option<Waiter>>
where
2020-03-18 14:30:02 -05:00
F: FnMut(Span, QueryJobId<DepKind>) -> Option<Option<Waiter>>,
{
2018-05-27 06:05:41 -05:00
// Visit the parent query which is a non-resumable waiter since it's on the same stack
2020-01-30 21:00:03 -06:00
if let Some(parent) = query.parent(query_map) {
if let Some(cycle) = visit(query.span(query_map), parent) {
return Some(cycle);
}
}
2018-05-27 06:05:41 -05:00
2018-08-19 08:30:23 -05:00
// Visit the explicit waiters which use condvars and are resumable
2020-01-30 21:00:03 -06:00
if let Some(latch) = query.latch(query_map) {
for (i, waiter) in latch.info.lock().waiters.iter().enumerate() {
if let Some(waiter_query) = waiter.query {
if visit(waiter.span, waiter_query).is_some() {
// Return a value which indicates that this waiter can be resumed
return Some(Some((query, i)));
}
}
}
}
2020-01-30 21:00:03 -06:00
None
}
2018-05-27 06:05:41 -05:00
/// Look for query cycles by doing a depth first search starting at `query`.
/// `span` is the reason for the `query` to execute. This is initially DUMMY_SP.
/// If a cycle is detected, this initial value is replaced with the span causing
/// the cycle.
#[cfg(parallel_compiler)]
2019-12-22 16:42:04 -06:00
fn cycle_check<'tcx>(
2020-01-30 21:00:03 -06:00
query_map: &QueryMap<'tcx>,
2020-03-18 14:30:02 -05:00
query: QueryJobId<DepKind>,
2019-12-22 16:42:04 -06:00
span: Span,
2020-03-18 14:30:02 -05:00
stack: &mut Vec<(Span, QueryJobId<DepKind>)>,
visited: &mut FxHashSet<QueryJobId<DepKind>>,
2020-01-30 21:00:03 -06:00
) -> Option<Option<Waiter>> {
if !visited.insert(query) {
return if let Some(p) = stack.iter().position(|q| q.1 == query) {
2018-05-27 06:05:41 -05:00
// We detected a query cycle, fix up the initial span and return Some
// Remove previous stack entries
stack.drain(0..p);
// Replace the span for the first query with the cycle cause
stack[0].0 = span;
Some(None)
} else {
None
2019-12-22 16:42:04 -06:00
};
}
// Query marked as visited is added it to the stack
2020-01-30 21:00:03 -06:00
stack.push((span, query));
2018-05-27 06:05:41 -05:00
// Visit all the waiters
2020-01-30 21:00:03 -06:00
let r = visit_waiters(query_map, query, |span, successor| {
cycle_check(query_map, successor, span, stack, visited)
});
2018-05-27 06:05:41 -05:00
// Remove the entry in our stack if we didn't find a cycle
if r.is_none() {
stack.pop();
}
r
}
2018-05-27 06:05:41 -05:00
/// Finds out if there's a path to the compiler root (aka. code which isn't in a query)
/// from `query` without going through any of the queries in `visited`.
/// This is achieved with a depth first search.
#[cfg(parallel_compiler)]
fn connected_to_root<'tcx>(
2020-01-30 21:00:03 -06:00
query_map: &QueryMap<'tcx>,
2020-03-18 14:30:02 -05:00
query: QueryJobId<DepKind>,
visited: &mut FxHashSet<QueryJobId<DepKind>>,
) -> bool {
// We already visited this or we're deliberately ignoring it
2020-01-30 21:00:03 -06:00
if !visited.insert(query) {
return false;
}
// This query is connected to the root (it has no query parent), return true
2020-01-30 21:00:03 -06:00
if query.parent(query_map).is_none() {
return true;
}
2020-01-30 21:00:03 -06:00
visit_waiters(query_map, query, |_, successor| {
connected_to_root(query_map, successor, visited).then_some(None)
})
.is_some()
}
// Deterministically pick an query from a list
#[cfg(parallel_compiler)]
2020-03-18 14:30:02 -05:00
fn pick_query<'a, 'tcx, T, F: Fn(&T) -> (Span, QueryJobId<DepKind>)>(
2020-01-30 21:00:03 -06:00
query_map: &QueryMap<'tcx>,
2019-06-13 16:48:52 -05:00
tcx: TyCtxt<'tcx>,
queries: &'a [T],
f: F,
) -> &'a T {
// Deterministically pick an entry point
// FIXME: Sort this instead
let mut hcx = tcx.create_stable_hashing_context();
2019-12-22 16:42:04 -06:00
queries
.iter()
.min_by_key(|v| {
let (span, query) = f(v);
let mut stable_hasher = StableHasher::new();
2020-01-30 21:00:03 -06:00
query.query(query_map).hash_stable(&mut hcx, &mut stable_hasher);
2019-12-22 16:42:04 -06:00
// Prefer entry points which have valid spans for nicer error messages
// We add an integer to the tuple ensuring that entry points
// with valid spans are picked first
let span_cmp = if span == DUMMY_SP { 1 } else { 0 };
(span_cmp, stable_hasher.finish::<u64>())
})
.unwrap()
}
2018-05-27 06:05:41 -05:00
/// Looks for query cycles starting from the last query in `jobs`.
/// If a cycle is found, all queries in the cycle is removed from `jobs` and
/// the function return true.
/// If a cycle was not found, the starting query is removed from `jobs` and
/// the function returns false.
#[cfg(parallel_compiler)]
fn remove_cycle<'tcx>(
2020-01-30 21:00:03 -06:00
query_map: &QueryMap<'tcx>,
2020-03-18 14:30:02 -05:00
jobs: &mut Vec<QueryJobId<DepKind>>,
2020-03-08 12:20:18 -05:00
wakelist: &mut Vec<Lrc<QueryWaiter<TyCtxt<'tcx>>>>,
2019-06-13 16:48:52 -05:00
tcx: TyCtxt<'tcx>,
2018-05-27 06:05:41 -05:00
) -> bool {
let mut visited = FxHashSet::default();
let mut stack = Vec::new();
2018-05-27 06:05:41 -05:00
// Look for a cycle starting with the last query in `jobs`
2020-01-30 21:00:03 -06:00
if let Some(waiter) =
cycle_check(query_map, jobs.pop().unwrap(), DUMMY_SP, &mut stack, &mut visited)
{
// The stack is a vector of pairs of spans and queries; reverse it so that
// the earlier entries require later entries
let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().rev().unzip();
2018-05-27 06:05:41 -05:00
// Shift the spans so that queries are matched with the span for their waitee
spans.rotate_right(1);
2018-05-27 06:05:41 -05:00
// Zip them back together
let mut stack: Vec<_> = spans.into_iter().zip(queries).collect();
// Remove the queries in our cycle from the list of jobs to look at
for r in &stack {
2020-01-30 21:00:03 -06:00
jobs.remove_item(&r.1);
}
// Find the queries in the cycle which are
// connected to queries outside the cycle
2019-12-22 16:42:04 -06:00
let entry_points = stack
.iter()
2020-01-30 21:00:03 -06:00
.filter_map(|&(span, query)| {
if query.parent(query_map).is_none() {
2019-12-22 16:42:04 -06:00
// This query is connected to the root (it has no query parent)
2020-01-30 21:00:03 -06:00
Some((span, query, None))
} else {
2019-12-22 16:42:04 -06:00
let mut waiters = Vec::new();
// Find all the direct waiters who lead to the root
2020-01-30 21:00:03 -06:00
visit_waiters(query_map, query, |span, waiter| {
2019-12-22 16:42:04 -06:00
// Mark all the other queries in the cycle as already visited
2020-01-30 21:00:03 -06:00
let mut visited = FxHashSet::from_iter(stack.iter().map(|q| q.1));
2019-12-22 16:42:04 -06:00
2020-01-30 21:00:03 -06:00
if connected_to_root(query_map, waiter, &mut visited) {
2019-12-22 16:42:04 -06:00
waiters.push((span, waiter));
}
None
});
if waiters.is_empty() {
None
} else {
// Deterministically pick one of the waiters to show to the user
2020-01-30 21:00:03 -06:00
let waiter = *pick_query(query_map, tcx, &waiters, |s| *s);
Some((span, query, Some(waiter)))
2019-12-22 16:42:04 -06:00
}
}
2019-12-22 16:42:04 -06:00
})
2020-03-18 14:30:02 -05:00
.collect::<Vec<(Span, QueryJobId<DepKind>, Option<(Span, QueryJobId<DepKind>)>)>>();
// Deterministically pick an entry point
2020-01-30 21:00:03 -06:00
let (_, entry_point, usage) = pick_query(query_map, tcx, &entry_points, |e| (e.0, e.1));
// Shift the stack so that our entry point is first
2020-01-30 21:00:03 -06:00
let entry_point_pos = stack.iter().position(|(_, query)| query == entry_point);
if let Some(pos) = entry_point_pos {
stack.rotate_left(pos);
}
2020-01-30 21:00:03 -06:00
let usage = usage.as_ref().map(|(span, query)| (*span, query.query(query_map)));
2018-05-27 06:05:41 -05:00
// Create the cycle error
let error = CycleError {
usage,
2019-12-22 16:42:04 -06:00
cycle: stack
.iter()
2020-01-30 21:00:03 -06:00
.map(|&(s, ref q)| QueryInfo { span: s, query: q.query(query_map) })
2019-12-22 16:42:04 -06:00
.collect(),
};
2018-05-27 06:05:41 -05:00
// We unwrap `waiter` here since there must always be one
// edge which is resumeable / waited using a query latch
let (waitee_query, waiter_idx) = waiter.unwrap();
// Extract the waiter we want to resume
2020-01-30 21:00:03 -06:00
let waiter = waitee_query.latch(query_map).unwrap().extract_waiter(waiter_idx);
2018-05-27 06:05:41 -05:00
2018-05-31 13:24:56 -05:00
// Set the cycle error so it will be picked up when resumed
*waiter.cycle.lock() = Some(error);
2018-05-27 06:05:41 -05:00
// Put the waiter on the list of things to resume
wakelist.push(waiter);
true
} else {
false
}
}
2018-05-27 06:05:41 -05:00
/// Creates a new thread and forwards information in thread locals to it.
/// The new thread runs the deadlock handler.
/// Must only be called when a deadlock is about to happen.
#[cfg(parallel_compiler)]
pub unsafe fn handle_deadlock() {
let registry = rayon_core::Registry::current();
2019-12-22 16:42:04 -06:00
let gcx_ptr = tls::GCX_PTR.with(|gcx_ptr| gcx_ptr as *const _);
let gcx_ptr = &*gcx_ptr;
let rustc_span_globals =
rustc_span::GLOBALS.with(|rustc_span_globals| rustc_span_globals as *const _);
let rustc_span_globals = &*rustc_span_globals;
let syntax_globals = rustc_ast::attr::GLOBALS.with(|syntax_globals| syntax_globals as *const _);
2019-12-25 12:41:30 -06:00
let syntax_globals = &*syntax_globals;
thread::spawn(move || {
tls::GCX_PTR.set(gcx_ptr, || {
rustc_ast::attr::GLOBALS.set(syntax_globals, || {
rustc_span::GLOBALS
.set(rustc_span_globals, || tls::with_global(|tcx| deadlock(tcx, &registry)))
2019-12-25 12:41:30 -06:00
});
})
});
}
2018-05-27 06:05:41 -05:00
/// Detects query cycles by using depth first search over all active query jobs.
/// If a query cycle is found it will break the cycle by finding an edge which
/// uses a query latch and then resuming that waiter.
/// There may be multiple cycles involved in a deadlock, so this searches
/// all active queries for cycles before finally resuming all the waiters at once.
#[cfg(parallel_compiler)]
2019-06-13 16:48:52 -05:00
fn deadlock(tcx: TyCtxt<'_>, registry: &rayon_core::Registry) {
let on_panic = OnDrop(|| {
eprintln!("deadlock handler panicked, aborting process");
process::abort();
});
let mut wakelist = Vec::new();
2020-01-30 21:00:03 -06:00
let query_map = tcx.queries.try_collect_active_jobs().unwrap();
2020-03-18 14:30:02 -05:00
let mut jobs: Vec<QueryJobId<DepKind>> = query_map.keys().cloned().collect();
2018-05-27 06:05:41 -05:00
let mut found_cycle = false;
while jobs.len() > 0 {
2020-01-30 21:00:03 -06:00
if remove_cycle(&query_map, &mut jobs, &mut wakelist, tcx) {
2018-05-27 06:05:41 -05:00
found_cycle = true;
}
}
2018-05-27 06:05:41 -05:00
// Check that a cycle was found. It is possible for a deadlock to occur without
// a query cycle if a query which can be waited on uses Rayon to do multithreading
// internally. Such a query (X) may be executing on 2 threads (A and B) and A may
// wait using Rayon on B. Rayon may then switch to executing another query (Y)
// which in turn will wait on X causing a deadlock. We have a false dependency from
// X to Y due to Rayon waiting and a true dependency from Y to X. The algorithm here
// only considers the true dependency and won't detect a cycle.
assert!(found_cycle);
// FIXME: Ensure this won't cause a deadlock before we return
for waiter in wakelist.into_iter() {
2018-05-31 13:24:56 -05:00
waiter.notify(registry);
}
2018-05-27 00:47:44 -05:00
on_panic.disable();
}