Skip to content

Commit 98a43ca

Browse files
authored
Rollup merge of #71392 - ecstatic-morse:body-predecessor-cache-arc, r=nikomatsakis
Don't hold the predecessor cache lock longer than necessary #71044 returns a `LockGuard` with the predecessor cache to callers of `Body::predecessors`. As a result, the lock around the predecessor cache could be held for an arbitrarily long time. This PR uses reference counting for ownership of the predecessor cache, meaning the lock is only ever held within `PredecessorCache::compute`. Checking this API for potential sources of deadlock is much easier now, since we no longer have to consider its consumers, only its internals. This required removing `predecessors_for`, since there is no equivalent to `LockGuard::map` for `Arc` and `Rc`. I believe this could be emulated with `owning_ref::{Arc,Rc}Ref`, but I don't think it's necessary. Also, we continue to return an opaque type from `Body::predecessors` with the lifetime of the `Body`, not `'static`. This depends on #71044. Only the last two commits are new. r? @nikomatsakis
2 parents b964451 + 34dfbc3 commit 98a43ca

File tree

6 files changed

+35
-35
lines changed

6 files changed

+35
-35
lines changed

src/librustc_codegen_ssa/mir/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
157157
let cleanup_kinds = analyze::cleanup_kinds(&mir);
158158
// Allocate a `Block` for every basic block, except
159159
// the start block, if nothing loops back to it.
160-
let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty();
160+
let reentrant_start_block = !mir.predecessors()[mir::START_BLOCK].is_empty();
161161
let block_bxs: IndexVec<mir::BasicBlock, Bx::BasicBlock> = mir
162162
.basic_blocks()
163163
.indices()

src/librustc_middle/mir/mod.rs

+2-13
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,12 @@ use rustc_ast::ast::Name;
2323
use rustc_data_structures::fx::FxHashSet;
2424
use rustc_data_structures::graph::dominators::{dominators, Dominators};
2525
use rustc_data_structures::graph::{self, GraphSuccessors};
26-
use rustc_data_structures::sync::MappedLockGuard;
2726
use rustc_index::bit_set::BitMatrix;
2827
use rustc_index::vec::{Idx, IndexVec};
2928
use rustc_macros::HashStable;
3029
use rustc_serialize::{Decodable, Encodable};
3130
use rustc_span::symbol::Symbol;
3231
use rustc_span::{Span, DUMMY_SP};
33-
use smallvec::SmallVec;
3432
use std::borrow::Cow;
3533
use std::fmt::{self, Debug, Display, Formatter, Write};
3634
use std::ops::{Index, IndexMut};
@@ -170,7 +168,7 @@ pub struct Body<'tcx> {
170168
/// FIXME(oli-obk): rewrite the promoted during promotion to eliminate the cell components.
171169
pub ignore_interior_mut_in_const_validation: bool,
172170

173-
pub predecessor_cache: PredecessorCache,
171+
predecessor_cache: PredecessorCache,
174172
}
175173

176174
impl<'tcx> Body<'tcx> {
@@ -398,15 +396,6 @@ impl<'tcx> Body<'tcx> {
398396
Location { block: bb, statement_index: self[bb].statements.len() }
399397
}
400398

401-
#[inline]
402-
pub fn predecessors_for(
403-
&self,
404-
bb: BasicBlock,
405-
) -> impl std::ops::Deref<Target = SmallVec<[BasicBlock; 4]>> + '_ {
406-
let predecessors = self.predecessor_cache.compute(&self.basic_blocks);
407-
MappedLockGuard::map(predecessors, |preds| &mut preds[bb])
408-
}
409-
410399
#[inline]
411400
pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
412401
self.predecessor_cache.compute(&self.basic_blocks)
@@ -2684,7 +2673,7 @@ impl graph::GraphPredecessors<'graph> for Body<'tcx> {
26842673
impl graph::WithPredecessors for Body<'tcx> {
26852674
#[inline]
26862675
fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2687-
self.predecessors_for(node).clone().into_iter()
2676+
self.predecessors()[node].clone().into_iter()
26882677
}
26892678
}
26902679

src/librustc_middle/mir/predecessors.rs

+29-18
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
//! Lazily compute the reverse control-flow graph for the MIR.
2+
13
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
2-
use rustc_data_structures::sync::{Lock, LockGuard, MappedLockGuard};
4+
use rustc_data_structures::sync::{Lock, Lrc};
35
use rustc_index::vec::IndexVec;
46
use rustc_serialize as serialize;
57
use smallvec::SmallVec;
@@ -10,40 +12,49 @@ use crate::mir::{BasicBlock, BasicBlockData};
1012
pub type Predecessors = IndexVec<BasicBlock, SmallVec<[BasicBlock; 4]>>;
1113

1214
#[derive(Clone, Debug)]
13-
pub struct PredecessorCache {
14-
cache: Lock<Option<Predecessors>>,
15+
pub(super) struct PredecessorCache {
16+
cache: Lock<Option<Lrc<Predecessors>>>,
1517
}
1618

1719
impl PredecessorCache {
1820
#[inline]
19-
pub fn new() -> Self {
21+
pub(super) fn new() -> Self {
2022
PredecessorCache { cache: Lock::new(None) }
2123
}
2224

25+
/// Invalidates the predecessor cache.
26+
///
27+
/// Invalidating the predecessor cache requires mutating the MIR, which in turn requires a
28+
/// unique reference (`&mut`) to the `mir::Body`. Because of this, we can assume that all
29+
/// callers of `invalidate` have a unique reference to the MIR and thus to the predecessor
30+
/// cache. This means we don't actually need to take a lock when `invalidate` is called.
2331
#[inline]
24-
pub fn invalidate(&mut self) {
32+
pub(super) fn invalidate(&mut self) {
2533
*self.cache.get_mut() = None;
2634
}
2735

36+
/// Returns a ref-counted smart pointer containing the predecessor graph for this MIR.
37+
///
38+
/// We use ref-counting instead of a mapped `LockGuard` here to ensure that the lock for
39+
/// `cache` is only held inside this function. As long as no other locks are taken while
40+
/// computing the predecessor graph, deadlock is impossible.
2841
#[inline]
29-
pub fn compute(
42+
pub(super) fn compute(
3043
&self,
3144
basic_blocks: &IndexVec<BasicBlock, BasicBlockData<'_>>,
32-
) -> MappedLockGuard<'_, Predecessors> {
33-
LockGuard::map(self.cache.lock(), |cache| {
34-
cache.get_or_insert_with(|| {
35-
let mut preds = IndexVec::from_elem(SmallVec::new(), basic_blocks);
36-
for (bb, data) in basic_blocks.iter_enumerated() {
37-
if let Some(term) = &data.terminator {
38-
for &succ in term.successors() {
39-
preds[succ].push(bb);
40-
}
45+
) -> Lrc<Predecessors> {
46+
Lrc::clone(self.cache.lock().get_or_insert_with(|| {
47+
let mut preds = IndexVec::from_elem(SmallVec::new(), basic_blocks);
48+
for (bb, data) in basic_blocks.iter_enumerated() {
49+
if let Some(term) = &data.terminator {
50+
for &succ in term.successors() {
51+
preds[succ].push(bb);
4152
}
4253
}
54+
}
4355

44-
preds
45-
})
46-
})
56+
Lrc::new(preds)
57+
}))
4758
}
4859
}
4960

src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1269,7 +1269,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
12691269
location: Location,
12701270
) -> impl Iterator<Item = Location> + 'a {
12711271
if location.statement_index == 0 {
1272-
let predecessors = body.predecessors_for(location.block).to_vec();
1272+
let predecessors = body.predecessors()[location.block].to_vec();
12731273
Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb)))
12741274
} else {
12751275
Either::Right(std::iter::once(Location {

src/librustc_mir/borrow_check/region_infer/values.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ impl RegionValueElements {
8989
// If this is a basic block head, then the predecessors are
9090
// the terminators of other basic blocks
9191
stack.extend(
92-
body.predecessors_for(block)
92+
body.predecessors()[block]
9393
.iter()
9494
.map(|&pred_bb| body.terminator_loc(pred_bb))
9595
.map(|pred_loc| self.point_from_location(pred_loc)),

src/librustc_mir/borrow_check/type_check/liveness/trace.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ impl LivenessResults<'me, 'typeck, 'flow, 'tcx> {
303303
}
304304

305305
let body = self.cx.body;
306-
for &pred_block in body.predecessors_for(block).iter() {
306+
for &pred_block in body.predecessors()[block].iter() {
307307
debug!("compute_drop_live_points_for_block: pred_block = {:?}", pred_block,);
308308

309309
// Check whether the variable is (at least partially)

0 commit comments

Comments
 (0)