| @@ -0,0 +1,415 @@ |
| 1 | +//! Specialisation of higher-order functions on known lambdas (issue #197, |
| 2 | +//! ADR 0043). |
| 3 | +//! |
| 4 | +//! `list.map(xs, fn (x) { x * 2 })` passes a closure that `map` calls |
| 5 | +//! through an indirect call for every element. When a direct call's |
| 6 | +//! closure argument is a known lambda (or a known top-level function), |
| 7 | +//! this pass makes — or reuses — a copy of the callee specialised to it: |
| 8 | +//! the closure parameter is removed, its captured variables become |
| 9 | +//! parameters, and the calls inside are direct. The next simplifier round |
| 10 | +//! inlines the lambda into the copy, so the loop body is the lambda's |
| 11 | +//! body. |
| 12 | +//! |
| 13 | +//! Copies are keyed by (function, lambda) and shared across call sites; |
| 14 | +//! recursion inside the copy calls the copy. The number of copies is |
| 15 | +//! bounded, per function and in total. The pass runs on the pristine |
| 16 | +//! recursion, before TRMC: a specialised `map` is still cons-recursive, |
| 17 | +//! and TRMC gives it a context afterwards (ADR 0039). Copies have no |
| 18 | +//! module: like the evidence specialiser's, they live in the |
| 19 | +//! `+specialised` C unit (ADR 0029), so inlining the lambda into them |
| 20 | +//! never crosses a module. |
| 21 | + |
| 22 | +use std::collections::{HashMap, HashSet}; |
| 23 | + |
| 24 | +use super::simplify::{rebuild, split, visit_values}; |
| 25 | +use crate::ir::{Atom, Expr, FnDecl, FnId, Program, Span, Value, VarId}; |
| 26 | + |
| 27 | +/// At most this many copies of one function (each keyed by a different |
| 28 | +/// lambda)… |
| 29 | +const COPIES_PER_FUNCTION: usize = 8; |
| 30 | + |
| 31 | +/// …and at most one copy per function of the program, in total: code |
| 32 | +/// growth is bounded. |
| 33 | +const COPIES_BUDGET_PER_FUNCTION: usize = 1; |
| 34 | + |
| 35 | +/// A parameter specialisation: the lambda each parameter is specialised |
| 36 | +/// on, and how many captures it has (a lambda's capture count is fixed). |
| 37 | +type Spec = Vec<Option<(FnId, u32)>>; |
| 38 | + |
| 39 | +/// Specialise the higher-order calls of the functions in `live`; the |
| 40 | +/// copies made, so the driver can run the simplifier on them. |
| 41 | +pub fn run_in(program: &mut Program, live: &[FnId]) -> Vec<FnId> { |
| 42 | + // Which parameters each function calls as a closure. |
| 43 | + let called: HashMap<FnId, HashSet<VarId>> = program |
| 44 | + .fns |
| 45 | + .iter() |
| 46 | + .enumerate() |
| 47 | + .map(|(id, f)| (id as FnId, called_params(f))) |
| 48 | + .collect(); |
| 49 | + let mut pass = Pass { |
| 50 | + copies: HashMap::new(), |
| 51 | + per_function: HashMap::new(), |
| 52 | + budget: program.fns.len() * COPIES_BUDGET_PER_FUNCTION, |
| 53 | + queue: Vec::new(), |
| 54 | + made: Vec::new(), |
| 55 | + }; |
| 56 | + for &id in live { |
| 57 | + let body = std::mem::replace(&mut program.fns[id as usize].body, Expr::Return(Atom::Unit)); |
| 58 | + let mut known = HashMap::new(); |
| 59 | + program.fns[id as usize].body = pass.chain(program, body, &mut known, &called); |
| 60 | + } |
| 61 | + // A copy is built once every original is settled: a copy of a copy |
| 62 | + // starts from its original's final body. |
| 63 | + while let Some((copy, original, spec)) = pass.queue.pop() { |
| 64 | + build_copy(program, copy, original, &spec); |
| 65 | + pass.made.push(copy); |
| 66 | + } |
| 67 | + pass.made |
| 68 | +} |
| 69 | + |
| 70 | +struct Pass { |
| 71 | + /// (function, its specialisation) → the copy. |
| 72 | + copies: HashMap<(FnId, Spec), FnId>, |
| 73 | + /// Copies made per original function. |
| 74 | + per_function: HashMap<FnId, usize>, |
| 75 | + budget: usize, |
| 76 | + /// Copies to build: (copy, original, the specialisation). |
| 77 | + queue: Vec<(FnId, FnId, Spec)>, |
| 78 | + made: Vec<FnId>, |
| 79 | +} |
| 80 | + |
| 81 | +impl Pass { |
| 82 | + /// A chain of `let`s and its end: record closures, specialise calls, |
| 83 | + /// recurse into branches and blocks. (Variables are unique within a |
| 84 | + /// function, so what is known about one holds wherever it is in |
| 85 | + /// scope, and one map serves every branch.) |
| 86 | + fn chain( |
| 87 | + &mut self, |
| 88 | + program: &mut Program, |
| 89 | + e: Expr, |
| 90 | + known: &mut HashMap<VarId, (FnId, Vec<Atom>)>, |
| 91 | + called: &HashMap<FnId, HashSet<VarId>>, |
| 92 | + ) -> Expr { |
| 93 | + let (lets, end) = split(e); |
| 94 | + let mut out = Vec::with_capacity(lets.len()); |
| 95 | + for (v, value, span) in lets { |
| 96 | + let value = self.value(program, value, known, called); |
| 97 | + match &value { |
| 98 | + Value::Closure(g, caps) => { |
| 99 | + known.insert(v, (*g, caps.clone())); |
| 100 | + } |
| 101 | + _ => { |
| 102 | + known.remove(&v); |
| 103 | + } |
| 104 | + } |
| 105 | + out.push((v, value, span)); |
| 106 | + } |
| 107 | + let end = match end { |
| 108 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 109 | + on, |
| 110 | + cases: cases |
| 111 | + .into_iter() |
| 112 | + .map(|(t, b)| (t, self.chain(program, b, known, called))) |
| 113 | + .collect(), |
| 114 | + default: default.map(|d| Box::new(self.chain(program, *d, known, called))), |
| 115 | + }, |
| 116 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 117 | + on, |
| 118 | + cases: cases |
| 119 | + .into_iter() |
| 120 | + .map(|(c, b)| (c, self.chain(program, b, known, called))) |
| 121 | + .collect(), |
| 122 | + default: Box::new(self.chain(program, *default, known, called)), |
| 123 | + }, |
| 124 | + end => end, |
| 125 | + }; |
| 126 | + rebuild(out, end) |
| 127 | + } |
| 128 | + |
| 129 | + fn value( |
| 130 | + &mut self, |
| 131 | + program: &mut Program, |
| 132 | + value: Value, |
| 133 | + known: &mut HashMap<VarId, (FnId, Vec<Atom>)>, |
| 134 | + called: &HashMap<FnId, HashSet<VarId>>, |
| 135 | + ) -> Value { |
| 136 | + match value { |
| 137 | + Value::Block(b) => Value::Block(Box::new(self.chain(program, *b, known, called))), |
| 138 | + Value::CallFn(g, args) => self.call_site(program, g, args, known, called), |
| 139 | + value => value, |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + /// A direct call of `g`: to a copy specialised on the known closures |
| 144 | + /// among its arguments that `g` actually calls, made if needed and |
| 145 | + /// the budgets allow; else unchanged. |
| 146 | + fn call_site( |
| 147 | + &mut self, |
| 148 | + program: &mut Program, |
| 149 | + g: FnId, |
| 150 | + args: Vec<Atom>, |
| 151 | + known: &HashMap<VarId, (FnId, Vec<Atom>)>, |
| 152 | + called: &HashMap<FnId, HashSet<VarId>>, |
| 153 | + ) -> Value { |
| 154 | + let Some(called_g) = called.get(&g) else { |
| 155 | + return Value::CallFn(g, args); |
| 156 | + }; |
| 157 | + let decl = &program.fns[g as usize]; |
| 158 | + if decl.params.len() != args.len() { |
| 159 | + return Value::CallFn(g, args); |
| 160 | + } |
| 161 | + let mut spec: Spec = vec![None; args.len()]; |
| 162 | + let mut any = false; |
| 163 | + for (i, a) in args.iter().enumerate() { |
| 164 | + let Atom::Var(x) = a else { continue }; |
| 165 | + let Some(&(lam, ref caps)) = known.get(x) else { |
| 166 | + continue; |
| 167 | + }; |
| 168 | + // Only a parameter `g` calls is worth specialising on. |
| 169 | + if !called_g.contains(&decl.params[i]) { |
| 170 | + continue; |
| 171 | + } |
| 172 | + spec[i] = Some((lam, caps.len() as u32)); |
| 173 | + any = true; |
| 174 | + } |
| 175 | + if !any { |
| 176 | + return Value::CallFn(g, args); |
| 177 | + } |
| 178 | + let Some(copy) = self.copy_for(program, g, &spec) else { |
| 179 | + return Value::CallFn(g, args); |
| 180 | + }; |
| 181 | + // The closure arguments become their captures. |
| 182 | + let mut out = Vec::with_capacity(args.len()); |
| 183 | + for (a, s) in args.into_iter().zip(&spec) { |
| 184 | + match s { |
| 185 | + Some(_) => { |
| 186 | + let Atom::Var(x) = a else { |
| 187 | + unreachable!("checked above") |
| 188 | + }; |
| 189 | + out.extend(known[&x].1.iter().cloned()); |
| 190 | + } |
| 191 | + None => out.push(a), |
| 192 | + } |
| 193 | + } |
| 194 | + Value::CallFn(copy, out) |
| 195 | + } |
| 196 | + |
| 197 | + /// The copy of `g` specialised as `spec` asks, registered if needed |
| 198 | + /// and the budgets allow. |
| 199 | + fn copy_for(&mut self, program: &mut Program, g: FnId, spec: &Spec) -> Option<FnId> { |
| 200 | + if let Some(copy) = self.copies.get(&(g, spec.clone())) { |
| 201 | + return Some(*copy); |
| 202 | + } |
| 203 | + let per_function = self.per_function.entry(g).or_insert(0); |
| 204 | + if *per_function >= COPIES_PER_FUNCTION || self.budget == 0 { |
| 205 | + return None; |
| 206 | + } |
| 207 | + *per_function += 1; |
| 208 | + self.budget -= 1; |
| 209 | + let decl = &program.fns[g as usize]; |
| 210 | + let names: Vec<&str> = spec |
| 211 | + .iter() |
| 212 | + .flatten() |
| 213 | + .map(|(lam, _)| program.fns[*lam as usize].name.as_str()) |
| 214 | + .collect(); |
| 215 | + let copy = FnDecl { |
| 216 | + name: format!("{} [{}]", decl.name, names.join(", ")), |
| 217 | + // Built from the original's, later (`build_copy`). |
| 218 | + params: decl.params.clone(), |
| 219 | + body: Expr::Return(Atom::Unit), |
| 220 | + n_vars: decl.n_vars, |
| 221 | + // Perceus decides borrows after this pass; the copy's |
| 222 | + // parameter list has a different shape anyway. |
| 223 | + borrowed: Default::default(), |
| 224 | + span: decl.span, |
| 225 | + // Copies have a unit of their own (ADR 0029). |
| 226 | + module: None, |
| 227 | + shapes: decl.shapes.clone(), |
| 228 | + fip: decl.fip, |
| 229 | + }; |
| 230 | + program.fns.push(copy); |
| 231 | + let id = (program.fns.len() - 1) as FnId; |
| 232 | + self.copies.insert((g, spec.clone()), id); |
| 233 | + self.queue.push((id, g, spec.clone())); |
| 234 | + Some(id) |
| 235 | + } |
| 236 | +} |
| 237 | + |
| 238 | +/// Build the copy of `original` specialised as `spec` asks: the closure |
| 239 | +/// parameters replaced by their lambdas' captures, the calls of them |
| 240 | +/// direct, and recursion to the copy itself. |
| 241 | +fn build_copy(program: &mut Program, copy: FnId, original: FnId, spec: &Spec) { |
| 242 | + let decl = &program.fns[original as usize]; |
| 243 | + let body = decl.body.clone(); |
| 244 | + let mut n_vars = decl.n_vars; |
| 245 | + // The specialised parameters, their lambdas, and the captures' fresh |
| 246 | + // variables (which take the parameters' place in the copy's own |
| 247 | + // parameter list, in order). |
| 248 | + let mut specialised: Vec<(VarId, FnId, Vec<VarId>)> = Vec::new(); |
| 249 | + let mut params = Vec::new(); |
| 250 | + for (p, s) in decl.params.iter().zip(spec) { |
| 251 | + match s { |
| 252 | + Some((lam, ncaps)) => { |
| 253 | + let caps: Vec<VarId> = (0..*ncaps) |
| 254 | + .map(|_| { |
| 255 | + let v = n_vars; |
| 256 | + n_vars += 1; |
| 257 | + v |
| 258 | + }) |
| 259 | + .collect(); |
| 260 | + specialised.push((*p, *lam, caps.clone())); |
| 261 | + params.extend(caps); |
| 262 | + } |
| 263 | + None => params.push(*p), |
| 264 | + } |
| 265 | + } |
| 266 | + let body = rewrite_body(body, original, copy, &decl.params, &specialised); |
| 267 | + // A specialised parameter that is still used somewhere (stored, or |
| 268 | + // passed to another function) gets its closure rebuilt at the top; |
| 269 | + // the simplifier's dead-let elimination removes it when there are no |
| 270 | + // such uses left. |
| 271 | + let mut body = body; |
| 272 | + for (p, lam, caps) in &specialised { |
| 273 | + let closure = Value::Closure(*lam, caps.iter().map(|c| Atom::Var(*c)).collect()); |
| 274 | + body = Expr::Let(*p, Box::new(closure), Box::new(body), None); |
| 275 | + } |
| 276 | + let copy_decl = &mut program.fns[copy as usize]; |
| 277 | + copy_decl.params = params; |
| 278 | + copy_decl.body = body; |
| 279 | + copy_decl.n_vars = n_vars; |
| 280 | +} |
| 281 | + |
| 282 | +/// `body` of the original, rewritten for the copy. |
| 283 | +fn rewrite_body( |
| 284 | + body: Expr, |
| 285 | + original: FnId, |
| 286 | + copy: FnId, |
| 287 | + original_params: &[VarId], |
| 288 | + specialised: &[(VarId, FnId, Vec<VarId>)], |
| 289 | +) -> Expr { |
| 290 | + let (lets, end) = split(body); |
| 291 | + let out: Vec<(VarId, Value, Option<Span>)> = lets |
| 292 | + .into_iter() |
| 293 | + .map(|(v, value, span)| { |
| 294 | + ( |
| 295 | + v, |
| 296 | + rewrite_value(value, original, copy, original_params, specialised), |
| 297 | + span, |
| 298 | + ) |
| 299 | + }) |
| 300 | + .collect(); |
| 301 | + let end = match end { |
| 302 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 303 | + on, |
| 304 | + cases: cases |
| 305 | + .into_iter() |
| 306 | + .map(|(t, b)| { |
| 307 | + ( |
| 308 | + t, |
| 309 | + rewrite_body(b, original, copy, original_params, specialised), |
| 310 | + ) |
| 311 | + }) |
| 312 | + .collect(), |
| 313 | + default: default.map(|d| { |
| 314 | + Box::new(rewrite_body( |
| 315 | + *d, |
| 316 | + original, |
| 317 | + copy, |
| 318 | + original_params, |
| 319 | + specialised, |
| 320 | + )) |
| 321 | + }), |
| 322 | + }, |
| 323 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 324 | + on, |
| 325 | + cases: cases |
| 326 | + .into_iter() |
| 327 | + .map(|(c, b)| { |
| 328 | + ( |
| 329 | + c, |
| 330 | + rewrite_body(b, original, copy, original_params, specialised), |
| 331 | + ) |
| 332 | + }) |
| 333 | + .collect(), |
| 334 | + default: Box::new(rewrite_body( |
| 335 | + *default, |
| 336 | + original, |
| 337 | + copy, |
| 338 | + original_params, |
| 339 | + specialised, |
| 340 | + )), |
| 341 | + }, |
| 342 | + end => end, |
| 343 | + }; |
| 344 | + rebuild(out, end) |
| 345 | +} |
| 346 | + |
| 347 | +fn rewrite_value( |
| 348 | + value: Value, |
| 349 | + original: FnId, |
| 350 | + copy: FnId, |
| 351 | + original_params: &[VarId], |
| 352 | + specialised: &[(VarId, FnId, Vec<VarId>)], |
| 353 | +) -> Value { |
| 354 | + match value { |
| 355 | + // A call of a specialised parameter: a direct call of its lambda |
| 356 | + // (captures first, ir.rs's convention). |
| 357 | + Value::Call(Atom::Var(f), args) => match specialised.iter().find(|(p, _, _)| *p == f) { |
| 358 | + Some((_, lam, caps)) => { |
| 359 | + let mut all: Vec<Atom> = caps.iter().map(|c| Atom::Var(*c)).collect(); |
| 360 | + all.extend(args); |
| 361 | + Value::CallFn(*lam, all) |
| 362 | + } |
| 363 | + None => Value::Call(Atom::Var(f), args), |
| 364 | + }, |
| 365 | + // A recursive call that passes every specialised parameter along |
| 366 | + // unchanged calls the copy; anything else still calls the |
| 367 | + // original. |
| 368 | + Value::CallFn(g, args) if g == original => { |
| 369 | + let pass_along = specialised.iter().all(|(p, _, _)| { |
| 370 | + original_params |
| 371 | + .iter() |
| 372 | + .position(|op| op == p) |
| 373 | + .is_some_and(|i| matches!(args.get(i), Some(Atom::Var(x)) if x == p)) |
| 374 | + }); |
| 375 | + if !pass_along { |
| 376 | + Value::CallFn(g, args) |
| 377 | + } else { |
| 378 | + let mut out: Vec<Atom> = Vec::with_capacity(args.len()); |
| 379 | + for (i, a) in args.into_iter().enumerate() { |
| 380 | + match specialised |
| 381 | + .iter() |
| 382 | + .find(|(p, _, _)| original_params.get(i) == Some(p)) |
| 383 | + { |
| 384 | + Some((_, _, caps)) => out.extend(caps.iter().map(|c| Atom::Var(*c))), |
| 385 | + None => out.push(a), |
| 386 | + } |
| 387 | + } |
| 388 | + Value::CallFn(copy, out) |
| 389 | + } |
| 390 | + } |
| 391 | + Value::Block(b) => Value::Block(Box::new(rewrite_body( |
| 392 | + *b, |
| 393 | + original, |
| 394 | + copy, |
| 395 | + original_params, |
| 396 | + specialised, |
| 397 | + ))), |
| 398 | + value => value, |
| 399 | + } |
| 400 | +} |
| 401 | + |
| 402 | +/// The parameters of `f` that are called as closures somewhere in its |
| 403 | +/// body (`call p(…)`): only those are worth specialising on. |
| 404 | +fn called_params(f: &FnDecl) -> HashSet<VarId> { |
| 405 | + let params: HashSet<VarId> = f.params.iter().copied().collect(); |
| 406 | + let mut out = HashSet::new(); |
| 407 | + visit_values(&f.body, &mut |v| { |
| 408 | + if let Value::Call(Atom::Var(p), _) = v |
| 409 | + && params.contains(p) |
| 410 | + { |
| 411 | + out.insert(*p); |
| 412 | + } |
| 413 | + }); |
| 414 | + out |
| 415 | +} |