| 1 |
// Copyright © 2023 Collabora, Ltd. |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
use crate::ir::*; |
| 5 |
use crate::union_find::UnionFind; |
| 6 |
|
| 7 |
use compiler::bitset::BitSet; |
| 8 |
use rustc_hash::{FxBuildHasher, FxHashMap}; |
| 9 |
use std::cell::RefCell; |
| 10 |
use std::cmp::Reverse; |
| 11 |
use std::collections::BinaryHeap; |
| 12 |
|
| 13 |
struct PhiTracker { |
| 14 |
phi: Phi, |
| 15 |
orig: SSAValue, |
| 16 |
dst: SSAValue, |
| 17 |
srcs: FxHashMap<usize, SSAValue>, |
| 18 |
} |
| 19 |
|
| 20 |
struct DefTrackerBlock { |
| 21 |
pred: Vec<usize>, |
| 22 |
succ: Vec<usize>, |
| 23 |
defs: RefCell<FxHashMap<SSAValue, SSAValue>>, |
| 24 |
phis: RefCell<Vec<PhiTracker>>, |
| 25 |
} |
| 26 |
|
| 27 |
fn get_ssa_or_phi( |
| 28 |
worklist: &mut BinaryHeap<Reverse<usize>>, |
| 29 |
ssa_alloc: &mut SSAValueAllocator, |
| 30 |
phi_alloc: &mut PhiAllocator, |
| 31 |
blocks: &[DefTrackerBlock], |
| 32 |
needs_src: &mut BitSet, |
| 33 |
b_idx: usize, |
| 34 |
ssa: SSAValue, |
| 35 |
) -> SSAValue { |
| 36 |
// Annoyingly, Rust stack sizes get to be a problem so we don't want to use |
| 37 |
// actual recursion here. Instead we use a worklist in the form of a binary |
| 38 |
// heap. Using a binary heap ensures that we process the earliest blocks |
| 39 |
// first. |
| 40 |
debug_assert!(worklist.is_empty()); |
| 41 |
worklist.push(Reverse(b_idx)); |
| 42 |
|
| 43 |
loop { |
| 44 |
let b_idx = worklist.peek().unwrap().0; |
| 45 |
let b = &blocks[b_idx]; |
| 46 |
|
| 47 |
if let Some(&b_ssa) = b.defs.borrow().get(&ssa) { |
| 48 |
// We already sorted this one out, pop the stack. |
| 49 |
worklist.pop(); |
| 50 |
if worklist.is_empty() { |
| 51 |
return b_ssa; |
| 52 |
} else { |
| 53 |
continue; |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
let mut pushed_pred = false; |
| 58 |
let mut pred_ssa = None; |
| 59 |
let mut all_same = true; |
| 60 |
for &p_idx in &b.pred { |
| 61 |
if p_idx >= b_idx { |
| 62 |
// This is a loop back-edge, add a phi just in case. We'll |
| 63 |
// remove it later if it's not needed |
| 64 |
all_same = false; |
| 65 |
} else if let Some(&p_ssa) = blocks[p_idx].defs.borrow().get(&ssa) { |
| 66 |
if *pred_ssa.get_or_insert(p_ssa) != p_ssa { |
| 67 |
all_same = false; |
| 68 |
} |
| 69 |
} else { |
| 70 |
worklist.push(Reverse(p_idx)); |
| 71 |
pushed_pred = true; |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
// If we pushed any predecessors to the stack, loop again to sort them |
| 76 |
// out before we try to sort out this block. |
| 77 |
if pushed_pred { |
| 78 |
continue; |
| 79 |
} |
| 80 |
|
| 81 |
// We now have everything we need to sort out this block |
| 82 |
let b_ssa = if all_same { |
| 83 |
pred_ssa.expect("Undefined value") |
| 84 |
} else { |
| 85 |
let phi = phi_alloc.alloc(); |
| 86 |
let phi_ssa = ssa_alloc.alloc(ssa.file()); |
| 87 |
let mut pt = PhiTracker { |
| 88 |
phi, |
| 89 |
orig: ssa, |
| 90 |
dst: phi_ssa, |
| 91 |
srcs: Default::default(), |
| 92 |
}; |
| 93 |
for &p_idx in &b.pred { |
| 94 |
if p_idx >= b_idx { |
| 95 |
needs_src.insert(p_idx); |
| 96 |
continue; |
| 97 |
} |
| 98 |
// Earlier iterations of the loop ensured this exists |
| 99 |
let p_ssa = *blocks[p_idx].defs.borrow().get(&ssa).unwrap(); |
| 100 |
pt.srcs.insert(p_idx, p_ssa); |
| 101 |
} |
| 102 |
blocks[b_idx].phis.borrow_mut().push(pt); |
| 103 |
phi_ssa |
| 104 |
}; |
| 105 |
|
| 106 |
blocks[b_idx].defs.borrow_mut().insert(ssa, b_ssa); |
| 107 |
worklist.pop(); |
| 108 |
if worklist.is_empty() { |
| 109 |
return b_ssa; |
| 110 |
} |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
fn get_or_insert_phi_dsts(bb: &mut BasicBlock) -> &mut OpPhiDsts { |
| 115 |
let ip = if let Some(ip) = bb.phi_dsts_ip() { |
| 116 |
ip |
| 117 |
} else { |
| 118 |
bb.instrs.insert(0, Instr::new(OpPhiDsts::new())); |
| 119 |
0 |
| 120 |
}; |
| 121 |
match &mut bb.instrs[ip].op { |
| 122 |
Op::PhiDsts(op) => op, |
| 123 |
_ => panic!("Expected to find the phi we just inserted"), |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
fn get_or_insert_phi_srcs(bb: &mut BasicBlock) -> &mut OpPhiSrcs { |
| 128 |
let ip = if let Some(ip) = bb.phi_srcs_ip() { |
| 129 |
ip |
| 130 |
} else if let Some(ip) = bb.branch_ip() { |
| 131 |
bb.instrs.insert(ip, Instr::new(OpPhiSrcs::new())); |
| 132 |
ip |
| 133 |
} else { |
| 134 |
bb.instrs.push(Instr::new(OpPhiSrcs::new())); |
| 135 |
bb.instrs.len() - 1 |
| 136 |
}; |
| 137 |
match &mut bb.instrs[ip].op { |
| 138 |
Op::PhiSrcs(op) => op, |
| 139 |
_ => panic!("Expected to find the phi we just inserted"), |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
impl Function { |
| 144 |
/// Repairs SSA form |
| 145 |
/// |
| 146 |
/// Certain passes such as register spilling may produce a program that is |
| 147 |
/// no longer in SSA form. This pass is able to repair SSA by inserting |
| 148 |
/// phis as needed. Even though we do not require dominance or that each |
| 149 |
/// value be defined once we do require that, for every use of an SSAValue |
| 150 |
/// and for every path from the start of the program to that use, there must |
| 151 |
/// be some definition of the value along that path. |
| 152 |
/// |
| 153 |
/// The algorithm implemented here is based on the one in "Simple and |
| 154 |
/// Efficient Construction of Static Single Assignment Form" by Braun, et. |
| 155 |
/// al. The primary difference between our implementation and the paper is |
| 156 |
/// that we can't rewrite the IR on-the-fly. Instead, we store everything |
| 157 |
/// in hash tables and handle removing redundant phis with back-edges as a |
| 158 |
/// separate pass between figuring out where phis are needed and actually |
| 159 |
/// constructing the phi instructions. |
| 160 |
pub fn repair_ssa(&mut self) { |
| 161 |
// First, count the number of defs for each SSA value. This will allow |
| 162 |
// us to skip any SSA values which only have a single definition in |
| 163 |
// later passes. |
| 164 |
let mut has_mult_defs = false; |
| 165 |
let mut num_defs = FxHashMap::default(); |
| 166 |
for b in &self.blocks { |
| 167 |
for instr in &b.instrs { |
| 168 |
instr.for_each_ssa_def(|ssa| { |
| 169 |
num_defs |
| 170 |
.entry(*ssa) |
| 171 |
.and_modify(|e| { |
| 172 |
has_mult_defs = true; |
| 173 |
*e += 1; |
| 174 |
}) |
| 175 |
.or_insert(1); |
| 176 |
}); |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
if !has_mult_defs { |
| 181 |
return; |
| 182 |
} |
| 183 |
|
| 184 |
let cfg = &mut self.blocks; |
| 185 |
let ssa_alloc = &mut self.ssa_alloc; |
| 186 |
let phi_alloc = &mut self.phi_alloc; |
| 187 |
|
| 188 |
let mut blocks = Vec::new(); |
| 189 |
let mut needs_src = BitSet::new(); |
| 190 |
let mut ssa_or_phi_worklist = BinaryHeap::new(); |
| 191 |
for b_idx in 0..cfg.len() { |
| 192 |
assert!(blocks.len() == b_idx); |
| 193 |
blocks.push(DefTrackerBlock { |
| 194 |
pred: cfg.pred_indices(b_idx).to_vec(), |
| 195 |
succ: cfg.succ_indices(b_idx).to_vec(), |
| 196 |
defs: RefCell::new(Default::default()), |
| 197 |
phis: RefCell::new(Vec::new()), |
| 198 |
}); |
| 199 |
|
| 200 |
for instr in &mut cfg[b_idx].instrs { |
| 201 |
instr.for_each_ssa_use_mut(|ssa| { |
| 202 |
if num_defs.get(ssa).cloned().unwrap_or(0) > 1 { |
| 203 |
*ssa = get_ssa_or_phi( |
| 204 |
&mut ssa_or_phi_worklist, |
| 205 |
ssa_alloc, |
| 206 |
phi_alloc, |
| 207 |
&blocks, |
| 208 |
&mut needs_src, |
| 209 |
b_idx, |
| 210 |
*ssa, |
| 211 |
); |
| 212 |
} |
| 213 |
}); |
| 214 |
|
| 215 |
instr.for_each_ssa_def_mut(|ssa| { |
| 216 |
if num_defs.get(ssa).cloned().unwrap_or(0) > 1 { |
| 217 |
let new_ssa = ssa_alloc.alloc(ssa.file()); |
| 218 |
blocks[b_idx].defs.borrow_mut().insert(*ssa, new_ssa); |
| 219 |
*ssa = new_ssa; |
| 220 |
} |
| 221 |
}); |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
// Populate phi sources for any back-edges |
| 226 |
loop { |
| 227 |
let Some(b_idx) = needs_src.iter().next() else { |
| 228 |
break; |
| 229 |
}; |
| 230 |
needs_src.remove(b_idx); |
| 231 |
|
| 232 |
for s_idx in &blocks[b_idx].succ { |
| 233 |
if *s_idx <= b_idx { |
| 234 |
let s = &blocks[*s_idx]; |
| 235 |
|
| 236 |
// We do a mutable borrow here. The algorithm is recursive |
| 237 |
// and may insert phis into other blocks. However, because |
| 238 |
// this is phi exists, its destination should be in the def |
| 239 |
// set for s and so no new phis should need to be added. |
| 240 |
// RefCell's dynamic borrow checks will assert this. |
| 241 |
for phi in s.phis.borrow_mut().iter_mut() { |
| 242 |
phi.srcs.entry(b_idx).or_insert_with(|| { |
| 243 |
get_ssa_or_phi( |
| 244 |
&mut ssa_or_phi_worklist, |
| 245 |
ssa_alloc, |
| 246 |
phi_alloc, |
| 247 |
&blocks, |
| 248 |
&mut needs_src, |
| 249 |
b_idx, |
| 250 |
phi.orig, |
| 251 |
) |
| 252 |
}); |
| 253 |
} |
| 254 |
} |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
// For loop back-edges, we inserted a phi whether we need one or not. |
| 259 |
// We want to eliminate any redundant phis. |
| 260 |
let mut ssa_map = UnionFind::<SSAValue, FxBuildHasher>::new(); |
| 261 |
if cfg.has_loop() { |
| 262 |
let mut to_do = true; |
| 263 |
while to_do { |
| 264 |
to_do = false; |
| 265 |
for b_idx in 0..cfg.len() { |
| 266 |
let b = &blocks[b_idx]; |
| 267 |
b.phis.borrow_mut().retain_mut(|phi| { |
| 268 |
let mut ssa = None; |
| 269 |
for (_, p_ssa) in phi.srcs.iter_mut() { |
| 270 |
// Apply the remap to the phi sources so that we |
| 271 |
// pick up any remaps from previous loop iterations. |
| 272 |
*p_ssa = ssa_map.find(*p_ssa); |
| 273 |
|
| 274 |
if *p_ssa == phi.dst { |
| 275 |
continue; |
| 276 |
} |
| 277 |
if *ssa.get_or_insert(*p_ssa) != *p_ssa { |
| 278 |
// Multiple unique sources |
| 279 |
return true; |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
// All sources are identical or the phi destination so |
| 284 |
// we can delete this phi and add it to the remap |
| 285 |
let ssa = ssa.expect("Circular SSA def"); |
| 286 |
// union(a, b) ensures that the representative is the representative |
| 287 |
// for a. This means union(ssa, phi.dst) ensures that phi.dst gets |
| 288 |
// mapped to ssa, not the other way around. |
| 289 |
ssa_map.union(ssa, phi.dst); |
| 290 |
to_do = true; |
| 291 |
false |
| 292 |
}); |
| 293 |
} |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
// Now we apply the remap to instruction sources and place the actual |
| 298 |
// phis |
| 299 |
for b_idx in 0..cfg.len() { |
| 300 |
// Grab the successor index for inserting OpPhiSrc before we take a |
| 301 |
// mutable reference to the CFG. There are no critical edges so we |
| 302 |
// can only have an OpPhiSrc if there is a single successor. |
| 303 |
let succ = cfg.succ_indices(b_idx); |
| 304 |
let s_idx = if succ.len() == 1 { |
| 305 |
Some(succ[0]) |
| 306 |
} else { |
| 307 |
for s_idx in succ { |
| 308 |
debug_assert!(blocks[*s_idx].phis.borrow().is_empty()); |
| 309 |
} |
| 310 |
None |
| 311 |
}; |
| 312 |
|
| 313 |
let bb = &mut cfg[b_idx]; |
| 314 |
|
| 315 |
// First we have phi destinations |
| 316 |
let b_phis = blocks[b_idx].phis.borrow(); |
| 317 |
if !b_phis.is_empty() { |
| 318 |
let phi_dst = get_or_insert_phi_dsts(bb); |
| 319 |
for pt in b_phis.iter() { |
| 320 |
phi_dst.dsts.push(pt.phi, pt.dst.into()); |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
// Fix up any remapped SSA values in sources |
| 325 |
if !ssa_map.is_empty() { |
| 326 |
for instr in &mut bb.instrs { |
| 327 |
instr.for_each_ssa_use_mut(|ssa| { |
| 328 |
*ssa = ssa_map.find(*ssa); |
| 329 |
}); |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
if let Some(s_idx) = s_idx { |
| 334 |
let s_phis = blocks[s_idx].phis.borrow(); |
| 335 |
if !s_phis.is_empty() { |
| 336 |
let phi_src = get_or_insert_phi_srcs(bb); |
| 337 |
for pt in s_phis.iter() { |
| 338 |
let mut ssa = *pt.srcs.get(&b_idx).unwrap(); |
| 339 |
ssa = ssa_map.find(ssa); |
| 340 |
phi_src.srcs.push(pt.phi, ssa.into()); |
| 341 |
} |
| 342 |
} |
| 343 |
} |
| 344 |
} |
| 345 |
} |
| 346 |
} |