| @@ -29,6 +29,11 @@ const SMALL_NODES: u32 = 32; |
| 29 | 29 | /// A bigger non-recursive function is inlinable only where its result is |
| 30 | 30 | /// the caller's (a tail site): nothing after the call is duplicated then. |
| 31 | 31 | const TAIL_NODES: u32 = 64; |
| 32 | +/// A function called exactly once is inlined as a move (its body ends in |
| 33 | +/// a switch: wrapped in a block at a non-tail site) only up to this many |
| 34 | +/// nodes — a bigger one is left to the size rules above. (The step |
| 35 | +/// functions fusion's rules build measure 15–30, issue #198.) |
| 36 | +const MOVE_NODES: u32 = 512; |
| 32 | 37 | /// Rounds of rewriting: the fixed point of the rewrites, capped (one |
| 33 | 38 | /// round can expose another — a known constructor behind an inlined call, |
| 34 | 39 | /// say). |
| @@ -53,6 +58,11 @@ pub struct Budget { |
| 53 | 58 | /// used once, which may exceed the cap): a second such inlining would |
| 54 | 59 | /// be a copy, so it takes the cap like any other. |
| 55 | 60 | moved: HashSet<FnId>, |
| 61 | + /// Where each function inlined as a move at its single direct call |
| 62 | + /// site went (per target, the callers it was moved into). A move into |
| 63 | + /// a caller that is now dead (never called, not an entry) left no |
| 64 | + /// live copy: moving the body again is still a move. |
| 65 | + moved_into: HashMap<FnId, Vec<FnId>>, |
| 56 | 66 | } |
| 57 | 67 | |
| 58 | 68 | /// Simplify the functions `live` of `program`, to the fixed point, with a |
| @@ -68,8 +78,10 @@ pub fn run_with_budget(program: &mut Program, live: &[FnId], budget: &mut Budget |
| 68 | 78 | // round. The passes between runs add functions: they start at 0. |
| 69 | 79 | budget.grown.resize(program.fns.len(), 0); |
| 70 | 80 | budget.caps.resize(program.fns.len(), 0); |
| 81 | + let entries: HashSet<FnId> = program.root_caps.keys().copied().collect(); |
| 71 | 82 | for _ in 0..MAX_ROUNDS { |
| 72 | 83 | let candidates = candidates(program); |
| 84 | + let calls = call_counts(program); |
| 73 | 85 | let mut changed = false; |
| 74 | 86 | for &id in live { |
| 75 | 87 | if budget.caps[id as usize] == 0 { |
| @@ -80,9 +92,12 @@ pub fn run_with_budget(program: &mut Program, live: &[FnId], budget: &mut Budget |
| 80 | 92 | program, |
| 81 | 93 | id, |
| 82 | 94 | &candidates, |
| 95 | + &calls, |
| 96 | + &entries, |
| 83 | 97 | &mut budget.grown[id as usize], |
| 84 | 98 | budget.caps[id as usize], |
| 85 | 99 | &mut budget.moved, |
| 100 | + &mut budget.moved_into, |
| 86 | 101 | ); |
| 87 | 102 | } |
| 88 | 103 | if !changed { |
| @@ -92,18 +107,25 @@ pub fn run_with_budget(program: &mut Program, live: &[FnId], budget: &mut Budget |
| 92 | 107 | } |
| 93 | 108 | |
| 94 | 109 | /// Simplify one function; whether anything was rewritten. |
| 110 | +#[allow(clippy::too_many_arguments)] |
| 95 | 111 | fn function( |
| 96 | 112 | program: &mut Program, |
| 97 | 113 | id: FnId, |
| 98 | 114 | candidates: &HashMap<FnId, Candidate>, |
| 115 | + calls: &HashMap<FnId, u32>, |
| 116 | + entries: &HashSet<FnId>, |
| 99 | 117 | grown: &mut u32, |
| 100 | 118 | cap: u32, |
| 101 | 119 | moved: &mut HashSet<FnId>, |
| 120 | + moved_into: &mut HashMap<FnId, Vec<FnId>>, |
| 102 | 121 | ) -> bool { |
| 103 | 122 | let decl = &mut program.fns[id as usize]; |
| 104 | 123 | let body = std::mem::replace(&mut decl.body, Expr::Return(Atom::Unit)); |
| 105 | 124 | let mut s = Simplify { |
| 106 | 125 | candidates, |
| 126 | + calls, |
| 127 | + entries, |
| 128 | + id, |
| 107 | 129 | module: decl.module.as_deref().map(Rc::from), |
| 108 | 130 | subst: HashMap::new(), |
| 109 | 131 | known: HashMap::new(), |
| @@ -115,6 +137,7 @@ fn function( |
| 115 | 137 | grown, |
| 116 | 138 | cap, |
| 117 | 139 | moved, |
| 140 | + moved_into, |
| 118 | 141 | changed: false, |
| 119 | 142 | }; |
| 120 | 143 | let uses = uses(&body); |
| @@ -149,7 +172,7 @@ enum Known { |
| 149 | 172 | } |
| 150 | 173 | |
| 151 | 174 | /// How a function body's value reaches its caller. |
| 152 | | −#[derive(Clone, Copy, PartialEq, Eq)] |
| 175 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 153 | 176 | enum End { |
| 154 | 177 | /// A chain of `let`s ending in a return. |
| 155 | 178 | Return, |
| @@ -209,8 +232,42 @@ fn candidates(program: &Program) -> HashMap<FnId, Candidate> { |
| 209 | 232 | .collect() |
| 210 | 233 | } |
| 211 | 234 | |
| 235 | +/// Direct call sites of each function, over the whole program. A closure |
| 236 | +/// of a function may be called anywhere: it counts as more than one site. |
| 237 | +fn call_counts(program: &Program) -> HashMap<FnId, u32> { |
| 238 | + let mut counts: HashMap<FnId, u32> = HashMap::new(); |
| 239 | + for f in &program.fns { |
| 240 | + visit_exprs(&f.body, &mut |e| { |
| 241 | + let value = match e { |
| 242 | + Expr::Let(_, value, _, _) | Expr::LetN(_, value, _, _) => value, |
| 243 | + _ => return, |
| 244 | + }; |
| 245 | + match &**value { |
| 246 | + Value::CallFn(g, _) => { |
| 247 | + let n = counts.entry(*g).or_insert(0); |
| 248 | + *n = n.saturating_add(1); |
| 249 | + } |
| 250 | + Value::Closure(g, _) => { |
| 251 | + counts.insert(*g, u32::MAX); |
| 252 | + } |
| 253 | + _ => {} |
| 254 | + } |
| 255 | + }); |
| 256 | + } |
| 257 | + counts |
| 258 | +} |
| 259 | + |
| 212 | 260 | struct Simplify<'a> { |
| 213 | 261 | candidates: &'a HashMap<FnId, Candidate>, |
| 262 | + /// Direct call sites of each function, program-wide (a closure |
| 263 | + /// creation counts as many: the function value may be called |
| 264 | + /// anywhere). A function with exactly one is a move candidate: its |
| 265 | + /// body replaces its one call. |
| 266 | + calls: &'a HashMap<FnId, u32>, |
| 267 | + /// The entries (`main`, tests): alive however they are called. |
| 268 | + entries: &'a HashSet<FnId>, |
| 269 | + /// The function being simplified. |
| 270 | + id: FnId, |
| 214 | 271 | /// The function's own module: only same-module callees are inlined |
| 215 | 272 | /// (Candidate::module). |
| 216 | 273 | module: Option<Rc<str>>, |
| @@ -238,10 +295,26 @@ struct Simplify<'a> { |
| 238 | 295 | cap: u32, |
| 239 | 296 | /// Functions already inlined as a move ([`Budget::moved`]). |
| 240 | 297 | moved: &'a mut HashSet<FnId>, |
| 298 | + /// The callers of each single-site move ([`Budget::moved_into`]). |
| 299 | + moved_into: &'a mut HashMap<FnId, Vec<FnId>>, |
| 241 | 300 | changed: bool, |
| 242 | 301 | } |
| 243 | 302 | |
| 244 | 303 | impl Simplify<'_> { |
| 304 | + /// Whether `f` has no live caller: never called directly (a closure |
| 305 | + /// of it counts as many calls) and not an entry. |
| 306 | + fn dead(&self, f: FnId) -> bool { |
| 307 | + self.calls.get(&f).copied().unwrap_or(0) == 0 && !self.entries.contains(&f) |
| 308 | + } |
| 309 | + |
| 310 | + /// Whether every body `g` was moved into is dead, so moving it again |
| 311 | + /// moves the only live copy. |
| 312 | + fn moved_into_dead(&self, g: FnId) -> bool { |
| 313 | + self.moved_into |
| 314 | + .get(&g) |
| 315 | + .is_none_or(|targets| targets.iter().all(|&h| self.dead(h))) |
| 316 | + } |
| 317 | + |
| 245 | 318 | fn atom(&self, a: &Atom) -> Atom { |
| 246 | 319 | match a { |
| 247 | 320 | Atom::Var(v) => self.subst.get(v).cloned().unwrap_or_else(|| a.clone()), |
| @@ -290,7 +363,9 @@ impl Simplify<'_> { |
| 290 | 363 | // it — the first time. The function may be referenced |
| 291 | 364 | // elsewhere too (an inlined caller copied the closure), |
| 292 | 365 | // so a second time is a copy, under the cap (issue #225). |
| 293 | | − force = uses.get(f) == Some(&1) && !self.moved.contains(&g); |
| 366 | + force = uses.get(f) == Some(&1) |
| 367 | + && !self.moved.contains(&g) |
| 368 | + && self.moved_into_dead(g); |
| 294 | 369 | let mut all = caps; |
| 295 | 370 | all.extend(args.iter().cloned()); |
| 296 | 371 | value = Value::CallFn(g, all); |
| @@ -315,10 +390,23 @@ impl Simplify<'_> { |
| 315 | 390 | let tail = tail_site |
| 316 | 391 | && (exits_ok || !cand.has_exit) |
| 317 | 392 | && (force || cand.nodes <= TAIL_NODES && within); |
| 393 | + // Called exactly once, directly: inlining moves the body |
| 394 | + // instead of copying it, as for a closure used once. A |
| 395 | + // caller the body was moved into before may be dead by |
| 396 | + // now (its own call was itself inlined away): then the |
| 397 | + // move is still a move. A body ending in a switch is |
| 398 | + // wrapped in a block at a non-tail site (capped: a huge |
| 399 | + // one is a job for the size rules). |
| 400 | + let once = !force && self.calls.get(g) == Some(&1) && self.moved_into_dead(*g); |
| 401 | + let move_ = once |
| 402 | + && (tail_site && (exits_ok || !cand.has_exit) |
| 403 | + || !cand.has_exit && cand.nodes <= MOVE_NODES); |
| 318 | 404 | let ok = if force { |
| 319 | 405 | // Used exactly once, inlining moves code instead of |
| 320 | 406 | // copying it: only the shape matters. |
| 321 | 407 | chain || tail |
| 408 | + } else if move_ { |
| 409 | + true |
| 322 | 410 | } else { |
| 323 | 411 | (chain && cand.nodes <= SMALL_NODES && within) || tail |
| 324 | 412 | }; |
| @@ -326,6 +414,9 @@ impl Simplify<'_> { |
| 326 | 414 | if force { |
| 327 | 415 | self.moved.insert(*g); |
| 328 | 416 | } |
| 417 | + if once { |
| 418 | + self.moved_into.entry(*g).or_default().push(self.id); |
| 419 | + } |
| 329 | 420 | *self.grown += cand.nodes; |
| 330 | 421 | self.inlined.insert(*g); |
| 331 | 422 | let (mut pasted, pend) = self.inline(&cand, args); |
| @@ -337,6 +428,14 @@ impl Simplify<'_> { |
| 337 | 428 | lets.push_front(item); |
| 338 | 429 | } |
| 339 | 430 | } |
| 431 | + // A body ending in a switch at a non-tail site: |
| 432 | + // the switch is the value of a block. |
| 433 | + pend @ (Expr::Switch { .. } | Expr::SwitchLit { .. }) if !tail_site => { |
| 434 | + lets.push_front((v, Value::Block(Box::new(pend)), span)); |
| 435 | + for item in pasted.into_iter().rev() { |
| 436 | + lets.push_front(item); |
| 437 | + } |
| 438 | + } |
| 340 | 439 | // A panic makes the rest dead; at a tail site the |
| 341 | 440 | // rest was `return v`, which the body replaces. |
| 342 | 441 | pend => { |