| @@ -17,16 +17,18 @@ |
| 17 | 17 | //! fresh names), so what is known about a variable holds wherever it is |
| 18 | 18 | //! in scope, and one map serves every branch. |
| 19 | 19 | |
| 20 | | −use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; |
| 20 | +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; |
| 21 | 21 | use std::rc::Rc; |
| 22 | 22 | |
| 23 | 23 | use crate::ir::{Atom, Expr, FnId, Program, Span, Value, VarId}; |
| 24 | 24 | |
| 25 | | −/// A function of at most this many nodes is inlinable at any site. |
| 26 | | −const SMALL_NODES: u32 = 12; |
| 25 | +/// A function of at most this many nodes is inlinable at any site. (The |
| 26 | +/// `std/iter` combinators measure 15–30: the point of them is that they |
| 27 | +/// dissolve into their caller, issue #199.) |
| 28 | +const SMALL_NODES: u32 = 32; |
| 27 | 29 | /// A bigger non-recursive function is inlinable only where its result is |
| 28 | 30 | /// the caller's (a tail site): nothing after the call is duplicated then. |
| 29 | | −const TAIL_NODES: u32 = 32; |
| 31 | +const TAIL_NODES: u32 = 64; |
| 30 | 32 | /// Rounds of rewriting: the fixed point of the rewrites, capped (one |
| 31 | 33 | /// round can expose another — a known constructor behind an inlined call, |
| 32 | 34 | /// say). |
| @@ -79,6 +81,8 @@ fn function( |
| 79 | 81 | module: decl.module.as_deref().map(Rc::from), |
| 80 | 82 | subst: HashMap::new(), |
| 81 | 83 | known: HashMap::new(), |
| 84 | + switch_blocks: HashMap::new(), |
| 85 | + dead: HashSet::new(), |
| 82 | 86 | next_var: decl.n_vars, |
| 83 | 87 | shapes: std::mem::take(&mut decl.shapes), |
| 84 | 88 | inlined: HashSet::from([id]), |
| @@ -142,9 +146,12 @@ struct Candidate { |
| 142 | 146 | /// modules would make a unit's C depend on another module's body, and |
| 143 | 147 | /// an edit there would recompile it. A caller without a module — |
| 144 | 148 | /// generated code, a specialiser's copy — may inline anything: its |
| 145 | | − /// `+specialised` unit is cross-cutting already. Cross-module calls |
| 146 | | − /// between named modules are fusion's business (issue #198); its |
| 147 | | − /// copies are generated too. |
| 149 | + /// `+specialised` unit is cross-cutting already. And a callee in std |
| 150 | + /// may be inlined anywhere: std ships with the toolchain, so its |
| 151 | + /// units' stability is the toolchain's own (and `std/iter`'s stream |
| 152 | + /// fusion, issue #199, needs it). Other cross-module calls are |
| 153 | + /// specialisation's business (issue #197); its copies are generated |
| 154 | + /// too. |
| 148 | 155 | module: Option<Rc<str>>, |
| 149 | 156 | nodes: u32, |
| 150 | 157 | end: End, |
| @@ -183,6 +190,13 @@ struct Simplify<'a> { |
| 183 | 190 | /// Variables bound to atoms, to substitute (copy propagation). |
| 184 | 191 | subst: HashMap<VarId, Atom>, |
| 185 | 192 | known: HashMap<VarId, Known>, |
| 193 | + /// Variables bound to a block that ends in a switch (`let v = { |
| 194 | + /// switch … }`): for case-of-case — a switch on `v` moves into the |
| 195 | + /// inner arms, where the constructor each arm builds is known. |
| 196 | + switch_blocks: HashMap<VarId, Rc<Expr>>, |
| 197 | + /// `let`s a rewrite consumed (a switch block folded into its user): |
| 198 | + /// dropped when the chain is rebuilt. |
| 199 | + dead: HashSet<VarId>, |
| 186 | 200 | /// Fresh variables: the function's `n_vars`, growing as inlining |
| 187 | 201 | /// brings a callee's variables in. |
| 188 | 202 | next_var: u32, |
| @@ -255,7 +269,9 @@ impl Simplify<'_> { |
| 255 | 269 | if let Value::CallFn(g, args) = &value |
| 256 | 270 | && !self.inlined.contains(g) |
| 257 | 271 | && let Some(cand) = self.candidates.get(g).cloned() |
| 258 | | − && (self.module.is_none() || cand.module == self.module) |
| 272 | + && (self.module.is_none() |
| 273 | + || cand.module == self.module |
| 274 | + || cand.module.as_deref().is_some_and(|m| m.starts_with("std/"))) |
| 259 | 275 | && cand.params.len() == args.len() |
| 260 | 276 | { |
| 261 | 277 | let tail_site = |
| @@ -319,10 +335,20 @@ impl Simplify<'_> { |
| 319 | 335 | } |
| 320 | 336 | } |
| 321 | 337 | out.push((v, value, span)); |
| 338 | + // A block ending in a switch, used once as a later switch's |
| 339 | + // scrutinee, is a case-of-case candidate. |
| 340 | + if let Value::Block(b) = &out.last().expect("just pushed").1 |
| 341 | + && ends_in_switch(b) |
| 342 | + { |
| 343 | + self.switch_blocks.insert(v, Rc::new((**b).clone())); |
| 344 | + } |
| 322 | 345 | } |
| 323 | 346 | let end = self.end(end, uses, exits_ok); |
| 324 | 347 | let mut expr = end; |
| 325 | 348 | for (v, value, span) in out.into_iter().rev() { |
| 349 | + if self.dead.contains(&v) { |
| 350 | + continue; |
| 351 | + } |
| 326 | 352 | expr = Expr::Let(v, Box::new(value), Box::new(expr), span); |
| 327 | 353 | } |
| 328 | 354 | expr |
| @@ -384,6 +410,36 @@ impl Simplify<'_> { |
| 384 | 410 | return self.expr(branch.clone(), uses, exits_ok); |
| 385 | 411 | } |
| 386 | 412 | } |
| 413 | + // Case-of-case: a switch on a value a block computed by a |
| 414 | + // switch. The outer switch moves into the inner arms, |
| 415 | + // where the constructor each arm builds is known — this |
| 416 | + // is what dissolves a stream-fusion pipeline's per-pull |
| 417 | + // `Step` (issue #199). Only when the inner block is free |
| 418 | + // of effects and panics (its `let`s move position) and |
| 419 | + // `v` is used once. |
| 420 | + if let Atom::Var(x) = &on { |
| 421 | + // `x` may be used again by the arms' field |
| 422 | + // projections of it: the gate is "no use outside this |
| 423 | + // switch", so count the scrutinee and the arms. |
| 424 | + let mut inside = 1u32; |
| 425 | + for b in cases.iter().map(|(_, b)| b).chain(default.iter().map(|d| &**d)) { |
| 426 | + visit(b, &mut |a| { |
| 427 | + if *a == Atom::Var(*x) { |
| 428 | + inside += 1; |
| 429 | + } |
| 430 | + }); |
| 431 | + } |
| 432 | + if uses.get(x) == Some(&inside) |
| 433 | + && let Some(inner) = self.switch_blocks.get(x).cloned() |
| 434 | + && block_pure(&inner) |
| 435 | + && let Some(lifted) = |
| 436 | + self.case_of_case(&inner, *x, &cases, default.as_deref(), uses) |
| 437 | + { |
| 438 | + self.dead.insert(*x); |
| 439 | + self.changed = true; |
| 440 | + return self.expr(lifted, uses, exits_ok); |
| 441 | + } |
| 442 | + } |
| 387 | 443 | Expr::Switch { |
| 388 | 444 | on, |
| 389 | 445 | cases: cases |
| @@ -423,6 +479,160 @@ impl Simplify<'_> { |
| 423 | 479 | } |
| 424 | 480 | } |
| 425 | 481 | |
| 482 | + /// Case-of-case: `inner` is `v`'s block, a chain ending in a switch; |
| 483 | + /// the outer switch (`cases`, `default`) moves into each inner arm, |
| 484 | + /// where what the arm built is known to the constructor fold. None if |
| 485 | + /// any arm can't take it, or if the growth is over budget. |
| 486 | + fn case_of_case( |
| 487 | + &mut self, |
| 488 | + inner: &Expr, |
| 489 | + scrutinee: VarId, |
| 490 | + cases: &[(u32, Expr)], |
| 491 | + default: Option<&Expr>, |
| 492 | + uses: &HashMap<VarId, u32>, |
| 493 | + ) -> Option<Expr> { |
| 494 | + let (lets, end) = split(inner.clone()); |
| 495 | + let Expr::Switch { |
| 496 | + on, |
| 497 | + cases: inner_cases, |
| 498 | + default: inner_default, |
| 499 | + } = end |
| 500 | + else { |
| 501 | + return None; |
| 502 | + }; |
| 503 | + // The outer switch is cloned into each inner arm: bounded by the |
| 504 | + // function's growth budget, as inlining's. |
| 505 | + let outer_size: u32 = cases |
| 506 | + .iter() |
| 507 | + .map(|(_, b)| size(b)) |
| 508 | + .sum::<u32>() |
| 509 | + + default.as_ref().map_or(0, |d| size(d)); |
| 510 | + let arms = inner_cases.len() as u32 + inner_default.is_some() as u32; |
| 511 | + let growth = outer_size.saturating_mul(arms); |
| 512 | + if *self.grown + growth > self.cap { |
| 513 | + return None; |
| 514 | + } |
| 515 | + *self.grown += growth; |
| 516 | + // Variables bound by the outer arms are freshened per inner arm |
| 517 | + // (variables are unique within a function), and the scrutinee is |
| 518 | + // the arm's result there. |
| 519 | + let mut bound = BTreeSet::new(); |
| 520 | + for (_, b) in cases { |
| 521 | + collect_bound(b, &mut bound); |
| 522 | + } |
| 523 | + if let Some(d) = default { |
| 524 | + collect_bound(d, &mut bound); |
| 525 | + } |
| 526 | + let mut arms = Vec::new(); |
| 527 | + for (t, body) in inner_cases { |
| 528 | + arms.push(( |
| 529 | + t, |
| 530 | + self.append_switch(body, scrutinee, cases, default, &bound, uses)?, |
| 531 | + )); |
| 532 | + } |
| 533 | + let new_default = match inner_default { |
| 534 | + Some(d) => Some(Box::new(self.append_switch( |
| 535 | + *d, |
| 536 | + scrutinee, |
| 537 | + cases, |
| 538 | + default, |
| 539 | + &bound, |
| 540 | + uses, |
| 541 | + )?)), |
| 542 | + None => None, |
| 543 | + }; |
| 544 | + Some(rebuild( |
| 545 | + lets, |
| 546 | + Expr::Switch { |
| 547 | + on, |
| 548 | + cases: arms, |
| 549 | + default: new_default, |
| 550 | + }, |
| 551 | + )) |
| 552 | + } |
| 553 | + |
| 554 | + /// `body` with the outer switch appended after its result. The arm's |
| 555 | + /// result is the scrutinee there (and what it built is known to the |
| 556 | + /// constructor fold). A panic or an `exit` ends the arm — the outer |
| 557 | + /// switch is never reached. |
| 558 | + fn append_switch( |
| 559 | + &mut self, |
| 560 | + body: Expr, |
| 561 | + scrutinee: VarId, |
| 562 | + cases: &[(u32, Expr)], |
| 563 | + default: Option<&Expr>, |
| 564 | + bound: &BTreeSet<VarId>, |
| 565 | + uses: &HashMap<VarId, u32>, |
| 566 | + ) -> Option<Expr> { |
| 567 | + let (lets, end) = split(body); |
| 568 | + let end = match end { |
| 569 | + Expr::Return(a @ Atom::Var(_)) => { |
| 570 | + // The outer arms as used here: the scrutinee is the |
| 571 | + // arm's result; their bound variables are freshened. |
| 572 | + let mut freshen: HashMap<VarId, VarId> = HashMap::new(); |
| 573 | + for w in bound { |
| 574 | + freshen.insert(*w, self.fresh_var()); |
| 575 | + } |
| 576 | + let m = &mut |w: VarId| { |
| 577 | + if w == scrutinee { |
| 578 | + a.clone() |
| 579 | + } else if let Some(f) = freshen.get(&w) { |
| 580 | + Atom::Var(*f) |
| 581 | + } else { |
| 582 | + Atom::Var(w) |
| 583 | + } |
| 584 | + }; |
| 585 | + Expr::Switch { |
| 586 | + on: a.clone(), |
| 587 | + cases: cases |
| 588 | + .iter() |
| 589 | + .map(|(t, b)| (*t, rename(b, m))) |
| 590 | + .collect(), |
| 591 | + default: default.map(|d| Box::new(rename(d, m))), |
| 592 | + } |
| 593 | + } |
| 594 | + end @ (Expr::Panic(_) | Expr::Exit(_)) => end, |
| 595 | + Expr::Switch { |
| 596 | + on, |
| 597 | + cases: inner_cases, |
| 598 | + default: inner_default, |
| 599 | + } => { |
| 600 | + let mut new_cases = Vec::new(); |
| 601 | + for (t, b) in inner_cases { |
| 602 | + new_cases.push(( |
| 603 | + t, |
| 604 | + self.append_switch(b, scrutinee, cases, default, bound, uses)?, |
| 605 | + )); |
| 606 | + } |
| 607 | + let new_default = match inner_default { |
| 608 | + Some(d) => Some(Box::new(self.append_switch( |
| 609 | + *d, scrutinee, cases, default, bound, uses, |
| 610 | + )?)), |
| 611 | + None => None, |
| 612 | + }; |
| 613 | + Expr::Switch { |
| 614 | + on, |
| 615 | + cases: new_cases, |
| 616 | + default: new_default, |
| 617 | + } |
| 618 | + } |
| 619 | + Expr::Return(_) => return None, // a literal: not a tag switch |
| 620 | + Expr::SwitchLit { .. } => return None, // literals: not a tag switch |
| 621 | + Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 622 | + unreachable!("Core before Perceus") |
| 623 | + } |
| 624 | + Expr::Let(..) => unreachable!("a chain's end is never a `let`"), |
| 625 | + }; |
| 626 | + Some(rebuild(lets, end)) |
| 627 | + } |
| 628 | + |
| 629 | + /// A fresh variable for the enclosing function. |
| 630 | + fn fresh_var(&mut self) -> VarId { |
| 631 | + let v = self.next_var; |
| 632 | + self.next_var += 1; |
| 633 | + v |
| 634 | + } |
| 635 | + |
| 426 | 636 | fn value(&mut self, value: Value, uses: &HashMap<VarId, u32>) -> Value { |
| 427 | 637 | match value { |
| 428 | 638 | Value::Atom(a) => Value::Atom(self.atom(&a)), |
| @@ -812,6 +1022,15 @@ fn rename_atoms(atoms: &[Atom], m: &mut dyn FnMut(VarId) -> Atom) -> Vec<Atom> { |
| 812 | 1022 | atoms.iter().map(|a| rename_atom(a, m)).collect() |
| 813 | 1023 | } |
| 814 | 1024 | |
| 1025 | +/// Every variable a `let` binds in `e`, anywhere in it. |
| 1026 | +fn collect_bound(e: &Expr, out: &mut BTreeSet<VarId>) { |
| 1027 | + visit_exprs(e, &mut |e| { |
| 1028 | + if let Expr::Let(v, _, _, _) = e { |
| 1029 | + out.insert(*v); |
| 1030 | + } |
| 1031 | + }); |
| 1032 | +} |
| 1033 | + |
| 815 | 1034 | /// The chain a body is: how its value leaves it. |
| 816 | 1035 | fn end_of(e: &Expr) -> End { |
| 817 | 1036 | let mut e = e; |
| @@ -825,6 +1044,54 @@ fn end_of(e: &Expr) -> End { |
| 825 | 1044 | } |
| 826 | 1045 | } |
| 827 | 1046 | |
| 1047 | +/// Whether the expression's chain ends in a switch. |
| 1048 | +fn ends_in_switch(e: &Expr) -> bool { |
| 1049 | + let mut e = e; |
| 1050 | + loop { |
| 1051 | + match e { |
| 1052 | + Expr::Let(_, _, rest, _) => e = rest, |
| 1053 | + Expr::Switch { .. } => return true, |
| 1054 | + _ => return false, |
| 1055 | + } |
| 1056 | + } |
| 1057 | +} |
| 1058 | + |
| 1059 | +/// Whether a block-switch is free of effects and panics, so its `let`s |
| 1060 | +/// may move past what follows the block (case-of-case). Conservative: |
| 1061 | +/// only pure values and primitives, and externs that can neither perform |
| 1062 | +/// nor panic. (The fusion branch shares a finer version; unified at the |
| 1063 | +/// merge.) |
| 1064 | +fn block_pure(e: &Expr) -> bool { |
| 1065 | + let mut ok = true; |
| 1066 | + visit_exprs(e, &mut |e| { |
| 1067 | + if !ok { |
| 1068 | + return; |
| 1069 | + } |
| 1070 | + match e { |
| 1071 | + Expr::Panic(_) => ok = false, |
| 1072 | + Expr::Let(_, value, _, _) => match value.as_ref() { |
| 1073 | + Value::Atom(_) |
| 1074 | + | Value::Field(..) |
| 1075 | + | Value::Prim(..) |
| 1076 | + | Value::Tuple(_) |
| 1077 | + | Value::Construct { .. } |
| 1078 | + | Value::Closure(..) |
| 1079 | + | Value::Block(_) => {} |
| 1080 | + Value::CallExtern(symbol, _) => { |
| 1081 | + if crate::externs::runtime_extern(symbol) |
| 1082 | + .is_none_or(|x| x.may_unwind) |
| 1083 | + { |
| 1084 | + ok = false; |
| 1085 | + } |
| 1086 | + } |
| 1087 | + _ => ok = false, |
| 1088 | + }, |
| 1089 | + _ => {} |
| 1090 | + } |
| 1091 | + }); |
| 1092 | + ok |
| 1093 | +} |
| 1094 | + |
| 828 | 1095 | /// Whether the body calls function `id`, or closes over it, anywhere. |
| 829 | 1096 | fn recursive(e: &Expr, id: FnId) -> bool { |
| 830 | 1097 | let mut found = false; |
| @@ -903,7 +1170,7 @@ pub(crate) fn visit_values(e: &Expr, f: &mut impl FnMut(&Value)) { |
| 903 | 1170 | } |
| 904 | 1171 | |
| 905 | 1172 | /// Every atom in a use position, anywhere in `e`. |
| 906 | | −fn visit(e: &Expr, f: &mut impl FnMut(&Atom)) { |
| 1173 | +pub(crate) fn visit(e: &Expr, f: &mut impl FnMut(&Atom)) { |
| 907 | 1174 | visit_exprs(e, &mut |e| match e { |
| 908 | 1175 | Expr::Let(_, value, _, _) => visit_value(value, f), |
| 909 | 1176 | Expr::Return(a) | Expr::Exit(a) => f(a), |