| @@ -76,6 +76,9 @@ pub(crate) fn emit( |
| 76 | 76 | current: 0, |
| 77 | 77 | ranges, |
| 78 | 78 | workers, |
| 79 | + cmp_switches: HashMap::new(), |
| 80 | + cmp_skip: BTreeSet::new(), |
| 81 | + cmp_defer: BTreeSet::new(), |
| 79 | 82 | raw: BTreeSet::new(), |
| 80 | 83 | worker: None, |
| 81 | 84 | functions: BTreeMap::new(), |
| @@ -353,6 +356,17 @@ struct Emitter<'p> { |
| 353 | 356 | /// worker's body is emitted, its raw locals (empty otherwise) and |
| 354 | 357 | /// its kind. |
| 355 | 358 | workers: BTreeMap<FnId, crate::unbox::WorkerPlan>, |
| 359 | + /// The current function's comparison switches fused to direct |
| 360 | + /// branches, by scrutinee variable ([`CmpSwitch`]). |
| 361 | + cmp_switches: HashMap<VarId, CmpSwitch>, |
| 362 | + /// The current function's `let`s a fused comparison switch absorbs |
| 363 | + /// (the comparison's result and a `TagIs`/`Not` chain over it): |
| 364 | + /// never materialized, and their `drop`s skipped — the results are |
| 365 | + /// small integers, whose drops are no-ops. |
| 366 | + cmp_skip: BTreeSet<VarId>, |
| 367 | + /// The current function's operand `drop`s deferred to a fused |
| 368 | + /// comparison's slow path (by `Drop` node). |
| 369 | + cmp_defer: BTreeSet<*const Expr>, |
| 356 | 370 | raw: BTreeSet<VarId>, |
| 357 | 371 | worker: Option<UnboxedKind>, |
| 358 | 372 | /// Block labels, numbered within each function. |
| @@ -363,6 +377,257 @@ struct Emitter<'p> { |
| 363 | 377 | written: Option<Line>, |
| 364 | 378 | } |
| 365 | 379 | |
| 380 | +/// A switch on an integer comparison's result, emitted as a direct |
| 381 | +/// compare-and-branch (ADR 0046, issue #191): the scrutinee is |
| 382 | +/// `tl_int_compare`'s `Order` or `tl_int_eq`'s Bool, or a `TagIs`/`Not` |
| 383 | +/// chain over the former, used nowhere else. |
| 384 | +#[derive(Clone)] |
| 385 | +struct CmpSwitch { |
| 386 | + /// The comparison extern's result variable: materialized only on |
| 387 | + /// the slow path (a big-integer operand). |
| 388 | + result: VarId, |
| 389 | + /// The compared operands. |
| 390 | + a: Atom, |
| 391 | + b: Atom, |
| 392 | + /// Operands whose `drop` sits between the comparison and the switch |
| 393 | + /// (the comparison was their last use): the drop moves to the slow |
| 394 | + /// path, after the call — on the fast path the guard proves them |
| 395 | + /// small integers, whose drops are no-ops. |
| 396 | + deferred: Vec<VarId>, |
| 397 | + kind: CmpKind, |
| 398 | +} |
| 399 | + |
| 400 | +#[derive(Clone)] |
| 401 | +enum CmpKind { |
| 402 | + /// The switch is on the `Order` itself (tags 0/1/2: Lt/Eq/Gt). |
| 403 | + Order, |
| 404 | + /// The switch is on a Bool: true where the `Order`'s tag is in the |
| 405 | + /// set (a bit per tag; a `TagIs(t)` is `{t}`, a `Not` complements). |
| 406 | + Bool(u32), |
| 407 | + /// The switch is on `tl_int_eq`'s Bool. |
| 408 | + Eq, |
| 409 | +} |
| 410 | + |
| 411 | +/// A variable dropped or consumed on the path (`cmp_walk`). |
| 412 | +#[derive(Clone, Copy)] |
| 413 | +struct DeadDrop { |
| 414 | + /// The `Drop` node (none: consumed — a call argument or a release — |
| 415 | + /// which cannot move to the slow path). |
| 416 | + node: Option<*const Expr>, |
| 417 | + /// No branch sits between the drop and here. |
| 418 | + spine: bool, |
| 419 | +} |
| 420 | + |
| 421 | +impl DeadDrop { |
| 422 | + const CONSUMED: DeadDrop = DeadDrop { |
| 423 | + node: None, |
| 424 | + spine: false, |
| 425 | + }; |
| 426 | + |
| 427 | + fn off_spine(self) -> DeadDrop { |
| 428 | + DeadDrop { |
| 429 | + spine: false, |
| 430 | + ..self |
| 431 | + } |
| 432 | + } |
| 433 | +} |
| 434 | + |
| 435 | +/// What a function's comparison walk found. |
| 436 | +#[derive(Default)] |
| 437 | +struct CmpFusions { |
| 438 | + /// The switches to fuse, by scrutinee variable. |
| 439 | + switches: HashMap<VarId, CmpSwitch>, |
| 440 | + /// The `let`s fused switches absorb. |
| 441 | + skip: BTreeSet<VarId>, |
| 442 | + /// The `Drop` nodes deferred to a slow path (by address). |
| 443 | + defer: BTreeSet<*const Expr>, |
| 444 | +} |
| 445 | + |
| 446 | +/// What a function's comparison bindings are: the tables a switch's |
| 447 | +/// scrutinee is resolved through, and every variable's non-`drop` uses. |
| 448 | +#[derive(Default)] |
| 449 | +struct CmpDefs { |
| 450 | + /// `let c = tl_int_compare(a, b)`. |
| 451 | + cmps: HashMap<VarId, (Atom, Atom)>, |
| 452 | + /// `let e = tl_int_eq(a, b)`. |
| 453 | + eqs: HashMap<VarId, (Atom, Atom)>, |
| 454 | + /// `let b = TagIs(t)(c)`. |
| 455 | + tagis: HashMap<VarId, (u32, VarId)>, |
| 456 | + /// `let n = Not(b)`. |
| 457 | + nots: HashMap<VarId, VarId>, |
| 458 | + /// Uses of each variable but a `drop`'s. |
| 459 | + uses: HashMap<VarId, u32>, |
| 460 | +} |
| 461 | + |
| 462 | +impl CmpDefs { |
| 463 | + fn count(&mut self, a: &Atom) { |
| 464 | + if let Atom::Var(v) = a { |
| 465 | + *self.uses.entry(*v).or_insert(0) += 1; |
| 466 | + } |
| 467 | + } |
| 468 | + |
| 469 | + fn count_value(&mut self, value: &Value) { |
| 470 | + match value { |
| 471 | + Value::Atom(a) => self.count(a), |
| 472 | + Value::Call(f, args) => { |
| 473 | + self.count(f); |
| 474 | + for a in args { |
| 475 | + self.count(a); |
| 476 | + } |
| 477 | + } |
| 478 | + Value::CallFn(_, args) |
| 479 | + | Value::CallExtern(_, args) |
| 480 | + | Value::Prim(_, args) |
| 481 | + | Value::Tuple(args) |
| 482 | + | Value::Construct { args, .. } |
| 483 | + | Value::Closure(_, args) => { |
| 484 | + for a in args { |
| 485 | + self.count(a); |
| 486 | + } |
| 487 | + } |
| 488 | + Value::Field(a, _) => self.count(a), |
| 489 | + Value::Perform { cap, args, .. } => { |
| 490 | + self.count(cap); |
| 491 | + for a in args { |
| 492 | + self.count(a); |
| 493 | + } |
| 494 | + } |
| 495 | + Value::Handle { |
| 496 | + body, ret, clauses, .. |
| 497 | + } => { |
| 498 | + self.count(body); |
| 499 | + if let Some(r) = ret { |
| 500 | + self.count(r); |
| 501 | + } |
| 502 | + for c in clauses { |
| 503 | + self.count(c); |
| 504 | + } |
| 505 | + } |
| 506 | + Value::Region { body, .. } => self.count(body), |
| 507 | + Value::Defer { body, cleanup } => { |
| 508 | + self.count(body); |
| 509 | + self.count(cleanup); |
| 510 | + } |
| 511 | + Value::Block(_) => {} // walked with the expressions |
| 512 | + Value::Reuse { token, value, .. } => { |
| 513 | + self.count(&Atom::Var(*token)); |
| 514 | + self.count_value(value); |
| 515 | + } |
| 516 | + Value::CtxExtend { ctx, cell, .. } => { |
| 517 | + self.count(ctx); |
| 518 | + self.count(cell); |
| 519 | + } |
| 520 | + Value::CtxApply { ctx, value } => { |
| 521 | + self.count(ctx); |
| 522 | + self.count(value); |
| 523 | + } |
| 524 | + } |
| 525 | + } |
| 526 | +} |
| 527 | + |
| 528 | +/// Collect a function's comparison bindings and non-`drop` uses. |
| 529 | +fn cmp_defs(e: &Expr, defs: &mut CmpDefs) { |
| 530 | + match e { |
| 531 | + Expr::Let(v, value, rest, _) => { |
| 532 | + match &**value { |
| 533 | + Value::CallExtern(sym, args) if args.len() == 2 => match sym.as_str() { |
| 534 | + "tl_int_compare" => { |
| 535 | + defs.cmps.insert(*v, (args[0].clone(), args[1].clone())); |
| 536 | + } |
| 537 | + "tl_int_eq" => { |
| 538 | + defs.eqs.insert(*v, (args[0].clone(), args[1].clone())); |
| 539 | + } |
| 540 | + _ => {} |
| 541 | + }, |
| 542 | + Value::Prim(Prim::TagIs(t), args) => { |
| 543 | + if let Some(Atom::Var(c)) = args.first() { |
| 544 | + defs.tagis.insert(*v, (*t, *c)); |
| 545 | + } |
| 546 | + } |
| 547 | + Value::Prim(Prim::Not, args) => { |
| 548 | + if let Some(Atom::Var(c)) = args.first() { |
| 549 | + defs.nots.insert(*v, *c); |
| 550 | + } |
| 551 | + } |
| 552 | + _ => {} |
| 553 | + } |
| 554 | + defs.count_value(value); |
| 555 | + if let Value::Block(b) = &**value { |
| 556 | + cmp_defs(b, defs); |
| 557 | + } |
| 558 | + cmp_defs(rest, defs); |
| 559 | + } |
| 560 | + Expr::LetN(_, value, rest, _) => { |
| 561 | + defs.count_value(value); |
| 562 | + cmp_defs(rest, defs); |
| 563 | + } |
| 564 | + Expr::Dup(v, rest) => { |
| 565 | + defs.count(&Atom::Var(*v)); |
| 566 | + cmp_defs(rest, defs); |
| 567 | + } |
| 568 | + Expr::Drop(_, rest) => cmp_defs(rest, defs), |
| 569 | + Expr::Release { |
| 570 | + var, |
| 571 | + fields, |
| 572 | + token, |
| 573 | + rest, |
| 574 | + .. |
| 575 | + } => { |
| 576 | + defs.count(&Atom::Var(*var)); |
| 577 | + for (_, a) in fields { |
| 578 | + defs.count(&Atom::Var(*a)); |
| 579 | + } |
| 580 | + if let Some(t) = token { |
| 581 | + defs.count(&Atom::Var(*t)); |
| 582 | + } |
| 583 | + cmp_defs(rest, defs); |
| 584 | + } |
| 585 | + Expr::Switch { on, cases, default } => { |
| 586 | + defs.count(on); |
| 587 | + for (_, b) in cases { |
| 588 | + cmp_defs(b, defs); |
| 589 | + } |
| 590 | + if let Some(d) = default { |
| 591 | + cmp_defs(d, defs); |
| 592 | + } |
| 593 | + } |
| 594 | + Expr::SwitchLit { on, cases, default } => { |
| 595 | + defs.count(on); |
| 596 | + for (_, b) in cases { |
| 597 | + cmp_defs(b, defs); |
| 598 | + } |
| 599 | + cmp_defs(default, defs); |
| 600 | + } |
| 601 | + Expr::Return(a) | Expr::Exit(a) => defs.count(a), |
| 602 | + Expr::ReturnN(atoms) => { |
| 603 | + for a in atoms { |
| 604 | + defs.count(a); |
| 605 | + } |
| 606 | + } |
| 607 | + Expr::Panic(_) => {} |
| 608 | + } |
| 609 | +} |
| 610 | + |
| 611 | +/// The `Expr` pointer a target is, for grouping the arms a tag leads to. |
| 612 | +fn expr_ptr(e: Option<&Expr>) -> Option<*const Expr> { |
| 613 | + e.map(|e| e as *const Expr) |
| 614 | +} |
| 615 | + |
| 616 | +/// The C condition for the `Order` tags in `mask` over the tagged small |
| 617 | +/// integers `a` and `b` (tagging preserves their order). |
| 618 | +fn order_cond(mask: u32, a: &str, b: &str) -> String { |
| 619 | + let op = match mask & 0b111 { |
| 620 | + 0b001 => "<", |
| 621 | + 0b010 => "==", |
| 622 | + 0b100 => ">", |
| 623 | + 0b011 => "<=", |
| 624 | + 0b110 => ">=", |
| 625 | + 0b101 => "!=", |
| 626 | + _ => unreachable!("no proper subset of Lt/Eq/Gt is two tests"), |
| 627 | + }; |
| 628 | + format!("((int64_t){a}) {op} ((int64_t){b})") |
| 629 | +} |
| 630 | + |
| 366 | 631 | /// C arguments for a call with these value slots: registers, padded. |
| 367 | 632 | fn register_args(slots: &[String]) -> String { |
| 368 | 633 | (0..REGS) |
| @@ -522,6 +787,10 @@ impl Emitter<'_> { |
| 522 | 787 | decl.name |
| 523 | 788 | ))); |
| 524 | 789 | } |
| 790 | + let (cmp_switches, cmp_skip, cmp_defer) = self.cmp_fusions(id, decl); |
| 791 | + self.cmp_switches = cmp_switches; |
| 792 | + self.cmp_skip = cmp_skip; |
| 793 | + self.cmp_defer = cmp_defer; |
| 525 | 794 | let mut out = String::new(); |
| 526 | 795 | self.uses = Uses::default(); |
| 527 | 796 | self.labels = 0; |
| @@ -973,13 +1242,27 @@ int main(int argc, char **argv) {{ |
| 973 | 1242 | } |
| 974 | 1243 | Expr::Dup(v, rest) => { |
| 975 | 1244 | // A double is not a reference: nothing to count. |
| 976 | | − if !self.raw.contains(v) { |
| 1245 | + // Neither is a proven-small integer (issue #191). |
| 1246 | + if !self.raw.contains(v) && !self.ranges.small(f.id, &Atom::Var(*v)) { |
| 977 | 1247 | let _ = writeln!(out, "{ind}tl_dup(v{v});"); |
| 978 | 1248 | held.push(*v); |
| 979 | 1249 | } |
| 980 | 1250 | e = rest; |
| 981 | 1251 | } |
| 982 | 1252 | Expr::Drop(v, rest) => { |
| 1253 | + // Deferred to a fused comparison's slow path (the |
| 1254 | + // comparison was the operand's last use). |
| 1255 | + if self.cmp_defer.contains(&(e as *const Expr)) { |
| 1256 | + e = rest; |
| 1257 | + continue; |
| 1258 | + } |
| 1259 | + // A fused comparison's result: never materialized, |
| 1260 | + // and a small integer's drop is a no-op anyway. |
| 1261 | + if self.cmp_skip.contains(v) || self.ranges.small(f.id, &Atom::Var(*v)) { |
| 1262 | + take(&mut held, *v); |
| 1263 | + e = rest; |
| 1264 | + continue; |
| 1265 | + } |
| 983 | 1266 | if !self.raw.contains(v) { |
| 984 | 1267 | let _ = writeln!(out, "{ind}tl_drop(ctx, v{v});"); |
| 985 | 1268 | take(&mut held, *v); |
| @@ -1009,7 +1292,24 @@ int main(int argc, char **argv) {{ |
| 1009 | 1292 | return Ok(None); |
| 1010 | 1293 | } |
| 1011 | 1294 | Expr::Switch { on, cases, default } => { |
| 1012 | | − return self.switch(out, f, on, cases, default.as_deref(), dest, held, depth); |
| 1295 | + // A switch on a comparison's result: a direct |
| 1296 | + // compare-and-branch (issue #191). |
| 1297 | + if let Atom::Var(s) = on |
| 1298 | + && let Some(plan) = self.cmp_switches.get(s).cloned() |
| 1299 | + { |
| 1300 | + return self.cmp_switch( |
| 1301 | + out, |
| 1302 | + f, |
| 1303 | + &plan, |
| 1304 | + cases, |
| 1305 | + default.as_deref(), |
| 1306 | + dest, |
| 1307 | + held, |
| 1308 | + depth, |
| 1309 | + ); |
| 1310 | + } |
| 1311 | + let cases: Vec<(u32, &Expr)> = cases.iter().map(|(t, b)| (*t, b)).collect(); |
| 1312 | + return self.switch(out, f, on, &cases, default.as_deref(), dest, held, depth); |
| 1013 | 1313 | } |
| 1014 | 1314 | Expr::SwitchLit { on, cases, default } => { |
| 1015 | 1315 | if cases.is_empty() { |
| @@ -1042,6 +1342,13 @@ int main(int argc, char **argv) {{ |
| 1042 | 1342 | depth: usize, |
| 1043 | 1343 | ) -> Result<Option<(&'e Expr, Dest)>, Unsupported> { |
| 1044 | 1344 | let ind = " ".repeat(depth); |
| 1345 | + // A comparison a switch fuses: the `let` is never materialized |
| 1346 | + // (its result, a small integer, needs no drop either; those are |
| 1347 | + // skipped with it). Its operands are borrowed, so the frame's |
| 1348 | + // holdings are unchanged. |
| 1349 | + if self.cmp_skip.contains(&v) { |
| 1350 | + return Ok(Some((rest, dest))); |
| 1351 | + } |
| 1045 | 1352 | // A value that is `exit`ed is the function's, from |
| 1046 | 1353 | // any block (ADR 0037): in tail position too. |
| 1047 | 1354 | let tail = (matches!(dest, Dest::Return) |
| @@ -1249,6 +1556,457 @@ int main(int argc, char **argv) {{ |
| 1249 | 1556 | Ok(Some(rest)) |
| 1250 | 1557 | } |
| 1251 | 1558 | |
| 1559 | + /// The function's comparison switches to fuse (by scrutinee |
| 1560 | + /// variable), the `let`s they absorb, and the operand `drop`s they |
| 1561 | + /// defer to the slow path (by the `Drop` node). |
| 1562 | + fn cmp_fusions( |
| 1563 | + &self, |
| 1564 | + f: FnId, |
| 1565 | + decl: &FnDecl, |
| 1566 | + ) -> ( |
| 1567 | + HashMap<VarId, CmpSwitch>, |
| 1568 | + BTreeSet<VarId>, |
| 1569 | + BTreeSet<*const Expr>, |
| 1570 | + ) { |
| 1571 | + let mut defs = CmpDefs::default(); |
| 1572 | + cmp_defs(&decl.body, &mut defs); |
| 1573 | + let mut out = CmpFusions::default(); |
| 1574 | + let mut dead = HashMap::new(); |
| 1575 | + self.cmp_walk(f, &decl.body, &defs, &mut dead, &mut out); |
| 1576 | + (out.switches, out.skip, out.defer) |
| 1577 | + } |
| 1578 | + |
| 1579 | + /// Walk `e`, tracking in `dead` the variables dropped or consumed on |
| 1580 | + /// the path so far. A comparison's operand may be dead where its |
| 1581 | + /// switch is: its `drop` then moves to the slow path (a no-op on the |
| 1582 | + /// fast path, whose guard proves it small) — but only when no branch |
| 1583 | + /// sits between the drop and the switch (the drop's other paths |
| 1584 | + /// still need it), and only when it was a drop, not a consume. |
| 1585 | + fn cmp_walk( |
| 1586 | + &self, |
| 1587 | + f: FnId, |
| 1588 | + e: &Expr, |
| 1589 | + defs: &CmpDefs, |
| 1590 | + dead: &mut HashMap<VarId, DeadDrop>, |
| 1591 | + out: &mut CmpFusions, |
| 1592 | + ) { |
| 1593 | + let mut e = e; |
| 1594 | + loop { |
| 1595 | + match e { |
| 1596 | + Expr::Let(_, value, rest, _) | Expr::LetN(_, value, rest, _) => { |
| 1597 | + if let Value::Block(inner) = &**value { |
| 1598 | + // A block is eager: what it consumes stays |
| 1599 | + // consumed past it. |
| 1600 | + self.cmp_walk(f, inner, defs, dead, out); |
| 1601 | + } else { |
| 1602 | + let (owned, _) = louise_perceus::uses(value, self.program); |
| 1603 | + for v in owned { |
| 1604 | + dead.insert(v, DeadDrop::CONSUMED); |
| 1605 | + } |
| 1606 | + } |
| 1607 | + e = rest; |
| 1608 | + } |
| 1609 | + Expr::Dup(_, rest) => e = rest, |
| 1610 | + Expr::Drop(v, rest) => { |
| 1611 | + dead.insert( |
| 1612 | + *v, |
| 1613 | + DeadDrop { |
| 1614 | + node: Some(e as *const Expr), |
| 1615 | + spine: true, |
| 1616 | + }, |
| 1617 | + ); |
| 1618 | + e = rest; |
| 1619 | + } |
| 1620 | + Expr::Release { var, rest, .. } => { |
| 1621 | + dead.insert(*var, DeadDrop::CONSUMED); |
| 1622 | + e = rest; |
| 1623 | + } |
| 1624 | + Expr::Switch { on, cases, default } => { |
| 1625 | + if let Atom::Var(s) = on { |
| 1626 | + self.cmp_try_fuse(f, *s, cases, default.as_deref(), defs, dead, out); |
| 1627 | + } |
| 1628 | + // What survives the switch is dead on every arm; a |
| 1629 | + // branch sits between the arms and the drops so far. |
| 1630 | + let mut merged: Option<HashMap<VarId, DeadDrop>> = None; |
| 1631 | + for b in cases |
| 1632 | + .iter() |
| 1633 | + .map(|(_, b)| b) |
| 1634 | + .chain(default.iter().map(|d| &**d)) |
| 1635 | + { |
| 1636 | + let mut d: HashMap<VarId, DeadDrop> = |
| 1637 | + dead.iter().map(|(v, dd)| (*v, dd.off_spine())).collect(); |
| 1638 | + self.cmp_walk(f, b, defs, &mut d, out); |
| 1639 | + merged = Some(match merged { |
| 1640 | + None => d, |
| 1641 | + Some(m) => m.into_iter().filter(|(v, _)| d.contains_key(v)).collect(), |
| 1642 | + }); |
| 1643 | + } |
| 1644 | + if let Some(m) = merged { |
| 1645 | + *dead = m; |
| 1646 | + } |
| 1647 | + return; |
| 1648 | + } |
| 1649 | + Expr::SwitchLit { cases, default, .. } => { |
| 1650 | + let mut merged: Option<HashMap<VarId, DeadDrop>> = None; |
| 1651 | + for b in cases.iter().map(|(_, b)| b).chain([&**default]) { |
| 1652 | + let mut d: HashMap<VarId, DeadDrop> = |
| 1653 | + dead.iter().map(|(v, dd)| (*v, dd.off_spine())).collect(); |
| 1654 | + self.cmp_walk(f, b, defs, &mut d, out); |
| 1655 | + merged = Some(match merged { |
| 1656 | + None => d, |
| 1657 | + Some(m) => m.into_iter().filter(|(v, _)| d.contains_key(v)).collect(), |
| 1658 | + }); |
| 1659 | + } |
| 1660 | + if let Some(m) = merged { |
| 1661 | + *dead = m; |
| 1662 | + } |
| 1663 | + return; |
| 1664 | + } |
| 1665 | + Expr::Return(_) | Expr::Exit(_) | Expr::ReturnN(_) | Expr::Panic(_) => return, |
| 1666 | + } |
| 1667 | + } |
| 1668 | + } |
| 1669 | + |
| 1670 | + /// The switch on `s` fuses to a direct comparison when `s` resolves |
| 1671 | + /// to one and is used nowhere else (issue #191): record the plan and |
| 1672 | + /// the `let`s it absorbs. |
| 1673 | + #[allow(clippy::too_many_arguments)] |
| 1674 | + fn cmp_try_fuse( |
| 1675 | + &self, |
| 1676 | + f: FnId, |
| 1677 | + s: VarId, |
| 1678 | + cases: &[(u32, Expr)], |
| 1679 | + default: Option<&Expr>, |
| 1680 | + defs: &CmpDefs, |
| 1681 | + dead: &HashMap<VarId, DeadDrop>, |
| 1682 | + out: &mut CmpFusions, |
| 1683 | + ) { |
| 1684 | + let once = |defs: &CmpDefs, v: VarId| defs.uses.get(&v).copied().unwrap_or(0) == 1; |
| 1685 | + let mut skip = Vec::new(); |
| 1686 | + let (result, a, b, kind) = 'resolve: { |
| 1687 | + if let Some((a, b)) = defs.cmps.get(&s) { |
| 1688 | + if !once(defs, s) { |
| 1689 | + return; |
| 1690 | + } |
| 1691 | + break 'resolve (s, a.clone(), b.clone(), CmpKind::Order); |
| 1692 | + } |
| 1693 | + if let Some((a, b)) = defs.eqs.get(&s) { |
| 1694 | + if !once(defs, s) { |
| 1695 | + return; |
| 1696 | + } |
| 1697 | + break 'resolve (s, a.clone(), b.clone(), CmpKind::Eq); |
| 1698 | + } |
| 1699 | + // A Bool chain: `Not`s over a `TagIs(t)` over the compare. |
| 1700 | + let mut cur = s; |
| 1701 | + let mut flip = false; |
| 1702 | + while let Some(&inner) = defs.nots.get(&cur) { |
| 1703 | + if !once(defs, cur) { |
| 1704 | + return; |
| 1705 | + } |
| 1706 | + skip.push(cur); |
| 1707 | + flip = !flip; |
| 1708 | + cur = inner; |
| 1709 | + } |
| 1710 | + let Some(&(t, c)) = defs.tagis.get(&cur) else { |
| 1711 | + return; |
| 1712 | + }; |
| 1713 | + if !once(defs, cur) || t > 2 { |
| 1714 | + return; |
| 1715 | + } |
| 1716 | + skip.push(cur); |
| 1717 | + let Some((a, b)) = defs.cmps.get(&c) else { |
| 1718 | + return; |
| 1719 | + }; |
| 1720 | + if !once(defs, c) { |
| 1721 | + return; |
| 1722 | + } |
| 1723 | + let mask = if flip { 0b111 & !(1 << t) } else { 1 << t }; |
| 1724 | + break 'resolve (c, a.clone(), b.clone(), CmpKind::Bool(mask)); |
| 1725 | + }; |
| 1726 | + // The operands must be readable where the comparison moves to |
| 1727 | + // (the switch). A dropped one dangles — unless it is proven |
| 1728 | + // small (its bits are the value; the drop is a no-op), or its |
| 1729 | + // drop is on this spine and moves to the slow path (deferred). |
| 1730 | + let mut deferred: Vec<VarId> = Vec::new(); |
| 1731 | + for op in [&a, &b] { |
| 1732 | + if let Atom::Var(x) = op |
| 1733 | + && let Some(dd) = dead.get(x) |
| 1734 | + { |
| 1735 | + if self.ranges.small(f, op) { |
| 1736 | + continue; |
| 1737 | + } |
| 1738 | + if dd.spine && dd.node.is_some() && !deferred.contains(x) { |
| 1739 | + deferred.push(*x); |
| 1740 | + } else { |
| 1741 | + return; |
| 1742 | + } |
| 1743 | + } |
| 1744 | + } |
| 1745 | + // A switch with no arm at all is not emitted either way. |
| 1746 | + if cases.is_empty() && default.is_none() { |
| 1747 | + return; |
| 1748 | + } |
| 1749 | + for &x in &deferred { |
| 1750 | + if let Some(node) = dead.get(&x).and_then(|dd| dd.node) { |
| 1751 | + out.defer.insert(node); |
| 1752 | + } |
| 1753 | + } |
| 1754 | + out.switches.insert( |
| 1755 | + s, |
| 1756 | + CmpSwitch { |
| 1757 | + result, |
| 1758 | + a, |
| 1759 | + b, |
| 1760 | + deferred, |
| 1761 | + kind, |
| 1762 | + }, |
| 1763 | + ); |
| 1764 | + out.skip.extend(skip); |
| 1765 | + out.skip.extend([s, result]); |
| 1766 | + } |
| 1767 | + |
| 1768 | + /// A switch on a comparison's result as a direct compare-and-branch |
| 1769 | + /// (issue #191): with both operands proven small, one C comparison; |
| 1770 | + /// otherwise a fast path under `tl_likely(a & b & 1)` (tagged small |
| 1771 | + /// integers compare in order), the general code — the extern's call |
| 1772 | + /// and the switch on its result — in the else. |
| 1773 | + #[allow(clippy::too_many_arguments)] |
| 1774 | + fn cmp_switch( |
| 1775 | + &mut self, |
| 1776 | + out: &mut String, |
| 1777 | + f: &Func, |
| 1778 | + plan: &CmpSwitch, |
| 1779 | + cases: &[(u32, Expr)], |
| 1780 | + default: Option<&Expr>, |
| 1781 | + dest: Dest, |
| 1782 | + held: Vec<VarId>, |
| 1783 | + depth: usize, |
| 1784 | + ) -> Result<Option<Vec<VarId>>, Unsupported> { |
| 1785 | + let ind = " ".repeat(depth); |
| 1786 | + let a = self.atom(&plan.a)?; |
| 1787 | + let b = self.atom(&plan.b)?; |
| 1788 | + let proven = self.ranges.small(f.id, &plan.a) && self.ranges.small(f.id, &plan.b); |
| 1789 | + // Deferred operand drops: the arms never hold them (the slow |
| 1790 | + // path drops them right after its call; on the fast path they |
| 1791 | + // are small integers, whose drops are no-ops). |
| 1792 | + let mut held = held; |
| 1793 | + for &x in &plan.deferred { |
| 1794 | + take(&mut held, x); |
| 1795 | + } |
| 1796 | + // The arm each `Order` tag leads to. |
| 1797 | + let target = |t: u32| -> Option<&Expr> { |
| 1798 | + cases |
| 1799 | + .iter() |
| 1800 | + .find(|(c, _)| *c == t) |
| 1801 | + .map(|(_, b)| b) |
| 1802 | + .or(default) |
| 1803 | + }; |
| 1804 | + // The compare-and-branch chain: (condition, arm) pairs, the last |
| 1805 | + // taken unconditionally. Arms shared by several tags merge. |
| 1806 | + let chain: Vec<(String, Option<&Expr>)> = match plan.kind { |
| 1807 | + CmpKind::Order => { |
| 1808 | + let mut groups: Vec<(u32, Option<&Expr>)> = Vec::new(); |
| 1809 | + for t in [0u32, 2, 1] { |
| 1810 | + let tg = target(t); |
| 1811 | + match groups |
| 1812 | + .iter_mut() |
| 1813 | + .find(|(_, g)| expr_ptr(*g) == expr_ptr(tg)) |
| 1814 | + { |
| 1815 | + Some((m, _)) => *m |= 1 << t, |
| 1816 | + None => groups.push((1 << t, tg)), |
| 1817 | + } |
| 1818 | + } |
| 1819 | + if groups.len() == 1 { |
| 1820 | + vec![(String::new(), groups[0].1)] |
| 1821 | + } else { |
| 1822 | + groups |
| 1823 | + .into_iter() |
| 1824 | + .map(|(mask, tg)| (order_cond(mask, &a, &b), tg)) |
| 1825 | + .collect() |
| 1826 | + } |
| 1827 | + } |
| 1828 | + CmpKind::Bool(mask) => { |
| 1829 | + if expr_ptr(target(1)) == expr_ptr(target(0)) { |
| 1830 | + vec![(String::new(), target(1))] |
| 1831 | + } else { |
| 1832 | + vec![ |
| 1833 | + (order_cond(mask, &a, &b), target(1)), |
| 1834 | + (String::new(), target(0)), |
| 1835 | + ] |
| 1836 | + } |
| 1837 | + } |
| 1838 | + CmpKind::Eq => { |
| 1839 | + if expr_ptr(target(1)) == expr_ptr(target(0)) { |
| 1840 | + vec![(String::new(), target(1))] |
| 1841 | + } else { |
| 1842 | + vec![ |
| 1843 | + (format!("({a}) == ({b})"), target(1)), |
| 1844 | + (String::new(), target(0)), |
| 1845 | + ] |
| 1846 | + } |
| 1847 | + } |
| 1848 | + }; |
| 1849 | + if chain.len() == 1 { |
| 1850 | + // Every tag leads to the same arm: no comparison at all. |
| 1851 | + return self.cmp_arms(out, f, &chain, dest, held, depth); |
| 1852 | + } |
| 1853 | + if proven { |
| 1854 | + return self.cmp_arms(out, f, &chain, dest, held, depth); |
| 1855 | + } |
| 1856 | + // Unproven: the arms are emitted once, after the dispatch; the |
| 1857 | + // fast path jumps to them, the slow path computes the extern's |
| 1858 | + // result and dispatches on its tag. No arm body is duplicated |
| 1859 | + // (nested comparisons would multiply the C text). |
| 1860 | + let guard = match plan.kind { |
| 1861 | + CmpKind::Eq => format!("tl_likely((({a}) & ({b}) & 1) != 0 || ({a}) == ({b}))"), |
| 1862 | + _ => format!("tl_likely((({a}) & ({b}) & 1) != 0)"), |
| 1863 | + }; |
| 1864 | + let sym = match plan.kind { |
| 1865 | + CmpKind::Eq => "tl_int_eq", |
| 1866 | + _ => "tl_int_compare", |
| 1867 | + }; |
| 1868 | + let labels: Vec<u32> = chain.iter().map(|_| self.label()).collect(); |
| 1869 | + // The fast path: each group's condition jumps to its arm. |
| 1870 | + let fast: Vec<(String, Option<u32>)> = chain |
| 1871 | + .iter() |
| 1872 | + .zip(&labels) |
| 1873 | + .map(|((cond, tg), l)| (cond.clone(), tg.map(|_| *l))) |
| 1874 | + .collect(); |
| 1875 | + let _ = writeln!(out, "{ind}if ({guard}) {{"); |
| 1876 | + self.cmp_goto(out, &fast, depth + 1); |
| 1877 | + let _ = writeln!(out, "{ind}}} else {{"); |
| 1878 | + let _ = writeln!(out, "{ind} v{} = {sym}(ctx, {a}, {b});", plan.result); |
| 1879 | + for &x in &plan.deferred { |
| 1880 | + let _ = writeln!(out, "{ind} tl_drop(ctx, v{x});"); |
| 1881 | + } |
| 1882 | + // The slow path: the result's tag, to the same arms. For a Bool |
| 1883 | + // chain the `Order`'s tags map back to the Bool arms. |
| 1884 | + let slow: Vec<(String, Option<u32>)> = match plan.kind { |
| 1885 | + CmpKind::Order => { |
| 1886 | + // Re-group by tag: a group covering two tags gets one |
| 1887 | + // entry per tag. |
| 1888 | + let mut entries = Vec::new(); |
| 1889 | + for (i, ((_, tg), l)) in chain.iter().zip(&labels).enumerate() { |
| 1890 | + for t in 0..3u32 { |
| 1891 | + if expr_ptr(target(t)) == expr_ptr(chain[i].1) { |
| 1892 | + entries.push(( |
| 1893 | + format!("tl_tag_of(v{}) == {t}", plan.result), |
| 1894 | + tg.map(|_| *l), |
| 1895 | + )); |
| 1896 | + } |
| 1897 | + } |
| 1898 | + } |
| 1899 | + entries |
| 1900 | + } |
| 1901 | + CmpKind::Bool(mask) => (0..3u32) |
| 1902 | + .map(|t| { |
| 1903 | + let g = if mask >> t & 1 == 1 { 0 } else { 1 }; |
| 1904 | + ( |
| 1905 | + format!("tl_tag_of(v{}) == {t}", plan.result), |
| 1906 | + chain[g].1.map(|_| labels[g]), |
| 1907 | + ) |
| 1908 | + }) |
| 1909 | + .collect(), |
| 1910 | + CmpKind::Eq => (0..2u32) |
| 1911 | + .map(|t| { |
| 1912 | + let g = if t == 1 { 0 } else { 1 }; |
| 1913 | + ( |
| 1914 | + format!("tl_tag_of(v{}) == {t}", plan.result), |
| 1915 | + chain[g].1.map(|_| labels[g]), |
| 1916 | + ) |
| 1917 | + }) |
| 1918 | + .collect(), |
| 1919 | + }; |
| 1920 | + self.cmp_goto(out, &slow, depth + 1); |
| 1921 | + let _ = writeln!(out, "{ind}}}"); |
| 1922 | + // The arms, each under its label; none falls through (each ends |
| 1923 | + // in a jump or a return, as a `switch`'s cases do). |
| 1924 | + let mut after = None; |
| 1925 | + let line = self.line; |
| 1926 | + for ((_, target), label) in chain.iter().zip(&labels) { |
| 1927 | + self.line = line; |
| 1928 | + self.sync_line(out); |
| 1929 | + if let Some(body) = target { |
| 1930 | + let _ = writeln!(out, "{ind}c{label}: {{"); |
| 1931 | + let a = self.expr(out, f, body, dest, held.clone(), depth + 1)?; |
| 1932 | + after = after.or(a); |
| 1933 | + let _ = writeln!(out, "{ind}}}"); |
| 1934 | + } |
| 1935 | + } |
| 1936 | + Ok(after) |
| 1937 | + } |
| 1938 | + |
| 1939 | + /// A fresh label number within the function. |
| 1940 | + fn label(&mut self) -> u32 { |
| 1941 | + self.labels += 1; |
| 1942 | + self.labels |
| 1943 | + } |
| 1944 | + |
| 1945 | + /// A dispatch chain: `if (cond) { goto cN; } else if … else { … }`, |
| 1946 | + /// the last entry unconditional (None target: the tag is |
| 1947 | + /// unreachable). A single-entry chain is just the jump. |
| 1948 | + fn cmp_goto(&mut self, out: &mut String, chain: &[(String, Option<u32>)], depth: usize) { |
| 1949 | + let ind = " ".repeat(depth); |
| 1950 | + let n = chain.len(); |
| 1951 | + for (i, (cond, target)) in chain.iter().enumerate() { |
| 1952 | + let body = match target { |
| 1953 | + Some(l) => format!("goto c{l};"), |
| 1954 | + None => "__builtin_unreachable();".to_owned(), |
| 1955 | + }; |
| 1956 | + if n == 1 { |
| 1957 | + let _ = writeln!(out, "{ind}{body}"); |
| 1958 | + } else if i == 0 { |
| 1959 | + let _ = writeln!(out, "{ind}if ({cond}) {{ {body} }}"); |
| 1960 | + } else if i + 1 == n { |
| 1961 | + let _ = writeln!(out, "{ind}else {{ {body} }}"); |
| 1962 | + } else { |
| 1963 | + let _ = writeln!(out, "{ind}else if ({cond}) {{ {body} }}"); |
| 1964 | + } |
| 1965 | + } |
| 1966 | + } |
| 1967 | + |
| 1968 | + /// A compare-and-branch chain: `if (cond) {arm} else if … else |
| 1969 | + /// {arm}`; an arm a tag has no case for is `__builtin_unreachable`. |
| 1970 | + fn cmp_arms( |
| 1971 | + &mut self, |
| 1972 | + out: &mut String, |
| 1973 | + f: &Func, |
| 1974 | + chain: &[(String, Option<&Expr>)], |
| 1975 | + dest: Dest, |
| 1976 | + held: Vec<VarId>, |
| 1977 | + depth: usize, |
| 1978 | + ) -> Result<Option<Vec<VarId>>, Unsupported> { |
| 1979 | + let ind = " ".repeat(depth); |
| 1980 | + let line = self.line; |
| 1981 | + let mut after = None; |
| 1982 | + let n = chain.len(); |
| 1983 | + for (i, (cond, target)) in chain.iter().enumerate() { |
| 1984 | + self.line = line; |
| 1985 | + self.sync_line(out); |
| 1986 | + if n == 1 { |
| 1987 | + let _ = writeln!(out, "{ind}{{"); |
| 1988 | + } else if i == 0 { |
| 1989 | + let _ = writeln!(out, "{ind}if ({cond}) {{"); |
| 1990 | + } else if i + 1 == n { |
| 1991 | + let _ = writeln!(out, "{ind}}} else {{"); |
| 1992 | + } else { |
| 1993 | + let _ = writeln!(out, "{ind}}} else if ({cond}) {{"); |
| 1994 | + } |
| 1995 | + let a = match target { |
| 1996 | + Some(body) => self.expr(out, f, body, dest, held.clone(), depth + 1)?, |
| 1997 | + None => { |
| 1998 | + let _ = writeln!(out, "{ind} __builtin_unreachable();"); |
| 1999 | + None |
| 2000 | + } |
| 2001 | + }; |
| 2002 | + after = after.or(a); |
| 2003 | + } |
| 2004 | + self.line = line; |
| 2005 | + self.sync_line(out); |
| 2006 | + let _ = writeln!(out, "{ind}}}"); |
| 2007 | + Ok(after) |
| 2008 | + } |
| 2009 | + |
| 1252 | 2010 | /// A switch on the tag of `on`: a C `switch`, each branch emitted |
| 1253 | 2011 | /// towards `dest` with what the frame holds before it. Returns the |
| 1254 | 2012 | /// references held after it (those of a branch that reaches the end |
| @@ -1259,7 +2017,7 @@ int main(int argc, char **argv) {{ |
| 1259 | 2017 | out: &mut String, |
| 1260 | 2018 | f: &Func, |
| 1261 | 2019 | on: &Atom, |
| 1262 | | − cases: &[(u32, Expr)], |
| 2020 | + cases: &[(u32, &Expr)], |
| 1263 | 2021 | default: Option<&Expr>, |
| 1264 | 2022 | dest: Dest, |
| 1265 | 2023 | held: Vec<VarId>, |