| @@ -0,0 +1,1009 @@ |
| 1 | +//! The simplifier (issue #196, ADR 0043): inlining, beta reduction, |
| 2 | +//! case-of-known-constructor, dead-let elimination, let sinking and copy |
| 3 | +//! propagation, per function, to a fixed point with a budget. |
| 4 | +//! |
| 5 | +//! It runs before TRMC and Perceus, so it never sees `CtxExtend`, |
| 6 | +//! `CtxApply`, `Dup`, `Drop`, `Release` or `Reuse`: those passes' |
| 7 | +//! invariants are unaffected. Only pure values — atoms, projections, |
| 8 | +//! primitives, constructions, tuples and closures, which no run of the |
| 9 | +//! program can observe — are removed or moved, and they never cross a |
| 10 | +//! call, a `perform` or a `handle`: effects keep their order, and the |
| 11 | +//! yield checks the C backend inserts later come after that order is |
| 12 | +//! fixed. Tail calls stay tail calls (ADR 0003): a call in tail position |
| 13 | +//! is inlined with its body's returns (and `exit`s) in place, and no |
| 14 | +//! other call gains a continuation. |
| 15 | +//! |
| 16 | +//! Variables are unique within a function (Core is in A-normal form with |
| 17 | +//! fresh names), so what is known about a variable holds wherever it is |
| 18 | +//! in scope, and one map serves every branch. |
| 19 | + |
| 20 | +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; |
| 21 | +use std::rc::Rc; |
| 22 | + |
| 23 | +use crate::ir::{Atom, Expr, FnId, Program, Span, Value, VarId}; |
| 24 | + |
| 25 | +/// A function of at most this many nodes is inlinable at any site. |
| 26 | +const SMALL_NODES: u32 = 12; |
| 27 | +/// A bigger non-recursive function is inlinable only where its result is |
| 28 | +/// the caller's (a tail site): nothing after the call is duplicated then. |
| 29 | +const TAIL_NODES: u32 = 32; |
| 30 | +/// Rounds of rewriting: the fixed point of the rewrites, capped (one |
| 31 | +/// round can expose another — a known constructor behind an inlined call, |
| 32 | +/// say). |
| 33 | +const MAX_ROUNDS: u32 = 4; |
| 34 | +/// Inlining into a function stops when it passes this many nodes, or this |
| 35 | +/// factor times where it started, whichever is larger: growth is bounded. |
| 36 | +const MAX_NODES: u32 = 512; |
| 37 | +const MAX_GROWTH: u32 = 4; |
| 38 | + |
| 39 | +/// Simplify the functions `live` of `program`, to the fixed point. |
| 40 | +pub fn run_in(program: &mut Program, live: &[FnId]) { |
| 41 | + // Growth is bounded over the whole pass, not per round: two functions |
| 42 | + // inlining into each other would otherwise grow on every round. |
| 43 | + let mut grown = vec![0u32; program.fns.len()]; |
| 44 | + let mut caps = vec![0u32; program.fns.len()]; |
| 45 | + for _ in 0..MAX_ROUNDS { |
| 46 | + let candidates = candidates(program); |
| 47 | + let mut changed = false; |
| 48 | + for &id in live { |
| 49 | + if caps[id as usize] == 0 { |
| 50 | + let size = size(&program.fns[id as usize].body); |
| 51 | + caps[id as usize] = MAX_NODES.max(MAX_GROWTH * size); |
| 52 | + } |
| 53 | + changed |= function( |
| 54 | + program, |
| 55 | + id, |
| 56 | + &candidates, |
| 57 | + &mut grown[id as usize], |
| 58 | + caps[id as usize], |
| 59 | + ); |
| 60 | + } |
| 61 | + if !changed { |
| 62 | + return; |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +/// Simplify one function; whether anything was rewritten. |
| 68 | +fn function( |
| 69 | + program: &mut Program, |
| 70 | + id: FnId, |
| 71 | + candidates: &HashMap<FnId, Candidate>, |
| 72 | + grown: &mut u32, |
| 73 | + cap: u32, |
| 74 | +) -> bool { |
| 75 | + let decl = &mut program.fns[id as usize]; |
| 76 | + let body = std::mem::replace(&mut decl.body, Expr::Return(Atom::Unit)); |
| 77 | + let mut s = Simplify { |
| 78 | + candidates, |
| 79 | + module: decl.module.as_deref().map(Rc::from), |
| 80 | + subst: HashMap::new(), |
| 81 | + known: HashMap::new(), |
| 82 | + next_var: decl.n_vars, |
| 83 | + shapes: std::mem::take(&mut decl.shapes), |
| 84 | + inlined: HashSet::from([id]), |
| 85 | + grown, |
| 86 | + cap, |
| 87 | + changed: false, |
| 88 | + }; |
| 89 | + let uses = uses(&body); |
| 90 | + let body = s.expr(body, &uses, true); |
| 91 | + let body = sweep(body, &mut s.changed); |
| 92 | + let changed = s.changed; |
| 93 | + let decl = &mut program.fns[id as usize]; |
| 94 | + decl.body = body; |
| 95 | + decl.n_vars = s.next_var; |
| 96 | + decl.shapes = s.shapes; |
| 97 | + if changed { |
| 98 | + let mut present = HashSet::new(); |
| 99 | + visit(&decl.body, &mut |a| { |
| 100 | + if let Atom::Var(v) = a { |
| 101 | + present.insert(*v); |
| 102 | + } |
| 103 | + }); |
| 104 | + decl.shapes.retain(|v, _| present.contains(v)); |
| 105 | + } |
| 106 | + changed |
| 107 | +} |
| 108 | + |
| 109 | +/// What is known at compile time about a variable's value. |
| 110 | +#[derive(Clone, Debug)] |
| 111 | +enum Known { |
| 112 | + /// A closure of this function with these captures. |
| 113 | + Closure(FnId, Vec<Atom>), |
| 114 | + /// A constructor's tag and fields. |
| 115 | + Construct(u32, Vec<Atom>), |
| 116 | + /// A tuple's fields. |
| 117 | + Tuple(Vec<Atom>), |
| 118 | +} |
| 119 | + |
| 120 | +/// How a function body's value reaches its caller. |
| 121 | +#[derive(Clone, Copy, PartialEq, Eq)] |
| 122 | +enum End { |
| 123 | + /// A chain of `let`s ending in a return. |
| 124 | + Return, |
| 125 | + /// A chain of `let`s ending in a panic: what followed the call is |
| 126 | + /// dead, so the body may replace it. |
| 127 | + Panic, |
| 128 | + /// Anything else (a switch, or an `exit` anywhere): inlining one at a |
| 129 | + /// non-tail site would duplicate the continuation or leave the wrong |
| 130 | + /// function. |
| 131 | + Other, |
| 132 | +} |
| 133 | + |
| 134 | +/// A function another may inline (any non-recursive one). |
| 135 | +#[derive(Clone)] |
| 136 | +struct Candidate { |
| 137 | + params: Vec<VarId>, |
| 138 | + body: Rc<Expr>, |
| 139 | + n_vars: u32, |
| 140 | + shapes: Rc<BTreeMap<VarId, Vec<u32>>>, |
| 141 | + /// The callee's module (its C unit, ADR 0029): inlining across |
| 142 | + /// modules would make a unit's C depend on another module's body, |
| 143 | + /// and an edit there would recompile it. Cross-module calls are |
| 144 | + /// specialisation's and fusion's business (issues #197, #198), whose |
| 145 | + /// copies have a unit of their own. |
| 146 | + module: Option<Rc<str>>, |
| 147 | + nodes: u32, |
| 148 | + end: End, |
| 149 | + has_exit: bool, |
| 150 | +} |
| 151 | + |
| 152 | +fn candidates(program: &Program) -> HashMap<FnId, Candidate> { |
| 153 | + program |
| 154 | + .fns |
| 155 | + .iter() |
| 156 | + .enumerate() |
| 157 | + .filter(|(id, f)| !recursive(&f.body, *id as FnId)) |
| 158 | + .map(|(id, f)| { |
| 159 | + ( |
| 160 | + id as FnId, |
| 161 | + Candidate { |
| 162 | + params: f.params.clone(), |
| 163 | + body: Rc::new(f.body.clone()), |
| 164 | + n_vars: f.n_vars, |
| 165 | + shapes: Rc::new(f.shapes.clone()), |
| 166 | + module: f.module.as_deref().map(Rc::from), |
| 167 | + nodes: size(&f.body), |
| 168 | + end: end_of(&f.body), |
| 169 | + has_exit: has_exit(&f.body), |
| 170 | + }, |
| 171 | + ) |
| 172 | + }) |
| 173 | + .collect() |
| 174 | +} |
| 175 | + |
| 176 | +struct Simplify<'a> { |
| 177 | + candidates: &'a HashMap<FnId, Candidate>, |
| 178 | + /// The function's own module: only same-module callees are inlined |
| 179 | + /// (Candidate::module). |
| 180 | + module: Option<Rc<str>>, |
| 181 | + /// Variables bound to atoms, to substitute (copy propagation). |
| 182 | + subst: HashMap<VarId, Atom>, |
| 183 | + known: HashMap<VarId, Known>, |
| 184 | + /// Fresh variables: the function's `n_vars`, growing as inlining |
| 185 | + /// brings a callee's variables in. |
| 186 | + next_var: u32, |
| 187 | + /// The function's `shapes` (ADR 0040), rewritten with it. |
| 188 | + shapes: BTreeMap<VarId, Vec<u32>>, |
| 189 | + /// The function itself and the functions already inlined at an |
| 190 | + /// enclosing point of this walk: never inlined again within it, so |
| 191 | + /// mutually recursive pairs terminate. |
| 192 | + inlined: HashSet<FnId>, |
| 193 | + /// Nodes inlined so far (over the whole pass), and the cap. |
| 194 | + grown: &'a mut u32, |
| 195 | + cap: u32, |
| 196 | + changed: bool, |
| 197 | +} |
| 198 | + |
| 199 | +impl Simplify<'_> { |
| 200 | + fn atom(&self, a: &Atom) -> Atom { |
| 201 | + match a { |
| 202 | + Atom::Var(v) => self.subst.get(v).cloned().unwrap_or_else(|| a.clone()), |
| 203 | + a => a.clone(), |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + fn atoms(&self, atoms: &[Atom]) -> Vec<Atom> { |
| 208 | + atoms.iter().map(|a| self.atom(a)).collect() |
| 209 | + } |
| 210 | + |
| 211 | + /// A chain of `let`s and its end. `exits_ok` is whether the chain is |
| 212 | + /// the function's own (not a block's): an inlined `exit` leaves the |
| 213 | + /// function, so only there is a body's `exit` the caller's (a |
| 214 | + /// `Return` is the enclosing block's value, ir.rs). |
| 215 | + fn expr(&mut self, e: Expr, uses: &HashMap<VarId, u32>, exits_ok: bool) -> Expr { |
| 216 | + let (lets, end) = split(e); |
| 217 | + let mut lets: VecDeque<(VarId, Value, Option<Span>)> = lets.into_iter().collect(); |
| 218 | + let mut end = end; |
| 219 | + let mut out: Vec<(VarId, Value, Option<Span>)> = Vec::new(); |
| 220 | + while let Some((v, value, span)) = lets.pop_front() { |
| 221 | + // A block that is a plain `let`-chain is structural nesting: |
| 222 | + // splice it (a block ending in a switch yields its value |
| 223 | + // through the branches' returns, so only chain ends flatten). |
| 224 | + if let Value::Block(b) = &value { |
| 225 | + let (blets, bend) = split((**b).clone()); |
| 226 | + if let Expr::Return(a) = bend { |
| 227 | + let mut pasted = blets; |
| 228 | + pasted.push((v, Value::Atom(a), span)); |
| 229 | + for item in pasted.into_iter().rev() { |
| 230 | + lets.push_front(item); |
| 231 | + } |
| 232 | + self.changed = true; |
| 233 | + continue; |
| 234 | + } |
| 235 | + } |
| 236 | + let mut value = self.value(value, uses); |
| 237 | + // Beta reduction: a call of a known closure becomes a direct |
| 238 | + // call (its captures come first, ir.rs's convention). |
| 239 | + let mut force = false; |
| 240 | + if let Value::Call(Atom::Var(f), args) = &value |
| 241 | + && let Some(Known::Closure(g, caps)) = self.known.get(f).cloned() |
| 242 | + { |
| 243 | + // A closure used exactly once: its function's size no |
| 244 | + // longer matters, inlining moves code instead of copying |
| 245 | + // it. |
| 246 | + force = uses.get(f) == Some(&1); |
| 247 | + let mut all = caps; |
| 248 | + all.extend(args.iter().cloned()); |
| 249 | + value = Value::CallFn(g, all); |
| 250 | + self.changed = true; |
| 251 | + } |
| 252 | + // Inlining. |
| 253 | + if let Value::CallFn(g, args) = &value |
| 254 | + && !self.inlined.contains(g) |
| 255 | + && let Some(cand) = self.candidates.get(g).cloned() |
| 256 | + && cand.module == self.module |
| 257 | + && cand.params.len() == args.len() |
| 258 | + { |
| 259 | + let tail_site = |
| 260 | + lets.is_empty() && matches!(&end, Expr::Return(Atom::Var(r)) if *r == v); |
| 261 | + let within = *self.grown + cand.nodes <= self.cap; |
| 262 | + let chain = matches!(cand.end, End::Return | End::Panic) && !cand.has_exit; |
| 263 | + let tail = tail_site |
| 264 | + && (exits_ok || !cand.has_exit) |
| 265 | + && (force || cand.nodes <= TAIL_NODES && within); |
| 266 | + let ok = if force { |
| 267 | + // Used exactly once, inlining moves code instead of |
| 268 | + // copying it: only the shape matters. |
| 269 | + chain || tail |
| 270 | + } else { |
| 271 | + (chain && cand.nodes <= SMALL_NODES && within) || tail |
| 272 | + }; |
| 273 | + if ok { |
| 274 | + *self.grown += cand.nodes; |
| 275 | + self.inlined.insert(*g); |
| 276 | + let (mut pasted, pend) = self.inline(&cand, args); |
| 277 | + self.inlined.remove(g); |
| 278 | + match pend { |
| 279 | + Expr::Return(a) => { |
| 280 | + pasted.push((v, Value::Atom(a), span)); |
| 281 | + for item in pasted.into_iter().rev() { |
| 282 | + lets.push_front(item); |
| 283 | + } |
| 284 | + } |
| 285 | + // A panic makes the rest dead; at a tail site the |
| 286 | + // rest was `return v`, which the body replaces. |
| 287 | + pend => { |
| 288 | + lets = pasted.into_iter().collect(); |
| 289 | + end = pend; |
| 290 | + } |
| 291 | + } |
| 292 | + self.changed = true; |
| 293 | + continue; |
| 294 | + } |
| 295 | + } |
| 296 | + // Copy propagation, and what is known about the value. |
| 297 | + match &value { |
| 298 | + Value::Atom(a) => { |
| 299 | + if let (Atom::Var(u), Some(shapes)) = (a, self.shapes.remove(&v)) { |
| 300 | + self.shapes.entry(*u).or_insert(shapes); |
| 301 | + } |
| 302 | + self.subst.insert(v, a.clone()); |
| 303 | + self.changed = true; |
| 304 | + continue; |
| 305 | + } |
| 306 | + Value::Closure(g, caps) => { |
| 307 | + self.known.insert(v, Known::Closure(*g, caps.clone())); |
| 308 | + } |
| 309 | + Value::Construct { tag, args, .. } => { |
| 310 | + self.known.insert(v, Known::Construct(*tag, args.clone())); |
| 311 | + } |
| 312 | + Value::Tuple(args) => { |
| 313 | + self.known.insert(v, Known::Tuple(args.clone())); |
| 314 | + } |
| 315 | + _ => { |
| 316 | + self.known.remove(&v); |
| 317 | + } |
| 318 | + } |
| 319 | + out.push((v, value, span)); |
| 320 | + } |
| 321 | + let end = self.end(end, uses, exits_ok); |
| 322 | + let mut expr = end; |
| 323 | + for (v, value, span) in out.into_iter().rev() { |
| 324 | + expr = Expr::Let(v, Box::new(value), Box::new(expr), span); |
| 325 | + } |
| 326 | + expr |
| 327 | + } |
| 328 | + |
| 329 | + /// The candidate's body renamed into this function (its parameters to |
| 330 | + /// the arguments, its other variables fresh), split into its `let`s |
| 331 | + /// and its end. |
| 332 | + fn inline( |
| 333 | + &mut self, |
| 334 | + cand: &Candidate, |
| 335 | + args: &[Atom], |
| 336 | + ) -> (Vec<(VarId, Value, Option<Span>)>, Expr) { |
| 337 | + let mut map: Vec<Option<Atom>> = vec![None; cand.n_vars as usize]; |
| 338 | + for (p, a) in cand.params.iter().zip(args) { |
| 339 | + map[*p as usize] = Some(a.clone()); |
| 340 | + } |
| 341 | + let mut next = self.next_var; |
| 342 | + for w in 0..cand.n_vars { |
| 343 | + if map[w as usize].is_none() { |
| 344 | + map[w as usize] = Some(Atom::Var(next)); |
| 345 | + next += 1; |
| 346 | + } |
| 347 | + } |
| 348 | + self.next_var = next; |
| 349 | + for (w, arities) in cand.shapes.iter() { |
| 350 | + if let Some(Atom::Var(u)) = &map[*w as usize] { |
| 351 | + self.shapes.entry(*u).or_insert_with(|| arities.clone()); |
| 352 | + } |
| 353 | + } |
| 354 | + let renamed = rename(&cand.body, &mut |w| { |
| 355 | + map[w as usize].clone().expect("every variable is mapped") |
| 356 | + }); |
| 357 | + split(renamed) |
| 358 | + } |
| 359 | + |
| 360 | + /// A chain's end: copy propagation, case-of-known-constructor, and |
| 361 | + /// the same treatment for the branches (which keep the chain's |
| 362 | + /// level: a top-level switch's branches are top-level too). |
| 363 | + fn end(&mut self, e: Expr, uses: &HashMap<VarId, u32>, exits_ok: bool) -> Expr { |
| 364 | + match e { |
| 365 | + Expr::Switch { on, cases, default } => { |
| 366 | + let on = self.atom(&on); |
| 367 | + let tag = match &on { |
| 368 | + Atom::Var(x) => match self.known.get(x) { |
| 369 | + Some(Known::Construct(tag, _)) => Some(*tag), |
| 370 | + _ => None, |
| 371 | + }, |
| 372 | + _ => None, |
| 373 | + }; |
| 374 | + if let Some(tag) = tag { |
| 375 | + let branch = cases |
| 376 | + .iter() |
| 377 | + .find(|(t, _)| *t == tag) |
| 378 | + .map(|(_, b)| b) |
| 379 | + .or(default.as_deref()); |
| 380 | + if let Some(branch) = branch { |
| 381 | + self.changed = true; |
| 382 | + return self.expr(branch.clone(), uses, exits_ok); |
| 383 | + } |
| 384 | + } |
| 385 | + Expr::Switch { |
| 386 | + on, |
| 387 | + cases: cases |
| 388 | + .into_iter() |
| 389 | + .map(|(t, b)| (t, self.expr(b, uses, exits_ok))) |
| 390 | + .collect(), |
| 391 | + default: default.map(|d| Box::new(self.expr(*d, uses, exits_ok))), |
| 392 | + } |
| 393 | + } |
| 394 | + Expr::SwitchLit { on, cases, default } => { |
| 395 | + let on = self.atom(&on); |
| 396 | + if let Atom::Lit(l) = &on { |
| 397 | + let branch = cases |
| 398 | + .iter() |
| 399 | + .find(|(c, _)| c == l) |
| 400 | + .map(|(_, b)| b) |
| 401 | + .unwrap_or(&default); |
| 402 | + self.changed = true; |
| 403 | + return self.expr(branch.clone(), uses, exits_ok); |
| 404 | + } |
| 405 | + Expr::SwitchLit { |
| 406 | + on, |
| 407 | + cases: cases |
| 408 | + .into_iter() |
| 409 | + .map(|(c, b)| (c, self.expr(b, uses, exits_ok))) |
| 410 | + .collect(), |
| 411 | + default: Box::new(self.expr(*default, uses, exits_ok)), |
| 412 | + } |
| 413 | + } |
| 414 | + Expr::Return(a) => Expr::Return(self.atom(&a)), |
| 415 | + Expr::Exit(a) => Expr::Exit(self.atom(&a)), |
| 416 | + Expr::Panic(p) => Expr::Panic(p), |
| 417 | + Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 418 | + unreachable!("Core before Perceus") |
| 419 | + } |
| 420 | + Expr::Let(..) => unreachable!("a chain's end is never a `let`"), |
| 421 | + } |
| 422 | + } |
| 423 | + |
| 424 | + fn value(&mut self, value: Value, uses: &HashMap<VarId, u32>) -> Value { |
| 425 | + match value { |
| 426 | + Value::Atom(a) => Value::Atom(self.atom(&a)), |
| 427 | + Value::Call(f, args) => Value::Call(self.atom(&f), self.atoms(&args)), |
| 428 | + Value::CallFn(g, args) => Value::CallFn(g, self.atoms(&args)), |
| 429 | + Value::CallExtern(s, args) => Value::CallExtern(s, self.atoms(&args)), |
| 430 | + Value::Prim(p, args) => Value::Prim(p, self.atoms(&args)), |
| 431 | + Value::Construct { tag, name, args } => Value::Construct { |
| 432 | + tag, |
| 433 | + name, |
| 434 | + args: self.atoms(&args), |
| 435 | + }, |
| 436 | + Value::Tuple(args) => Value::Tuple(self.atoms(&args)), |
| 437 | + Value::Field(a, i) => { |
| 438 | + let a = self.atom(&a); |
| 439 | + let folded = match &a { |
| 440 | + Atom::Var(x) => match self.known.get(x) { |
| 441 | + Some(Known::Construct(_, fields)) | Some(Known::Tuple(fields)) => { |
| 442 | + fields.get(i as usize).cloned() |
| 443 | + } |
| 444 | + _ => None, |
| 445 | + }, |
| 446 | + _ => None, |
| 447 | + }; |
| 448 | + match folded { |
| 449 | + Some(field) => { |
| 450 | + self.changed = true; |
| 451 | + Value::Atom(field) |
| 452 | + } |
| 453 | + None => Value::Field(a, i), |
| 454 | + } |
| 455 | + } |
| 456 | + Value::Closure(g, caps) => Value::Closure(g, self.atoms(&caps)), |
| 457 | + Value::Perform { |
| 458 | + cap, |
| 459 | + effect, |
| 460 | + op, |
| 461 | + args, |
| 462 | + } => Value::Perform { |
| 463 | + cap: self.atom(&cap), |
| 464 | + effect, |
| 465 | + op, |
| 466 | + args: self.atoms(&args), |
| 467 | + }, |
| 468 | + Value::Handle { |
| 469 | + effect, |
| 470 | + body, |
| 471 | + ret, |
| 472 | + clauses, |
| 473 | + } => Value::Handle { |
| 474 | + effect, |
| 475 | + body: self.atom(&body), |
| 476 | + ret: ret.map(|r| self.atom(&r)), |
| 477 | + clauses: self.atoms(&clauses), |
| 478 | + }, |
| 479 | + Value::Region { effects, body } => Value::Region { |
| 480 | + effects, |
| 481 | + body: self.atom(&body), |
| 482 | + }, |
| 483 | + Value::Defer { body, cleanup } => Value::Defer { |
| 484 | + body: self.atom(&body), |
| 485 | + cleanup: self.atom(&cleanup), |
| 486 | + }, |
| 487 | + Value::Block(b) => Value::Block(Box::new(self.expr(*b, uses, false))), |
| 488 | + Value::Reuse { .. } | Value::CtxExtend { .. } | Value::CtxApply { .. } => { |
| 489 | + unreachable!("Core before TRMC and Perceus") |
| 490 | + } |
| 491 | + } |
| 492 | + } |
| 493 | +} |
| 494 | + |
| 495 | +/// Whether removing or moving a `let` of `value` changes nothing but |
| 496 | +/// allocation: no call, operation or control flow. |
| 497 | +fn pure(value: &Value) -> bool { |
| 498 | + matches!( |
| 499 | + value, |
| 500 | + Value::Atom(_) |
| 501 | + | Value::Field(..) |
| 502 | + | Value::Prim(..) |
| 503 | + | Value::Tuple(_) |
| 504 | + | Value::Construct { .. } |
| 505 | + | Value::Closure(..) |
| 506 | + ) |
| 507 | +} |
| 508 | + |
| 509 | +/// `let v = value; rest`, as the chain of its `let`s and the end they |
| 510 | +/// lead to. |
| 511 | +fn split(mut e: Expr) -> (Vec<(VarId, Value, Option<Span>)>, Expr) { |
| 512 | + let mut lets = Vec::new(); |
| 513 | + while let Expr::Let(v, value, rest, span) = e { |
| 514 | + lets.push((v, *value, span)); |
| 515 | + e = *rest; |
| 516 | + } |
| 517 | + (lets, e) |
| 518 | +} |
| 519 | + |
| 520 | +/// Remove `let`s of pure values nothing uses, and sink a pure `let` used |
| 521 | +/// in exactly one branch of the following switch into it: it is computed |
| 522 | +/// only on that path. |
| 523 | +fn sweep(e: Expr, changed: &mut bool) -> Expr { |
| 524 | + sweep_in(e, &mut HashSet::new(), changed) |
| 525 | +} |
| 526 | + |
| 527 | +fn sweep_in(e: Expr, used: &mut HashSet<VarId>, changed: &mut bool) -> Expr { |
| 528 | + let (mut lets, end) = split(e); |
| 529 | + let mut end = match end { |
| 530 | + Expr::Return(a) => { |
| 531 | + var(&a, used); |
| 532 | + Expr::Return(a) |
| 533 | + } |
| 534 | + Expr::Exit(a) => { |
| 535 | + var(&a, used); |
| 536 | + Expr::Exit(a) |
| 537 | + } |
| 538 | + Expr::Panic(p) => Expr::Panic(p), |
| 539 | + Expr::Switch { on, cases, default } => { |
| 540 | + var(&on, used); |
| 541 | + let (tags, mut bodies): (Vec<u32>, Vec<Expr>) = cases.into_iter().unzip(); |
| 542 | + let has_default = default.is_some(); |
| 543 | + if let Some(d) = default { |
| 544 | + bodies.push(*d); |
| 545 | + } |
| 546 | + // What a branch uses decides what the chain before the switch |
| 547 | + // must keep, so the branches' own set stays apart: sinking a |
| 548 | + // `let` into one branch must see the uses before the switch, |
| 549 | + // not the branches'. |
| 550 | + let mut inner = HashSet::new(); |
| 551 | + let mut frees = sweep_bodies(&mut bodies, &mut inner, changed); |
| 552 | + sink(&mut lets, &on, &mut bodies, &mut frees, used, changed); |
| 553 | + used.extend(inner); |
| 554 | + let mut bodies = bodies.into_iter(); |
| 555 | + let cases = tags.into_iter().zip(bodies.by_ref()).collect(); |
| 556 | + let default = if has_default { |
| 557 | + Some(Box::new(bodies.next().expect("the default's body"))) |
| 558 | + } else { |
| 559 | + None |
| 560 | + }; |
| 561 | + Expr::Switch { on, cases, default } |
| 562 | + } |
| 563 | + Expr::SwitchLit { on, cases, default } => { |
| 564 | + var(&on, used); |
| 565 | + let (lits, mut bodies): (Vec<crate::ir::Lit>, Vec<Expr>) = cases.into_iter().unzip(); |
| 566 | + bodies.push(*default); |
| 567 | + let mut inner = HashSet::new(); |
| 568 | + let mut frees = sweep_bodies(&mut bodies, &mut inner, changed); |
| 569 | + sink(&mut lets, &on, &mut bodies, &mut frees, used, changed); |
| 570 | + used.extend(inner); |
| 571 | + let mut bodies = bodies.into_iter(); |
| 572 | + let cases = lits.into_iter().zip(bodies.by_ref()).collect(); |
| 573 | + let default = Box::new(bodies.next().expect("the default's body")); |
| 574 | + Expr::SwitchLit { on, cases, default } |
| 575 | + } |
| 576 | + Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 577 | + unreachable!("Core before Perceus") |
| 578 | + } |
| 579 | + Expr::Let(..) => unreachable!("a chain's end is never a `let`"), |
| 580 | + }; |
| 581 | + while let Some((v, value, span)) = lets.pop() { |
| 582 | + if pure(&value) && !used.contains(&v) { |
| 583 | + *changed = true; |
| 584 | + continue; |
| 585 | + } |
| 586 | + used.remove(&v); |
| 587 | + let value = match value { |
| 588 | + Value::Block(b) => { |
| 589 | + let mut b = sweep_in(*b, &mut HashSet::new(), changed); |
| 590 | + sink_into_block(&mut b, &mut lets, used, changed); |
| 591 | + used.extend(free_vars(&b)); |
| 592 | + Value::Block(Box::new(b)) |
| 593 | + } |
| 594 | + value => { |
| 595 | + value_vars(&value, used); |
| 596 | + value |
| 597 | + } |
| 598 | + }; |
| 599 | + end = Expr::Let(v, Box::new(value), Box::new(end), span); |
| 600 | + } |
| 601 | + end |
| 602 | +} |
| 603 | + |
| 604 | +/// Sweep each branch body; the free variables of each, after. |
| 605 | +fn sweep_bodies( |
| 606 | + bodies: &mut [Expr], |
| 607 | + used: &mut HashSet<VarId>, |
| 608 | + changed: &mut bool, |
| 609 | +) -> Vec<HashSet<VarId>> { |
| 610 | + let mut frees = Vec::with_capacity(bodies.len()); |
| 611 | + for body in bodies { |
| 612 | + *body = sweep_in( |
| 613 | + std::mem::replace(body, Expr::Return(Atom::Unit)), |
| 614 | + used, |
| 615 | + changed, |
| 616 | + ); |
| 617 | + frees.push(free_vars(body)); |
| 618 | + } |
| 619 | + frees |
| 620 | +} |
| 621 | + |
| 622 | +/// Sink the trailing pure `let`s of a chain that end in a switch: a |
| 623 | +/// `let` whose variable is used in exactly one branch (and not after the |
| 624 | +/// switch, nor in the scrutinee) moves into that branch. |
| 625 | +fn sink( |
| 626 | + lets: &mut Vec<(VarId, Value, Option<Span>)>, |
| 627 | + on: &Atom, |
| 628 | + bodies: &mut [Expr], |
| 629 | + frees: &mut [HashSet<VarId>], |
| 630 | + used: &HashSet<VarId>, |
| 631 | + changed: &mut bool, |
| 632 | +) { |
| 633 | + loop { |
| 634 | + let hit = match lets.last() { |
| 635 | + Some((v, value, _)) |
| 636 | + if pure(value) && !used.contains(v) && !matches!(on, Atom::Var(o) if o == v) => |
| 637 | + { |
| 638 | + let mut hits = frees.iter().enumerate().filter(|(_, f)| f.contains(v)); |
| 639 | + match (hits.next(), hits.next()) { |
| 640 | + (Some((i, _)), None) => Some(i), |
| 641 | + _ => None, |
| 642 | + } |
| 643 | + } |
| 644 | + _ => None, |
| 645 | + }; |
| 646 | + let Some(i) = hit else { break }; |
| 647 | + let (v, value, span) = lets.pop().expect("checked above"); |
| 648 | + // The value's own variables are used in that branch now. |
| 649 | + value_vars(&value, &mut frees[i]); |
| 650 | + let body = std::mem::replace(&mut bodies[i], Expr::Return(Atom::Unit)); |
| 651 | + bodies[i] = Expr::Let(v, Box::new(value), Box::new(body), span); |
| 652 | + *changed = true; |
| 653 | + } |
| 654 | +} |
| 655 | + |
| 656 | +/// A block that is exactly a switch takes the pure `let`s before it that |
| 657 | +/// only one branch uses, as a chain ending in the switch would. |
| 658 | +fn sink_into_block( |
| 659 | + b: &mut Expr, |
| 660 | + lets: &mut Vec<(VarId, Value, Option<Span>)>, |
| 661 | + used: &HashSet<VarId>, |
| 662 | + changed: &mut bool, |
| 663 | +) { |
| 664 | + let (prefix, end) = split(std::mem::replace(b, Expr::Return(Atom::Unit))); |
| 665 | + if !prefix.is_empty() { |
| 666 | + *b = rebuild(prefix, end); |
| 667 | + return; |
| 668 | + } |
| 669 | + match end { |
| 670 | + Expr::Switch { on, cases, default } => { |
| 671 | + let (tags, mut bodies): (Vec<u32>, Vec<Expr>) = cases.into_iter().unzip(); |
| 672 | + let has_default = default.is_some(); |
| 673 | + if let Some(d) = default { |
| 674 | + bodies.push(*d); |
| 675 | + } |
| 676 | + let mut frees: Vec<HashSet<VarId>> = bodies.iter().map(free_vars).collect(); |
| 677 | + sink(lets, &on, &mut bodies, &mut frees, used, changed); |
| 678 | + let mut bodies = bodies.into_iter(); |
| 679 | + let cases = tags.into_iter().zip(bodies.by_ref()).collect(); |
| 680 | + let default = if has_default { |
| 681 | + Some(Box::new(bodies.next().expect("the default's body"))) |
| 682 | + } else { |
| 683 | + None |
| 684 | + }; |
| 685 | + *b = Expr::Switch { on, cases, default }; |
| 686 | + } |
| 687 | + Expr::SwitchLit { on, cases, default } => { |
| 688 | + let (lits, mut bodies): (Vec<crate::ir::Lit>, Vec<Expr>) = cases.into_iter().unzip(); |
| 689 | + bodies.push(*default); |
| 690 | + let mut frees: Vec<HashSet<VarId>> = bodies.iter().map(free_vars).collect(); |
| 691 | + sink(lets, &on, &mut bodies, &mut frees, used, changed); |
| 692 | + let mut bodies = bodies.into_iter(); |
| 693 | + let cases = lits.into_iter().zip(bodies.by_ref()).collect(); |
| 694 | + let default = Box::new(bodies.next().expect("the default's body")); |
| 695 | + *b = Expr::SwitchLit { on, cases, default }; |
| 696 | + } |
| 697 | + end => { |
| 698 | + *b = end; |
| 699 | + } |
| 700 | + } |
| 701 | +} |
| 702 | + |
| 703 | +/// Rebuild an expression from its chain and its end (`split` reversed). |
| 704 | +fn rebuild(lets: Vec<(VarId, Value, Option<Span>)>, end: Expr) -> Expr { |
| 705 | + let mut out = end; |
| 706 | + for (v, value, span) in lets.into_iter().rev() { |
| 707 | + out = Expr::Let(v, Box::new(value), Box::new(out), span); |
| 708 | + } |
| 709 | + out |
| 710 | +} |
| 711 | + |
| 712 | +/// `e` with its variables replaced: inlining renames a callee's |
| 713 | +/// variables into the caller's (its parameters to the arguments, the |
| 714 | +/// rest fresh). |
| 715 | +fn rename(e: &Expr, m: &mut dyn FnMut(VarId) -> Atom) -> Expr { |
| 716 | + match e { |
| 717 | + Expr::Let(v, value, rest, span) => { |
| 718 | + let Atom::Var(v) = m(*v) else { |
| 719 | + unreachable!("a parameter is never `let`-bound") |
| 720 | + }; |
| 721 | + Expr::Let( |
| 722 | + v, |
| 723 | + Box::new(rename_value(value, m)), |
| 724 | + Box::new(rename(rest, m)), |
| 725 | + *span, |
| 726 | + ) |
| 727 | + } |
| 728 | + Expr::Return(a) => Expr::Return(rename_atom(a, m)), |
| 729 | + Expr::Exit(a) => Expr::Exit(rename_atom(a, m)), |
| 730 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 731 | + on: rename_atom(on, m), |
| 732 | + cases: cases.iter().map(|(t, b)| (*t, rename(b, m))).collect(), |
| 733 | + default: default.as_ref().map(|d| Box::new(rename(d, m))), |
| 734 | + }, |
| 735 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 736 | + on: rename_atom(on, m), |
| 737 | + cases: cases |
| 738 | + .iter() |
| 739 | + .map(|(c, b)| (c.clone(), rename(b, m))) |
| 740 | + .collect(), |
| 741 | + default: Box::new(rename(default, m)), |
| 742 | + }, |
| 743 | + Expr::Panic(p) => Expr::Panic(p.clone()), |
| 744 | + Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 745 | + unreachable!("Core before Perceus") |
| 746 | + } |
| 747 | + } |
| 748 | +} |
| 749 | + |
| 750 | +fn rename_atom(a: &Atom, m: &mut dyn FnMut(VarId) -> Atom) -> Atom { |
| 751 | + match a { |
| 752 | + Atom::Var(v) => m(*v), |
| 753 | + a => a.clone(), |
| 754 | + } |
| 755 | +} |
| 756 | + |
| 757 | +fn rename_value(v: &Value, m: &mut dyn FnMut(VarId) -> Atom) -> Value { |
| 758 | + match v { |
| 759 | + Value::Atom(a) => Value::Atom(rename_atom(a, m)), |
| 760 | + Value::Call(f, args) => Value::Call(rename_atom(f, m), rename_atoms(args, m)), |
| 761 | + Value::CallFn(g, args) => Value::CallFn(*g, rename_atoms(args, m)), |
| 762 | + Value::CallExtern(s, args) => Value::CallExtern(s.clone(), rename_atoms(args, m)), |
| 763 | + Value::Prim(p, args) => Value::Prim(*p, rename_atoms(args, m)), |
| 764 | + Value::Construct { tag, name, args } => Value::Construct { |
| 765 | + tag: *tag, |
| 766 | + name: name.clone(), |
| 767 | + args: rename_atoms(args, m), |
| 768 | + }, |
| 769 | + Value::Tuple(args) => Value::Tuple(rename_atoms(args, m)), |
| 770 | + Value::Field(a, i) => Value::Field(rename_atom(a, m), *i), |
| 771 | + Value::Closure(g, caps) => Value::Closure(*g, rename_atoms(caps, m)), |
| 772 | + Value::Perform { |
| 773 | + cap, |
| 774 | + effect, |
| 775 | + op, |
| 776 | + args, |
| 777 | + } => Value::Perform { |
| 778 | + cap: rename_atom(cap, m), |
| 779 | + effect: *effect, |
| 780 | + op: *op, |
| 781 | + args: rename_atoms(args, m), |
| 782 | + }, |
| 783 | + Value::Handle { |
| 784 | + effect, |
| 785 | + body, |
| 786 | + ret, |
| 787 | + clauses, |
| 788 | + } => Value::Handle { |
| 789 | + effect: *effect, |
| 790 | + body: rename_atom(body, m), |
| 791 | + ret: ret.as_ref().map(|r| rename_atom(r, m)), |
| 792 | + clauses: rename_atoms(clauses, m), |
| 793 | + }, |
| 794 | + Value::Region { effects, body } => Value::Region { |
| 795 | + effects: effects.clone(), |
| 796 | + body: rename_atom(body, m), |
| 797 | + }, |
| 798 | + Value::Defer { body, cleanup } => Value::Defer { |
| 799 | + body: rename_atom(body, m), |
| 800 | + cleanup: rename_atom(cleanup, m), |
| 801 | + }, |
| 802 | + Value::Block(b) => Value::Block(Box::new(rename(b, m))), |
| 803 | + Value::Reuse { .. } | Value::CtxExtend { .. } | Value::CtxApply { .. } => { |
| 804 | + unreachable!("Core before TRMC and Perceus") |
| 805 | + } |
| 806 | + } |
| 807 | +} |
| 808 | + |
| 809 | +fn rename_atoms(atoms: &[Atom], m: &mut dyn FnMut(VarId) -> Atom) -> Vec<Atom> { |
| 810 | + atoms.iter().map(|a| rename_atom(a, m)).collect() |
| 811 | +} |
| 812 | + |
| 813 | +/// The chain a body is: how its value leaves it. |
| 814 | +fn end_of(e: &Expr) -> End { |
| 815 | + let mut e = e; |
| 816 | + loop { |
| 817 | + match e { |
| 818 | + Expr::Let(_, _, rest, _) => e = rest, |
| 819 | + Expr::Return(_) => return End::Return, |
| 820 | + Expr::Panic(_) => return End::Panic, |
| 821 | + _ => return End::Other, |
| 822 | + } |
| 823 | + } |
| 824 | +} |
| 825 | + |
| 826 | +/// Whether the body calls function `id`, or closes over it, anywhere. |
| 827 | +fn recursive(e: &Expr, id: FnId) -> bool { |
| 828 | + let mut found = false; |
| 829 | + visit_values(e, &mut |v| { |
| 830 | + if matches!(v, Value::CallFn(g, _) | Value::Closure(g, _) if *g == id) { |
| 831 | + found = true; |
| 832 | + } |
| 833 | + }); |
| 834 | + found |
| 835 | +} |
| 836 | + |
| 837 | +/// Whether the body leaves its function early (ADR 0037), anywhere. |
| 838 | +fn has_exit(e: &Expr) -> bool { |
| 839 | + let mut found = false; |
| 840 | + visit_exprs(e, &mut |e| { |
| 841 | + if matches!(e, Expr::Exit(_)) { |
| 842 | + found = true; |
| 843 | + } |
| 844 | + }); |
| 845 | + found |
| 846 | +} |
| 847 | + |
| 848 | +/// An upper bound on a body's size in nodes (lets, values, branches), |
| 849 | +/// saturating where the caps stop mattering. |
| 850 | +fn size(e: &Expr) -> u32 { |
| 851 | + let mut n = 0u32; |
| 852 | + visit_exprs(e, &mut |_| { |
| 853 | + n = n.saturating_add(1); |
| 854 | + }); |
| 855 | + let mut m = 0u32; |
| 856 | + visit_values(e, &mut |_| { |
| 857 | + m = m.saturating_add(1); |
| 858 | + }); |
| 859 | + n + m |
| 860 | +} |
| 861 | + |
| 862 | +/// Every expression node, anywhere in `e` (analysis only: it accepts |
| 863 | +/// every node, whenever it runs). |
| 864 | +fn visit_exprs(e: &Expr, f: &mut impl FnMut(&Expr)) { |
| 865 | + let mut work = vec![e]; |
| 866 | + while let Some(e) = work.pop() { |
| 867 | + f(e); |
| 868 | + match e { |
| 869 | + Expr::Let(_, value, rest, _) => { |
| 870 | + if let Value::Block(b) = &**value { |
| 871 | + work.push(b); |
| 872 | + } |
| 873 | + work.push(rest); |
| 874 | + } |
| 875 | + Expr::Switch { cases, default, .. } => { |
| 876 | + for (_, b) in cases { |
| 877 | + work.push(b); |
| 878 | + } |
| 879 | + if let Some(d) = default { |
| 880 | + work.push(d); |
| 881 | + } |
| 882 | + } |
| 883 | + Expr::SwitchLit { cases, default, .. } => { |
| 884 | + for (_, b) in cases { |
| 885 | + work.push(b); |
| 886 | + } |
| 887 | + work.push(default); |
| 888 | + } |
| 889 | + _ => {} |
| 890 | + } |
| 891 | + } |
| 892 | +} |
| 893 | + |
| 894 | +/// Every value node, anywhere in `e`. |
| 895 | +fn visit_values(e: &Expr, f: &mut impl FnMut(&Value)) { |
| 896 | + visit_exprs(e, &mut |e| { |
| 897 | + if let Expr::Let(_, value, _, _) = e { |
| 898 | + f(value); |
| 899 | + } |
| 900 | + }); |
| 901 | +} |
| 902 | + |
| 903 | +/// Every atom in a use position, anywhere in `e`. |
| 904 | +fn visit(e: &Expr, f: &mut impl FnMut(&Atom)) { |
| 905 | + visit_exprs(e, &mut |e| match e { |
| 906 | + Expr::Let(_, value, _, _) => visit_value(value, f), |
| 907 | + Expr::Return(a) | Expr::Exit(a) => f(a), |
| 908 | + Expr::Switch { on, .. } | Expr::SwitchLit { on, .. } => f(on), |
| 909 | + Expr::Dup(v, _) | Expr::Drop(v, _) => f(&Atom::Var(*v)), |
| 910 | + Expr::Release { |
| 911 | + var, fields, token, .. |
| 912 | + } => { |
| 913 | + f(&Atom::Var(*var)); |
| 914 | + for (_, v) in fields { |
| 915 | + f(&Atom::Var(*v)); |
| 916 | + } |
| 917 | + if let Some(t) = token { |
| 918 | + f(&Atom::Var(*t)); |
| 919 | + } |
| 920 | + } |
| 921 | + Expr::Panic(_) => {} |
| 922 | + }); |
| 923 | +} |
| 924 | + |
| 925 | +fn visit_value(v: &Value, f: &mut impl FnMut(&Atom)) { |
| 926 | + match v { |
| 927 | + Value::Atom(a) => f(a), |
| 928 | + Value::Call(g, args) => { |
| 929 | + f(g); |
| 930 | + for a in args { |
| 931 | + f(a); |
| 932 | + } |
| 933 | + } |
| 934 | + Value::CallFn(_, args) |
| 935 | + | Value::CallExtern(_, args) |
| 936 | + | Value::Prim(_, args) |
| 937 | + | Value::Tuple(args) |
| 938 | + | Value::Construct { args, .. } |
| 939 | + | Value::Closure(_, args) => { |
| 940 | + for a in args { |
| 941 | + f(a); |
| 942 | + } |
| 943 | + } |
| 944 | + Value::Field(a, _) => f(a), |
| 945 | + Value::Perform { cap, args, .. } => { |
| 946 | + f(cap); |
| 947 | + for a in args { |
| 948 | + f(a); |
| 949 | + } |
| 950 | + } |
| 951 | + Value::Handle { |
| 952 | + body, ret, clauses, .. |
| 953 | + } => { |
| 954 | + f(body); |
| 955 | + if let Some(r) = ret { |
| 956 | + f(r); |
| 957 | + } |
| 958 | + for a in clauses { |
| 959 | + f(a); |
| 960 | + } |
| 961 | + } |
| 962 | + Value::Region { body, .. } => f(body), |
| 963 | + Value::Defer { body, cleanup } => { |
| 964 | + f(body); |
| 965 | + f(cleanup); |
| 966 | + } |
| 967 | + Value::Block(_) => {} // `visit_exprs` walks into blocks |
| 968 | + Value::Reuse { token, value, .. } => { |
| 969 | + f(&Atom::Var(*token)); |
| 970 | + visit_value(value, f); |
| 971 | + } |
| 972 | + Value::CtxExtend { ctx, cell, .. } => { |
| 973 | + f(ctx); |
| 974 | + f(cell); |
| 975 | + } |
| 976 | + Value::CtxApply { ctx, value } => { |
| 977 | + f(ctx); |
| 978 | + f(value); |
| 979 | + } |
| 980 | + } |
| 981 | +} |
| 982 | + |
| 983 | +fn var(a: &Atom, used: &mut HashSet<VarId>) { |
| 984 | + if let Atom::Var(v) = a { |
| 985 | + used.insert(*v); |
| 986 | + } |
| 987 | +} |
| 988 | + |
| 989 | +fn value_vars(value: &Value, used: &mut HashSet<VarId>) { |
| 990 | + visit_value(value, &mut |a| var(a, used)); |
| 991 | +} |
| 992 | + |
| 993 | +/// The variables used anywhere in `e`, and how often. |
| 994 | +fn uses(e: &Expr) -> HashMap<VarId, u32> { |
| 995 | + let mut out: HashMap<VarId, u32> = HashMap::new(); |
| 996 | + visit(e, &mut |a| { |
| 997 | + if let Atom::Var(v) = a { |
| 998 | + *out.entry(*v).or_insert(0) += 1; |
| 999 | + } |
| 1000 | + }); |
| 1001 | + out |
| 1002 | +} |
| 1003 | + |
| 1004 | +/// The variables used anywhere in `e`. |
| 1005 | +fn free_vars(e: &Expr) -> HashSet<VarId> { |
| 1006 | + let mut out = HashSet::new(); |
| 1007 | + visit(e, &mut |a| var(a, &mut out)); |
| 1008 | + out |
| 1009 | +} |