| @@ -27,8 +27,21 @@ |
| 27 | 27 | //! the stack). The chunks of a split function (`opt::split`, issue #281) |
| 28 | 28 | //! are one function for this rule: their boundaries must stay tail calls, |
| 29 | 29 | //! as a recursive group's do. |
| 30 | +//! |
| 31 | +//! The inference is interprocedural, bottom-up over the call graph |
| 32 | +//! (issue #336): the functions are grouped into *units* — a recursive |
| 33 | +//! group (`callgraph::recursive_groups`), merged with the chunks split |
| 34 | +//! from its functions, since the tail-call rule crosses those boundaries |
| 35 | +//! — and each unit's fixpoint runs once the units it calls are final, so |
| 36 | +//! a call's argument is consuming exactly when the callee's parameter is |
| 37 | +//! owned in the callee's *final* signature. Within a unit the rules |
| 38 | +//! above iterate to their greatest fixpoint; across units the |
| 39 | +//! callee-first order is the fixpoint. The result is the same greatest |
| 40 | +//! fixpoint a whole-program loop computes (a monotone removal system |
| 41 | +//! decomposed over the units' DAG); the order only makes it |
| 42 | +//! one-pass-per-unit instead of re-scanning the program. |
| 30 | 43 | |
| 31 | | −use std::collections::BTreeSet; |
| 44 | +use std::collections::{BTreeMap, BTreeSet, HashMap}; |
| 32 | 45 | |
| 33 | 46 | use louise_core::callgraph::recursive_groups; |
| 34 | 47 | use louise_core::ir::{Atom, Expr, FnId, Program, Value, VarId}; |
| @@ -46,7 +59,7 @@ pub(crate) fn infer(program: &mut Program, live: &BTreeSet<FnId>) { |
| 46 | 59 | return; |
| 47 | 60 | } |
| 48 | 61 | let closures = closure_targets(program, live); |
| 49 | | − let group = recursive_groups(program); |
| 62 | + let unit = units(program, &recursive_groups(program)); |
| 50 | 63 | let mut borrowed: Vec<BTreeSet<usize>> = program |
| 51 | 64 | .fns |
| 52 | 65 | .iter() |
| @@ -72,42 +85,42 @@ pub(crate) fn infer(program: &mut Program, live: &BTreeSet<FnId>) { |
| 72 | 85 | .collect() |
| 73 | 86 | }) |
| 74 | 87 | .collect(); |
| 75 | | − loop { |
| 76 | | − let mut owned: Vec<(usize, usize)> = Vec::new(); |
| 77 | | − for &id in live { |
| 78 | | − let id = id as usize; |
| 79 | | − let f = &program.fns[id]; |
| 80 | | − let borrows = |g: FnId, i: usize| borrowed[g as usize].contains(&i); |
| 81 | | − for i in &borrowed[id] { |
| 82 | | − if consumes(&f.body, f.params[*i], &borrows, &program.owned) { |
| 83 | | − owned.push((id, *i)); |
| 84 | | − } |
| 85 | | − } |
| 86 | | − let mut reads: BTreeSet<VarId> = borrowed[id].iter().map(|i| f.params[*i]).collect(); |
| 87 | | − projections_of(&f.body, &mut reads); |
| 88 | | − tail_calls(&f.body, &mut |g, args| { |
| 89 | | − if group[g as usize] != group[id] |
| 90 | | − && split_origin(&program.fns[g as usize].name) |
| 91 | | − != split_origin(&program.fns[id].name) |
| 92 | | − { |
| 93 | | − return; |
| 94 | | − } |
| 95 | | − for (i, a) in args.iter().enumerate() { |
| 96 | | − if let Atom::Var(x) = a |
| 97 | | − && !reads.contains(x) |
| 98 | | − && borrows(g, i) |
| 99 | | − { |
| 100 | | − owned.push((g as usize, i)); |
| 88 | + for members in callees_first(program, live, &unit) { |
| 89 | + loop { |
| 90 | + let mut owned: Vec<(usize, usize)> = Vec::new(); |
| 91 | + for &id in &members { |
| 92 | + let id = id as usize; |
| 93 | + let f = &program.fns[id]; |
| 94 | + let borrows = |g: FnId, i: usize| borrowed[g as usize].contains(&i); |
| 95 | + for i in &borrowed[id] { |
| 96 | + if consumes(&f.body, f.params[*i], &borrows, &program.owned) { |
| 97 | + owned.push((id, *i)); |
| 101 | 98 | } |
| 102 | 99 | } |
| 103 | | − }); |
| 104 | | − } |
| 105 | | − let mut changed = false; |
| 106 | | − for (f, i) in owned { |
| 107 | | − changed |= borrowed[f].remove(&i); |
| 108 | | − } |
| 109 | | − if !changed { |
| 110 | | − break; |
| 100 | + let mut reads: BTreeSet<VarId> = |
| 101 | + borrowed[id].iter().map(|i| f.params[*i]).collect(); |
| 102 | + projections_of(&f.body, &mut reads); |
| 103 | + tail_calls(&f.body, &mut |g, args| { |
| 104 | + if unit[g as usize] != unit[id] { |
| 105 | + return; |
| 106 | + } |
| 107 | + for (i, a) in args.iter().enumerate() { |
| 108 | + if let Atom::Var(x) = a |
| 109 | + && !reads.contains(x) |
| 110 | + && borrows(g, i) |
| 111 | + { |
| 112 | + owned.push((g as usize, i)); |
| 113 | + } |
| 114 | + } |
| 115 | + }); |
| 116 | + } |
| 117 | + let mut changed = false; |
| 118 | + for (f, i) in owned { |
| 119 | + changed |= borrowed[f].remove(&i); |
| 120 | + } |
| 121 | + if !changed { |
| 122 | + break; |
| 123 | + } |
| 111 | 124 | } |
| 112 | 125 | } |
| 113 | 126 | for (f, b) in program.fns.iter_mut().zip(borrowed) { |
| @@ -121,6 +134,101 @@ fn split_origin(name: &str) -> &str { |
| 121 | 134 | name.split("$split").next().unwrap_or(name) |
| 122 | 135 | } |
| 123 | 136 | |
| 137 | +/// The borrow-inference unit of each function: its recursive group, |
| 138 | +/// merged (union-find over the group ids) with the groups of every |
| 139 | +/// function sharing a split origin. A split chain `f`, `f$split1`, … is |
| 140 | +/// one unit, so the tail-call rule's "same function" is the whole chain; |
| 141 | +/// when `f` is also in a recursive group, the group and the chain are |
| 142 | +/// one unit too, and a chunk's tail call into the group forces owned |
| 143 | +/// parameters exactly as a group's internal tail calls do. |
| 144 | +fn units(program: &Program, group: &[usize]) -> Vec<usize> { |
| 145 | + fn find(parent: &mut [usize], x: usize) -> usize { |
| 146 | + let mut root = x; |
| 147 | + while parent[root] != root { |
| 148 | + root = parent[root]; |
| 149 | + } |
| 150 | + // Halve the path as it is walked back. |
| 151 | + let mut x = x; |
| 152 | + while parent[x] != root { |
| 153 | + let next = parent[x]; |
| 154 | + parent[x] = root; |
| 155 | + x = next; |
| 156 | + } |
| 157 | + root |
| 158 | + } |
| 159 | + let n = program.fns.len(); |
| 160 | + let mut parent: Vec<usize> = (0..n).collect(); |
| 161 | + let mut by_origin: HashMap<&str, usize> = HashMap::new(); |
| 162 | + for (id, f) in program.fns.iter().enumerate() { |
| 163 | + let g = find(&mut parent, group[id]); |
| 164 | + match by_origin.entry(split_origin(&f.name)) { |
| 165 | + std::collections::hash_map::Entry::Occupied(mut o) => { |
| 166 | + let first = find(&mut parent, *o.get()); |
| 167 | + if first != g { |
| 168 | + parent[first] = g; |
| 169 | + } |
| 170 | + o.insert(g); |
| 171 | + } |
| 172 | + std::collections::hash_map::Entry::Vacant(v) => { |
| 173 | + v.insert(g); |
| 174 | + } |
| 175 | + } |
| 176 | + } |
| 177 | + (0..n).map(|id| find(&mut parent, group[id])).collect() |
| 178 | +} |
| 179 | + |
| 180 | +/// The units of the functions in `live`, callees first (the unit graph |
| 181 | +/// is the call graph's condensation, merged by split origin: a DAG), each |
| 182 | +/// as its member functions. A unit's fixpoint then reads the *final* |
| 183 | +/// borrowed sets of everything it calls outside the unit; only its own |
| 184 | +/// members' sets are still moving. |
| 185 | +fn callees_first(program: &Program, live: &BTreeSet<FnId>, unit: &[usize]) -> Vec<Vec<FnId>> { |
| 186 | + let mut members: BTreeMap<usize, Vec<FnId>> = BTreeMap::new(); |
| 187 | + for &id in live { |
| 188 | + members.entry(unit[id as usize]).or_default().push(id); |
| 189 | + } |
| 190 | + // unit -> the other units it calls directly. |
| 191 | + let mut calls: BTreeMap<usize, BTreeSet<usize>> = BTreeMap::new(); |
| 192 | + for (&u, fns) in &members { |
| 193 | + let mut out = BTreeSet::new(); |
| 194 | + for &id in fns { |
| 195 | + visit_values(&program.fns[id as usize].body, &mut |v| { |
| 196 | + if let Value::CallFn(g, _) = v |
| 197 | + && live.contains(g) |
| 198 | + { |
| 199 | + let ug = unit[*g as usize]; |
| 200 | + if ug != u { |
| 201 | + out.insert(ug); |
| 202 | + } |
| 203 | + } |
| 204 | + }); |
| 205 | + } |
| 206 | + calls.insert(u, out); |
| 207 | + } |
| 208 | + // Post-order over the unit DAG: every callee unit before its callers. |
| 209 | + let mut order: Vec<usize> = Vec::new(); |
| 210 | + let mut seen: BTreeSet<usize> = BTreeSet::new(); |
| 211 | + for &root in members.keys() { |
| 212 | + let mut stack = vec![(root, false)]; |
| 213 | + while let Some((u, done)) = stack.pop() { |
| 214 | + if done { |
| 215 | + order.push(u); |
| 216 | + continue; |
| 217 | + } |
| 218 | + if !seen.insert(u) { |
| 219 | + continue; |
| 220 | + } |
| 221 | + stack.push((u, true)); |
| 222 | + for &g in &calls[&u] { |
| 223 | + if !seen.contains(&g) { |
| 224 | + stack.push((g, false)); |
| 225 | + } |
| 226 | + } |
| 227 | + } |
| 228 | + } |
| 229 | + order.into_iter().map(|u| members[&u].clone()).collect() |
| 230 | +} |
| 231 | + |
| 124 | 232 | /// Functions made into closures somewhere in `live`. |
| 125 | 233 | fn closure_targets(program: &Program, live: &BTreeSet<FnId>) -> BTreeSet<FnId> { |
| 126 | 234 | let mut out = BTreeSet::new(); |
| @@ -304,3 +412,229 @@ fn visit_lets(e: &Expr, f: &mut impl FnMut(VarId, &Value)) { |
| 304 | 412 | Expr::Return(_) | Expr::Exit(_) | Expr::Panic(_) | Expr::ReturnN(_) => {} |
| 305 | 413 | } |
| 306 | 414 | } |
| 415 | + |
| 416 | +#[cfg(test)] |
| 417 | +mod tests { |
| 418 | + use super::*; |
| 419 | + use louise_core::ir::FnDecl; |
| 420 | + |
| 421 | + /// `fn name(p0, …, p{n-1}) { body }` with `n_vars` variables. |
| 422 | + fn f(name: &str, params: u32, n_vars: u32, body: Expr) -> FnDecl { |
| 423 | + FnDecl { |
| 424 | + name: name.to_owned(), |
| 425 | + params: (0..params).collect(), |
| 426 | + body, |
| 427 | + n_vars, |
| 428 | + borrowed: Default::default(), |
| 429 | + span: None, |
| 430 | + module: None, |
| 431 | + shapes: Default::default(), |
| 432 | + fip: false, |
| 433 | + cpr_arity: None, |
| 434 | + unbox_sig: None, |
| 435 | + } |
| 436 | + } |
| 437 | + |
| 438 | + fn program(fns: Vec<FnDecl>) -> Program { |
| 439 | + Program { |
| 440 | + fns, |
| 441 | + effects: Vec::new(), |
| 442 | + blocking: Default::default(), |
| 443 | + owned: Default::default(), |
| 444 | + actor_caps: Vec::new(), |
| 445 | + root_caps: Default::default(), |
| 446 | + } |
| 447 | + } |
| 448 | + |
| 449 | + /// `let v = g(args); v` — a tail call. |
| 450 | + fn tail_call(v: VarId, g: FnId, args: Vec<Atom>) -> Expr { |
| 451 | + Expr::Let( |
| 452 | + v, |
| 453 | + Box::new(Value::CallFn(g, args)), |
| 454 | + Box::new(Expr::Return(Atom::Var(v))), |
| 455 | + None, |
| 456 | + ) |
| 457 | + } |
| 458 | + |
| 459 | + /// The borrowed parameters of every function, after inference. |
| 460 | + fn infer_all(p: &mut Program) -> Vec<BTreeSet<usize>> { |
| 461 | + let live = (0..p.fns.len() as FnId).collect(); |
| 462 | + infer(p, &live); |
| 463 | + p.fns.iter().map(|f| f.borrowed.clone()).collect() |
| 464 | + } |
| 465 | + |
| 466 | + #[test] |
| 467 | + fn passed_to_a_borrowed_parameter_is_not_consuming() { |
| 468 | + // g(q) = (): g borrows q; f(p) = g(p): f borrows p too, however |
| 469 | + // the functions are ordered (callees are final first). |
| 470 | + let mut p = program(vec![ |
| 471 | + f("f", 1, 2, tail_call(1, 1, vec![Atom::Var(0)])), |
| 472 | + f("g", 1, 1, Expr::Return(Atom::Unit)), |
| 473 | + ]); |
| 474 | + let b = infer_all(&mut p); |
| 475 | + assert_eq!(b[0], BTreeSet::from([0]), "f borrows p"); |
| 476 | + assert_eq!(b[1], BTreeSet::from([0]), "g borrows q"); |
| 477 | + } |
| 478 | + |
| 479 | + #[test] |
| 480 | + fn passed_to_an_owned_parameter_is_consuming() { |
| 481 | + // g(q) = q: g owns q (it returns it); f(p) = g(p) owns p. |
| 482 | + let mut p = program(vec![ |
| 483 | + f("f", 1, 2, tail_call(1, 1, vec![Atom::Var(0)])), |
| 484 | + f("g", 1, 1, Expr::Return(Atom::Var(0))), |
| 485 | + ]); |
| 486 | + let b = infer_all(&mut p); |
| 487 | + assert!(b[0].is_empty(), "f owns p"); |
| 488 | + assert!(b[1].is_empty(), "g owns q"); |
| 489 | + } |
| 490 | + |
| 491 | + #[test] |
| 492 | + fn consumption_propagates_through_a_call_chain() { |
| 493 | + // h(r) = r; g(q) = h(q); f(p) = g(p): every parameter owned, by |
| 494 | + // propagation, not by re-scanning the whole program. |
| 495 | + let mut p = program(vec![ |
| 496 | + f("f", 1, 2, tail_call(1, 1, vec![Atom::Var(0)])), |
| 497 | + f("g", 1, 2, tail_call(1, 2, vec![Atom::Var(0)])), |
| 498 | + f("h", 1, 1, Expr::Return(Atom::Var(0))), |
| 499 | + ]); |
| 500 | + let b = infer_all(&mut p); |
| 501 | + assert!(b.iter().all(BTreeSet::is_empty), "{b:?}"); |
| 502 | + } |
| 503 | + |
| 504 | + #[test] |
| 505 | + fn a_tail_call_in_the_group_forces_owned() { |
| 506 | + // f(x, y) = let v = h(y); f(x, v), h borrowing its parameter: |
| 507 | + // nothing consumes y, but the recursive tail call passes f's own |
| 508 | + // owned v to y's parameter, so y stays owned (dropping it after |
| 509 | + // the call would break the musttail); x, passed along, stays |
| 510 | + // borrowed. |
| 511 | + let mut p = program(vec![ |
| 512 | + f( |
| 513 | + "f", |
| 514 | + 2, |
| 515 | + 3, |
| 516 | + Expr::Let( |
| 517 | + 2, |
| 518 | + Box::new(Value::CallFn(1, vec![Atom::Var(1)])), |
| 519 | + Box::new(tail_call(2, 0, vec![Atom::Var(0), Atom::Var(2)])), |
| 520 | + None, |
| 521 | + ), |
| 522 | + ), |
| 523 | + f("h", 1, 1, Expr::Return(Atom::Unit)), |
| 524 | + ]); |
| 525 | + let b = infer_all(&mut p); |
| 526 | + assert_eq!(b[0], BTreeSet::from([0]), "x borrowed, y owned: {:?}", b[0]); |
| 527 | + } |
| 528 | + |
| 529 | + #[test] |
| 530 | + fn split_chunks_are_one_unit_for_the_tail_call_rule() { |
| 531 | + // f$split1(q) = let v = h(q); f$split2(q, v) (tail); f$split2 |
| 532 | + // borrows both parameters, h borrows. Nothing consumes v, but |
| 533 | + // the chunk boundary must stay a tail call, so f$split2's second |
| 534 | + // parameter is owned — the chunks are one unit though each is |
| 535 | + // its own recursive group. |
| 536 | + let mut p = program(vec![ |
| 537 | + f("f", 1, 2, tail_call(1, 1, vec![Atom::Var(0)])), |
| 538 | + f( |
| 539 | + "f$split1", |
| 540 | + 1, |
| 541 | + 3, |
| 542 | + Expr::Let( |
| 543 | + 1, |
| 544 | + Box::new(Value::CallFn(3, vec![Atom::Var(0)])), |
| 545 | + Box::new(tail_call(2, 2, vec![Atom::Var(0), Atom::Var(1)])), |
| 546 | + None, |
| 547 | + ), |
| 548 | + ), |
| 549 | + f("f$split2", 2, 2, Expr::Return(Atom::Unit)), |
| 550 | + f("h", 1, 1, Expr::Return(Atom::Unit)), |
| 551 | + ]); |
| 552 | + let b = infer_all(&mut p); |
| 553 | + assert_eq!(b[2], BTreeSet::from([0]), "f$split2: r borrowed, s owned"); |
| 554 | + assert_eq!(b[1], BTreeSet::from([0]), "f$split1 borrows q"); |
| 555 | + } |
| 556 | + |
| 557 | + #[test] |
| 558 | + fn a_chunk_tail_call_into_the_group_forces_owned() { |
| 559 | + // f and g are mutually recursive (one group); f$split1, a chunk |
| 560 | + // of f, tail-calls g with an owned value for g's second |
| 561 | + // parameter. The merged unit forces it owned (a group boundary |
| 562 | + // alone would not), and the ownedness cascades back through the |
| 563 | + // group. |
| 564 | + let mut p = program(vec![ |
| 565 | + // f(x) = g(x, x) (tail) |
| 566 | + f("f", 1, 2, tail_call(1, 1, vec![Atom::Var(0), Atom::Var(0)])), |
| 567 | + // g(y, z) = f(y) (tail) |
| 568 | + f("g", 2, 3, tail_call(2, 0, vec![Atom::Var(0)])), |
| 569 | + // h(w) = () |
| 570 | + f("h", 1, 1, Expr::Return(Atom::Unit)), |
| 571 | + // f$split1(q) = let v1 = h(q); let v2 = g(q, v1); v2 (tail) |
| 572 | + f( |
| 573 | + "f$split1", |
| 574 | + 1, |
| 575 | + 3, |
| 576 | + Expr::Let( |
| 577 | + 1, |
| 578 | + Box::new(Value::CallFn(2, vec![Atom::Var(0)])), |
| 579 | + Box::new(tail_call(2, 1, vec![Atom::Var(0), Atom::Var(1)])), |
| 580 | + None, |
| 581 | + ), |
| 582 | + ), |
| 583 | + ]); |
| 584 | + let b = infer_all(&mut p); |
| 585 | + assert!(b[1].is_empty(), "g owns both parameters: {:?}", b[1]); |
| 586 | + assert!(b[0].is_empty(), "f owns x: {:?}", b[0]); |
| 587 | + assert_eq!(b[3], BTreeSet::new(), "f$split1 owns q: {:?}", b[3]); |
| 588 | + assert_eq!(b[2], BTreeSet::from([0]), "h borrows w"); |
| 589 | + } |
| 590 | + |
| 591 | + #[test] |
| 592 | + fn a_cross_unit_tail_call_may_borrow() { |
| 593 | + // f(p) = g(p) (tail), g(q) = (): different units, so the |
| 594 | + // owned-forcing rule does not apply; the call is not a musttail |
| 595 | + // (the caller drops after it: one frame, bounded chain). |
| 596 | + let mut p = program(vec![ |
| 597 | + f("f", 1, 2, tail_call(1, 1, vec![Atom::Var(0)])), |
| 598 | + f("g", 1, 1, Expr::Return(Atom::Unit)), |
| 599 | + ]); |
| 600 | + let b = infer_all(&mut p); |
| 601 | + assert_eq!(b[0], BTreeSet::from([0])); |
| 602 | + assert_eq!(b[1], BTreeSet::from([0])); |
| 603 | + } |
| 604 | + |
| 605 | + #[test] |
| 606 | + fn mutual_recursion_iterates_to_the_fixpoint() { |
| 607 | + // f(x) = g(x) (tail); g(y) = f(y) (tail): one unit. Both pass |
| 608 | + // the other's parameter along: both borrowed. |
| 609 | + let mut p = program(vec![ |
| 610 | + f("f", 1, 2, tail_call(1, 1, vec![Atom::Var(0)])), |
| 611 | + f("g", 1, 2, tail_call(1, 0, vec![Atom::Var(0)])), |
| 612 | + ]); |
| 613 | + let b = infer_all(&mut p); |
| 614 | + assert_eq!(b[0], BTreeSet::from([0])); |
| 615 | + assert_eq!(b[1], BTreeSet::from([0])); |
| 616 | + } |
| 617 | + |
| 618 | + #[test] |
| 619 | + fn a_closure_target_borrows_nothing() { |
| 620 | + // g is made into a closure in f: g's parameter stays owned, and |
| 621 | + // f's direct call of it consumes. |
| 622 | + let mut p = program(vec![ |
| 623 | + f( |
| 624 | + "f", |
| 625 | + 1, |
| 626 | + 3, |
| 627 | + Expr::Let( |
| 628 | + 1, |
| 629 | + Box::new(Value::Closure(1, Vec::new())), |
| 630 | + Box::new(tail_call(2, 1, vec![Atom::Var(0)])), |
| 631 | + None, |
| 632 | + ), |
| 633 | + ), |
| 634 | + f("g", 1, 1, Expr::Return(Atom::Unit)), |
| 635 | + ]); |
| 636 | + let b = infer_all(&mut p); |
| 637 | + assert!(b[1].is_empty(), "a closure's parameters are owned"); |
| 638 | + assert!(b[0].is_empty(), "the call consumes p"); |
| 639 | + } |
| 640 | +} |