| @@ -0,0 +1,445 @@ |
| 1 | +//! Splitting giant functions into tail-call chains (issue #281, ADR |
| 2 | +//! 0056). |
| 3 | +//! |
| 4 | +//! The inliner leaves some functions — `main` of a program with derived |
| 5 | +//! impls, above all — at tens of thousands of Core nodes. One C function |
| 6 | +//! per Core function then means one giant C function, and clang's `-g` |
| 7 | +//! passes are quadratic in its size: `tests/run/msgpack.lse`'s 13,000-line |
| 8 | +//! `main` needs 88 s and 6.5 GB to compile at `-O1 -g` (4.3 s and 178 MB |
| 9 | +//! at `-g1`). `LOUISE_CFLAGS=-g` is how a release build keeps variable |
| 10 | +//! info (issue #116), so any big enough program hits this. |
| 11 | +//! |
| 12 | +//! The pass cuts such a function's top-level `let` chain into chunks of |
| 13 | +//! at most a budget of nodes each; a chunk ends tail-calling the next, |
| 14 | +//! handing it the variables live at the cut as owned arguments. The C is |
| 15 | +//! then a chain of bounded functions connected by `musttail` calls: the |
| 16 | +//! stack stays constant and every quadratic C-compiler pass sees a |
| 17 | +//! bounded function. |
| 18 | +//! |
| 19 | +//! Only the top-level chain is cut: a `switch` arm's or a |
| 20 | +//! [`Value::Block`]'s body is never entered — a block's label cannot |
| 21 | +//! cross a C function boundary. Size that lives inside them (a single |
| 22 | +//! item over the budget on its own) leaves the function unsplit, and so |
| 23 | +//! does a cut whose live variables would not fit a C signature with |
| 24 | +//! headroom. Functions with an unboxed signature or a CPR worker's |
| 25 | +//! multi-value return are skipped: theirs is not the uniform signature |
| 26 | +//! the chain's calls rely on. |
| 27 | +//! |
| 28 | +//! The C backend runs the pass after the optimiser and before Perceus |
| 29 | +//! (`louise_codegen_c::units`), which inserts the reference counts of |
| 30 | +//! the new calls and infers the chunks' borrowed parameters as for any |
| 31 | +//! function. The interpreter never runs it. The threshold is |
| 32 | +//! [`DEFAULT_NODES`], overridden by `LOUISE_SPLIT_NODES` (0 disables the |
| 33 | +//! pass), read once by the backend. |
| 34 | + |
| 35 | +use std::collections::{BTreeMap, BTreeSet, HashMap}; |
| 36 | + |
| 37 | +use crate::ir::{Atom, Expr, FnDecl, FnId, Program, Span, Value, VarId}; |
| 38 | +use crate::opt::simplify::{visit, visit_exprs, visit_value, visit_values}; |
| 39 | + |
| 40 | +/// The default size budget of a chunk, in Core nodes (lets, values, |
| 41 | +/// branches): ~2,000 lines of C at the observed ratio, where clang's |
| 42 | +/// `-g` passes are still flat (msgpack's `main`: 5.3 s and 200 MB at |
| 43 | +/// `-O1 -g`, against 4.3 s and 178 MB at `-g1` — and 88 s and 6.5 GB |
| 44 | +/// unsplit). `LOUISE_SPLIT_NODES` overrides it (0 disables), read once |
| 45 | +/// by the C backend. |
| 46 | +pub const DEFAULT_NODES: u32 = 500; |
| 47 | + |
| 48 | +/// The most parameters a chunk may take: the C signature passes six |
| 49 | +/// arguments in registers and up to 26 more through the context |
| 50 | +/// (`louise_codegen_c::emit`); stay well under. |
| 51 | +pub const MAX_PARAMS: usize = 24; |
| 52 | + |
| 53 | +/// A statement of a chain: the variables it binds (one, or a CPR |
| 54 | +/// worker's components), its value, its span. |
| 55 | +type Stmt = (Vec<VarId>, Value, Option<Span>); |
| 56 | + |
| 57 | +/// `e` as its leading `let`s (`LetN` included: a worker's call is a |
| 58 | +/// statement like any other) and what ends them. |
| 59 | +fn peel(mut e: Expr) -> (Vec<Stmt>, Expr) { |
| 60 | + let mut lets = Vec::new(); |
| 61 | + loop { |
| 62 | + match e { |
| 63 | + Expr::Let(v, value, rest, span) => { |
| 64 | + lets.push((vec![v], *value, span)); |
| 65 | + e = *rest; |
| 66 | + } |
| 67 | + Expr::LetN(vs, value, rest, span) => { |
| 68 | + lets.push((vs, *value, span)); |
| 69 | + e = *rest; |
| 70 | + } |
| 71 | + _ => return (lets, e), |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +/// Rebuild an expression from its chain and its end (`peel` reversed). |
| 77 | +fn wrap(lets: Vec<Stmt>, end: Expr) -> Expr { |
| 78 | + lets.into_iter() |
| 79 | + .rev() |
| 80 | + .fold(end, |rest, (mut vs, value, span)| { |
| 81 | + if vs.len() == 1 { |
| 82 | + Expr::Let(vs.remove(0), Box::new(value), Box::new(rest), span) |
| 83 | + } else { |
| 84 | + Expr::LetN(vs, Box::new(value), Box::new(rest), span) |
| 85 | + } |
| 86 | + }) |
| 87 | +} |
| 88 | + |
| 89 | +/// Split every function of `live` whose body exceeds `nodes` into a |
| 90 | +/// chain of chunks (see the module docs). The new functions |
| 91 | +/// (`{name}$split1`, …) are appended to `program` and returned. `nodes` |
| 92 | +/// of 0 disables the pass. |
| 93 | +pub fn run_in(program: &mut Program, live: &[FnId], nodes: u32) -> Vec<FnId> { |
| 94 | + run_with(program, live, nodes, MAX_PARAMS) |
| 95 | +} |
| 96 | + |
| 97 | +/// [`run_in`], with the cap on a chunk's parameters given: the tests |
| 98 | +/// force the live-variables overflow path with a low one. |
| 99 | +pub fn run_with(program: &mut Program, live: &[FnId], nodes: u32, cap: usize) -> Vec<FnId> { |
| 100 | + let mut new = Vec::new(); |
| 101 | + if nodes == 0 { |
| 102 | + return new; |
| 103 | + } |
| 104 | + for &id in live { |
| 105 | + let decl = &program.fns[id as usize]; |
| 106 | + if decl.unbox_sig.is_some() || decl.cpr_arity.is_some() { |
| 107 | + continue; |
| 108 | + } |
| 109 | + if size(&decl.body) <= nodes { |
| 110 | + continue; |
| 111 | + } |
| 112 | + if let Some(cuts) = plan(&decl.body, nodes, cap) { |
| 113 | + materialize(program, id, cuts, &mut new); |
| 114 | + } |
| 115 | + } |
| 116 | + new |
| 117 | +} |
| 118 | + |
| 119 | +/// Where a chain is cut: before item `at` (items `0..n` are its `let`s, |
| 120 | +/// item `n` its end), with the variables live there — the next chunk's |
| 121 | +/// parameters. |
| 122 | +struct Cut { |
| 123 | + at: usize, |
| 124 | + live: Vec<VarId>, |
| 125 | +} |
| 126 | + |
| 127 | +/// The cuts that split `body` into chunks of at most `nodes` each, or |
| 128 | +/// `None` to leave it whole: an item over the budget by itself (its size |
| 129 | +/// lives inside a block or the ending switch), or a cut point with more |
| 130 | +/// than `cap` live variables. |
| 131 | +fn plan(body: &Expr, nodes: u32, cap: usize) -> Option<Vec<Cut>> { |
| 132 | + let mut lets: Vec<(Vec<VarId>, &Value)> = Vec::new(); |
| 133 | + let mut end = body; |
| 134 | + loop { |
| 135 | + match end { |
| 136 | + Expr::Let(v, value, rest, _) => { |
| 137 | + lets.push((vec![*v], value)); |
| 138 | + end = rest; |
| 139 | + } |
| 140 | + Expr::LetN(vs, value, rest, _) => { |
| 141 | + lets.push((vs.clone(), value)); |
| 142 | + end = rest; |
| 143 | + } |
| 144 | + _ => break, |
| 145 | + } |
| 146 | + } |
| 147 | + // Item sizes: a `let` costs its node plus its value's; the chain's |
| 148 | + // end is the last item. A non-last chunk gains a tail call |
| 149 | + // (`let r = f(…); r`, three nodes), so items get three nodes less. |
| 150 | + let budget = nodes.saturating_sub(3); |
| 151 | + let mut sizes: Vec<u32> = lets.iter().map(|(_, v)| 1 + value_size(v)).collect(); |
| 152 | + sizes.push(size(end)); |
| 153 | + if sizes.iter().any(|&s| s > budget) { |
| 154 | + return None; |
| 155 | + } |
| 156 | + // `live[k]`: the variables the rest of the chain uses at item `k`, |
| 157 | + // walked backwards: live before `let v… = value` is live after it, |
| 158 | + // minus `v…`, plus what `value` reads. |
| 159 | + let n = lets.len(); |
| 160 | + let mut live: Vec<BTreeSet<VarId>> = vec![BTreeSet::new(); n + 1]; |
| 161 | + let mut cur = free_vars(end); |
| 162 | + for (k, (vs, value)) in lets.iter().enumerate().rev() { |
| 163 | + live[k + 1] = cur.clone(); |
| 164 | + for v in vs { |
| 165 | + cur.remove(v); |
| 166 | + } |
| 167 | + free_of_value(value, &mut cur); |
| 168 | + } |
| 169 | + live[0] = cur; |
| 170 | + // Pack items into chunks of at most `budget`, cutting only where the |
| 171 | + // live variables fit a C signature with headroom. |
| 172 | + let mut cuts = Vec::new(); |
| 173 | + let mut chunk = 0u32; |
| 174 | + for (k, &s) in sizes.iter().enumerate() { |
| 175 | + if chunk > 0 && chunk + s > budget { |
| 176 | + if live[k].len() > cap { |
| 177 | + return None; |
| 178 | + } |
| 179 | + cuts.push(Cut { |
| 180 | + at: k, |
| 181 | + live: live[k].iter().copied().collect(), |
| 182 | + }); |
| 183 | + chunk = 0; |
| 184 | + } |
| 185 | + chunk += s; |
| 186 | + } |
| 187 | + if cuts.is_empty() { None } else { Some(cuts) } |
| 188 | +} |
| 189 | + |
| 190 | +/// Cut `id`'s body at `cuts`: chunk 0 stays in `id`, the rest become |
| 191 | +/// `{name}$split{N}` functions, each chunk tail-calling the next. |
| 192 | +fn materialize(program: &mut Program, id: FnId, cuts: Vec<Cut>, new: &mut Vec<FnId>) { |
| 193 | + let (name, span, module, fip) = { |
| 194 | + let d = &program.fns[id as usize]; |
| 195 | + (d.name.clone(), d.span, d.module.clone(), d.fip) |
| 196 | + }; |
| 197 | + let d = &mut program.fns[id as usize]; |
| 198 | + let body = std::mem::replace(&mut d.body, Expr::Return(Atom::Unit)); |
| 199 | + let mut params = std::mem::take(&mut d.params); |
| 200 | + let shapes = std::mem::take(&mut d.shapes); |
| 201 | + // The fresh variable each chunk's tail call binds: one past every |
| 202 | + // variable the un-split function had, so it is always free. |
| 203 | + let call_result = d.n_vars; |
| 204 | + let (lets, end) = peel(body); |
| 205 | + let base = program.fns.len() as FnId; |
| 206 | + // The chunks: items `start..cut.at` (then `start..` and the chain's |
| 207 | + // end), chunk `j+1` taking `cuts[j]`'s live variables as parameters. |
| 208 | + let mut chunks: Vec<(Vec<VarId>, Vec<Stmt>, Option<Expr>)> = Vec::new(); |
| 209 | + let mut start = 0; |
| 210 | + for cut in &cuts { |
| 211 | + chunks.push((params, lets[start..cut.at].to_vec(), None)); |
| 212 | + params = cut.live.clone(); |
| 213 | + start = cut.at; |
| 214 | + } |
| 215 | + chunks.push((params, lets[start..].to_vec(), Some(end))); |
| 216 | + for (j, (chunk_params, stmts, chunk_end)) in chunks.into_iter().enumerate() { |
| 217 | + // A chunk but the last ends tail-calling the next (chunk `j+1` |
| 218 | + // is function `base + j`): the shape `emit` makes a `musttail`. |
| 219 | + let end = chunk_end.unwrap_or_else(|| { |
| 220 | + let args = cuts[j].live.iter().map(|v| Atom::Var(*v)).collect(); |
| 221 | + Expr::Let( |
| 222 | + call_result, |
| 223 | + Box::new(Value::CallFn(base + j as FnId, args)), |
| 224 | + Box::new(Expr::Return(Atom::Var(call_result))), |
| 225 | + None, |
| 226 | + ) |
| 227 | + }); |
| 228 | + let mut body = wrap(stmts, end); |
| 229 | + let mut renumber = Renumber::new(&chunk_params); |
| 230 | + renumber.expr(&mut body); |
| 231 | + let chunk_params = (0..chunk_params.len() as VarId).collect(); |
| 232 | + let chunk_shapes = renumber.shapes(&shapes); |
| 233 | + if j == 0 { |
| 234 | + let d = &mut program.fns[id as usize]; |
| 235 | + d.params = chunk_params; |
| 236 | + d.body = body; |
| 237 | + d.n_vars = renumber.next; |
| 238 | + d.shapes = chunk_shapes; |
| 239 | + } else { |
| 240 | + new.push(base + (j - 1) as FnId); |
| 241 | + program.fns.push(FnDecl { |
| 242 | + name: format!("{name}$split{j}"), |
| 243 | + params: chunk_params, |
| 244 | + body, |
| 245 | + n_vars: renumber.next, |
| 246 | + borrowed: Default::default(), |
| 247 | + span, |
| 248 | + module: module.clone(), |
| 249 | + shapes: chunk_shapes, |
| 250 | + fip, |
| 251 | + cpr_arity: None, |
| 252 | + unbox_sig: None, |
| 253 | + }); |
| 254 | + } |
| 255 | + } |
| 256 | +} |
| 257 | + |
| 258 | +/// Renumbers a chunk's variables: its parameters become `0..`, the rest |
| 259 | +/// fresh in order of binding, so each chunk declares its own `n_vars` |
| 260 | +/// (the un-split function's numbering would declare every variable of |
| 261 | +/// the whole function in every chunk). |
| 262 | +struct Renumber { |
| 263 | + map: HashMap<VarId, VarId>, |
| 264 | + next: VarId, |
| 265 | +} |
| 266 | + |
| 267 | +impl Renumber { |
| 268 | + fn new(params: &[VarId]) -> Renumber { |
| 269 | + let map = params |
| 270 | + .iter() |
| 271 | + .enumerate() |
| 272 | + .map(|(i, p)| (*p, i as VarId)) |
| 273 | + .collect(); |
| 274 | + Renumber { |
| 275 | + map, |
| 276 | + next: params.len() as VarId, |
| 277 | + } |
| 278 | + } |
| 279 | + |
| 280 | + /// The chunk's shapes: the un-split function's, restricted to the |
| 281 | + /// chunk's variables and renumbered with them. |
| 282 | + fn shapes(&self, shapes: &BTreeMap<VarId, Vec<u32>>) -> BTreeMap<VarId, Vec<u32>> { |
| 283 | + shapes |
| 284 | + .iter() |
| 285 | + .filter_map(|(v, a)| self.map.get(v).map(|&m| (m, a.clone()))) |
| 286 | + .collect() |
| 287 | + } |
| 288 | + |
| 289 | + fn bind(&mut self, v: &mut VarId) { |
| 290 | + let fresh = self.next; |
| 291 | + self.next += 1; |
| 292 | + self.map.insert(*v, fresh); |
| 293 | + *v = fresh; |
| 294 | + } |
| 295 | + |
| 296 | + fn atom(&self, a: &mut Atom) { |
| 297 | + if let Atom::Var(v) = a { |
| 298 | + *v = *self.map.get(v).expect("a use of a bound variable"); |
| 299 | + } |
| 300 | + } |
| 301 | + |
| 302 | + fn atoms(&self, args: &mut [Atom]) { |
| 303 | + for a in args { |
| 304 | + self.atom(a); |
| 305 | + } |
| 306 | + } |
| 307 | + |
| 308 | + fn expr(&mut self, e: &mut Expr) { |
| 309 | + match e { |
| 310 | + Expr::Let(v, value, rest, _) => { |
| 311 | + self.value(value); |
| 312 | + self.bind(v); |
| 313 | + self.expr(rest); |
| 314 | + } |
| 315 | + Expr::LetN(vs, value, rest, _) => { |
| 316 | + self.value(value); |
| 317 | + for v in vs { |
| 318 | + self.bind(v); |
| 319 | + } |
| 320 | + self.expr(rest); |
| 321 | + } |
| 322 | + Expr::Return(a) | Expr::Exit(a) => self.atom(a), |
| 323 | + Expr::ReturnN(atoms) => self.atoms(atoms), |
| 324 | + Expr::Switch { on, cases, default } => { |
| 325 | + self.atom(on); |
| 326 | + for (_, b) in cases { |
| 327 | + self.expr(b); |
| 328 | + } |
| 329 | + if let Some(d) = default { |
| 330 | + self.expr(d); |
| 331 | + } |
| 332 | + } |
| 333 | + Expr::SwitchLit { on, cases, default } => { |
| 334 | + self.atom(on); |
| 335 | + for (_, b) in cases { |
| 336 | + self.expr(b); |
| 337 | + } |
| 338 | + self.expr(default); |
| 339 | + } |
| 340 | + Expr::Panic(_) => {} |
| 341 | + Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 342 | + unreachable!("Core before Perceus") |
| 343 | + } |
| 344 | + } |
| 345 | + } |
| 346 | + |
| 347 | + fn value(&mut self, v: &mut Value) { |
| 348 | + match v { |
| 349 | + Value::Atom(a) => self.atom(a), |
| 350 | + Value::Call(f, args) => { |
| 351 | + self.atom(f); |
| 352 | + self.atoms(args); |
| 353 | + } |
| 354 | + Value::CallFn(_, args) |
| 355 | + | Value::CallExtern(_, args) |
| 356 | + | Value::Prim(_, args) |
| 357 | + | Value::Tuple(args) |
| 358 | + | Value::Construct { args, .. } |
| 359 | + | Value::Closure(_, args) => self.atoms(args), |
| 360 | + Value::Field(a, _) => self.atom(a), |
| 361 | + Value::Perform { cap, args, .. } => { |
| 362 | + self.atom(cap); |
| 363 | + self.atoms(args); |
| 364 | + } |
| 365 | + Value::Handle { |
| 366 | + body, ret, clauses, .. |
| 367 | + } => { |
| 368 | + self.atom(body); |
| 369 | + if let Some(r) = ret { |
| 370 | + self.atom(r); |
| 371 | + } |
| 372 | + self.atoms(clauses); |
| 373 | + } |
| 374 | + Value::Region { body, .. } => self.atom(body), |
| 375 | + Value::Defer { body, cleanup } => { |
| 376 | + self.atom(body); |
| 377 | + self.atom(cleanup); |
| 378 | + } |
| 379 | + Value::Block(b) => self.expr(b), |
| 380 | + Value::CtxExtend { ctx, cell, .. } => { |
| 381 | + self.atom(ctx); |
| 382 | + self.atom(cell); |
| 383 | + } |
| 384 | + Value::CtxApply { ctx, value } => { |
| 385 | + self.atom(ctx); |
| 386 | + self.atom(value); |
| 387 | + } |
| 388 | + Value::Reuse { .. } => unreachable!("Core before Perceus"), |
| 389 | + } |
| 390 | + } |
| 391 | +} |
| 392 | + |
| 393 | +/// A body's size in nodes (lets, values, branches), as |
| 394 | +/// `opt::simplify`'s. |
| 395 | +fn size(e: &Expr) -> u32 { |
| 396 | + let mut n = 0u32; |
| 397 | + visit_exprs(e, &mut |_| { |
| 398 | + n = n.saturating_add(1); |
| 399 | + }); |
| 400 | + visit_values(e, &mut |_| { |
| 401 | + n = n.saturating_add(1); |
| 402 | + }); |
| 403 | + n |
| 404 | +} |
| 405 | + |
| 406 | +/// A value's size in nodes: itself, plus its block's body if it has one. |
| 407 | +fn value_size(v: &Value) -> u32 { |
| 408 | + 1 + match v { |
| 409 | + Value::Block(b) => size(b), |
| 410 | + _ => 0, |
| 411 | + } |
| 412 | +} |
| 413 | + |
| 414 | +/// The variables `e` uses that it does not bind. |
| 415 | +fn free_vars(e: &Expr) -> BTreeSet<VarId> { |
| 416 | + let mut used = BTreeSet::new(); |
| 417 | + visit(e, &mut |a| { |
| 418 | + if let Atom::Var(v) = a { |
| 419 | + used.insert(*v); |
| 420 | + } |
| 421 | + }); |
| 422 | + let mut bound = BTreeSet::new(); |
| 423 | + visit_exprs(e, &mut |e| match e { |
| 424 | + Expr::Let(v, ..) => { |
| 425 | + bound.insert(*v); |
| 426 | + } |
| 427 | + Expr::LetN(vs, ..) => bound.extend(vs), |
| 428 | + _ => {} |
| 429 | + }); |
| 430 | + used.retain(|v| !bound.contains(v)); |
| 431 | + used |
| 432 | +} |
| 433 | + |
| 434 | +/// The variables `value` reads, added to `out` — a block's: its free |
| 435 | +/// variables (what it binds never leaves it). |
| 436 | +fn free_of_value(value: &Value, out: &mut BTreeSet<VarId>) { |
| 437 | + match value { |
| 438 | + Value::Block(b) => out.extend(free_vars(b)), |
| 439 | + value => visit_value(value, &mut |a| { |
| 440 | + if let Atom::Var(v) = a { |
| 441 | + out.insert(*v); |
| 442 | + } |
| 443 | + }), |
| 444 | + } |
| 445 | +} |