Skip to content

Commit b04a787

Browse files
committed
Compute block costs lazily.
1 parent 5854bec commit b04a787

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

compiler/rustc_mir_transform/src/jump_threading.rs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
//! Applying the optimisation can create a lot of new MIR, so we bound the instruction
3131
//! cost by `MAX_COST`.
3232
33+
use std::cell::OnceCell;
34+
3335
use rustc_arena::DroplessArena;
3436
use rustc_const_eval::const_eval::DummyMachine;
3537
use rustc_const_eval::interpret::{ImmTy, Immediate, InterpCx, OpTy, Projectable};
@@ -81,15 +83,7 @@ impl<'tcx> crate::MirPass<'tcx> for JumpThreading {
8183
loop_headers: loop_headers(body),
8284
entry_states: IndexVec::from_elem(ConditionSet::BOTTOM, &body.basic_blocks),
8385
opportunities: Vec::new(),
84-
costs: body
85-
.basic_blocks
86-
.iter_enumerated()
87-
.map(|(bb, bbdata)| {
88-
let mut cost = CostChecker::new(tcx, typing_env, None, body);
89-
cost.visit_basic_block_data(bb, bbdata);
90-
cost.cost()
91-
})
92-
.collect(),
86+
costs: IndexVec::from_elem(OnceCell::new(), &body.basic_blocks),
9387
};
9488

9589
for (bb, bbdata) in traversal::postorder(body) {
@@ -165,7 +159,7 @@ struct TOFinder<'a, 'tcx> {
165159
arena: &'a DroplessArena,
166160
opportunities: Vec<ThreadingOpportunity>,
167161
/// Pre-computed cost of duplicating each block.
168-
costs: IndexVec<BasicBlock, usize>,
162+
costs: IndexVec<BasicBlock, OnceCell<usize>>,
169163
}
170164

171165
/// Singly-linked list to represent chains of blocks. This is cheap to copy, and is converted to
@@ -333,13 +327,22 @@ impl<'a, 'tcx> TOFinder<'a, 'tcx> {
333327
cond.chain = BBChain::cons(self.arena, bb, cond.chain);
334328
// Remove conditions for which the duplication cost is too high.
335329
// This is required to keep the size of the `ConditionSet` tractable.
336-
let cost = cond.cost + self.costs[head];
330+
let cost = cond.cost + self.cost(head);
337331
cond.cost = cost;
338332
cost <= MAX_COST
339333
});
340334
ConditionSet(state)
341335
}
342336

337+
fn cost(&self, bb: BasicBlock) -> usize {
338+
*self.costs[bb].get_or_init(|| {
339+
let bbdata = &self.body[bb];
340+
let mut cost = CostChecker::new(self.tcx, self.typing_env, None, self.body);
341+
cost.visit_basic_block_data(bb, bbdata);
342+
cost.cost()
343+
})
344+
}
345+
343346
/// Remove all conditions in the state that alias given place.
344347
fn flood_state(
345348
&self,

0 commit comments

Comments
 (0)