| @@ -0,0 +1,650 @@ |
| 1 | +//! Fast integer paths (ADR 0046 piece 3, issue #191): range analysis. |
| 2 | +//! |
| 3 | +//! `tl_int_add` and friends check two things per operation: the operands' |
| 4 | +//! tags, and the result's overflow (which promotes to a big integer). |
| 5 | +//! Both are cheap branches, and both are wasted work when the answer is |
| 6 | +//! known: a loop counter or accumulator that provably stays small. When |
| 7 | +//! every operand of an add, subtract or multiply is proven to be a small |
| 8 | +//! integer with room to spare, the C backend emits the operation without |
| 9 | +//! the checks (`tl_int_add_unchecked` in the generated prelude), which |
| 10 | +//! cannot overflow and never promotes — exactly what the checked path |
| 11 | +//! computes in that case, so the interpreter's semantics are unchanged. |
| 12 | +//! |
| 13 | +//! The analysis is an interval pass over the whole program: a value is |
| 14 | +//! `Small(lo, hi)` (proven a small integer in the inclusive range), |
| 15 | +//! `Big` (unknown — maybe a big integer, maybe not an Int at all) or |
| 16 | +//! `Bottom` (no observation yet, the fixpoint's seed). Parameters get |
| 17 | +//! their ranges from every direct call site, iterated to a fixpoint over |
| 18 | +//! the call graph; loops (recursion) converge by widening to coarse |
| 19 | +//! thresholds — which is all the proof needs, since safety only asks |
| 20 | +//! |value| ≤ 2^60, never exactness. Guards refine the arms of a `switch` |
| 21 | +//! on a comparison (`sum_to`'s `i > n` bounds the counter's growth). |
| 22 | + |
| 23 | +use std::collections::{BTreeSet, HashMap}; |
| 24 | + |
| 25 | +use louise_core::ir::{Atom, Expr, FnDecl, FnId, Lit, Prim, Program, Value, VarId}; |
| 26 | + |
| 27 | +/// A value as an untagged Int. `Small(lo, hi)`: proven a small integer |
| 28 | +/// in `[lo, hi]`. `Big`: unknown. `Bottom`: nothing observed yet. |
| 29 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 30 | +enum Range { |
| 31 | + Bottom, |
| 32 | + Small(i64, i64), |
| 33 | + Big, |
| 34 | +} |
| 35 | + |
| 36 | +/// The most a small int is: `-2^62..=2^62-1` (the low bit is the tag). |
| 37 | +const SMALL_MAX: i64 = (1 << 62) - 1; |
| 38 | +/// Add and subtract skip their checks when both operands stay within |
| 39 | +/// this: two tagged values within 2^60 give a tagged result within |
| 40 | +/// 2^61 + 1, which cannot overflow an i64, and the untagged result is a |
| 41 | +/// small int. |
| 42 | +const ADD_SAFE: i64 = 1 << 60; |
| 43 | +/// Multiply likewise, when `|x * y| ≤ 2^60`. |
| 44 | +const MUL_SAFE: i64 = 1 << 30; |
| 45 | +/// Widening thresholds, past which a still-growing bound is `Big`. |
| 46 | +const WIDEN_TO: [i64; 3] = [1 << 8, 1 << 16, 1 << 31]; |
| 47 | + |
| 48 | +impl Range { |
| 49 | + fn of(n: i64) -> Range { |
| 50 | + match n.checked_abs() { |
| 51 | + Some(a) if a <= SMALL_MAX => Range::Small(n, n), |
| 52 | + _ => Range::Big, |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + /// Union (both observations possible), the fixpoint's direction. |
| 57 | + fn join(self, other: Range) -> Range { |
| 58 | + match (self, other) { |
| 59 | + (Range::Bottom, r) | (r, Range::Bottom) => r, |
| 60 | + (Range::Big, _) | (_, Range::Big) => Range::Big, |
| 61 | + (Range::Small(a, b), Range::Small(c, d)) => Range::Small(a.min(c), b.max(d)), |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + /// The part of the range within `[lo, hi]` (a guard arm's |
| 66 | + /// condition). `Big` stays `Big`: unknown could be a big integer, |
| 67 | + /// for which the guard's comparison is meaningful. An empty |
| 68 | + /// intersection becomes `Big` too: the arm may be dead code, which |
| 69 | + /// is still emitted. |
| 70 | + fn meet(self, lo: i64, hi: i64) -> Range { |
| 71 | + match self { |
| 72 | + Range::Small(a, b) if a.max(lo) <= b.min(hi) => Range::Small(a.max(lo), b.min(hi)), |
| 73 | + Range::Small(..) => Range::Big, |
| 74 | + r => r, |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + /// The arithmetic, saturating to `Big` past the small-int range (the |
| 79 | + /// checked path promotes there, so the result is not provably small). |
| 80 | + /// `Bottom` stays `Bottom`: nothing has been observed *yet* — the |
| 81 | + /// fixpoint's next round computes this again with the observations. |
| 82 | + fn arith(self, other: Range, f: impl FnOnce(i128, i128, i128, i128) -> (i128, i128)) -> Range { |
| 83 | + match (self, other) { |
| 84 | + (Range::Bottom, _) | (_, Range::Bottom) => Range::Bottom, |
| 85 | + (Range::Small(alo, ahi), Range::Small(blo, bhi)) => { |
| 86 | + let (lo, hi) = f(alo.into(), ahi.into(), blo.into(), bhi.into()); |
| 87 | + if lo < -(SMALL_MAX as i128) || hi > SMALL_MAX as i128 { |
| 88 | + Range::Big |
| 89 | + } else { |
| 90 | + Range::Small(lo as i64, hi as i64) |
| 91 | + } |
| 92 | + } |
| 93 | + _ => Range::Big, |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + fn add(self, other: Range) -> Range { |
| 98 | + self.arith(other, |alo, ahi, blo, bhi| (alo + blo, ahi + bhi)) |
| 99 | + } |
| 100 | + |
| 101 | + fn sub(self, other: Range) -> Range { |
| 102 | + self.arith(other, |alo, ahi, blo, bhi| (alo - bhi, ahi - blo)) |
| 103 | + } |
| 104 | + |
| 105 | + fn mul(self, other: Range) -> Range { |
| 106 | + self.arith(other, |alo, ahi, blo, bhi| { |
| 107 | + let ps = [alo * blo, alo * bhi, ahi * blo, ahi * bhi]; |
| 108 | + (*ps.iter().min().unwrap(), *ps.iter().max().unwrap()) |
| 109 | + }) |
| 110 | + } |
| 111 | + |
| 112 | + /// Division's and remainder's result where they return at all (a |
| 113 | + /// zero divisor panics, and a panic produces no value): the |
| 114 | + /// magnitude never exceeds the dividend's. |
| 115 | + fn shrink(self) -> Range { |
| 116 | + match self { |
| 117 | + Range::Small(lo, hi) => { |
| 118 | + let m = lo |
| 119 | + .unsigned_abs() |
| 120 | + .max(hi.unsigned_abs()) |
| 121 | + .min(SMALL_MAX as u64) as i64; |
| 122 | + Range::Small(-m, m) |
| 123 | + } |
| 124 | + r => r, |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + /// Whether an `add`/`sub` on two operands of these ranges skips its |
| 129 | + /// checks. |
| 130 | + fn add_safe(self, other: Range) -> bool { |
| 131 | + let ok = |r: Range| match r { |
| 132 | + Range::Small(lo, hi) => { |
| 133 | + lo.unsigned_abs() <= ADD_SAFE as u64 && hi.unsigned_abs() <= ADD_SAFE as u64 |
| 134 | + } |
| 135 | + _ => false, |
| 136 | + }; |
| 137 | + ok(self) && ok(other) |
| 138 | + } |
| 139 | + |
| 140 | + /// Whether a `mul` does. |
| 141 | + fn mul_safe(self, other: Range) -> bool { |
| 142 | + let ok = |r: Range| match r { |
| 143 | + Range::Small(lo, hi) => { |
| 144 | + lo.unsigned_abs() <= MUL_SAFE as u64 && hi.unsigned_abs() <= MUL_SAFE as u64 |
| 145 | + } |
| 146 | + _ => false, |
| 147 | + }; |
| 148 | + ok(self) && ok(other) |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +/// The proven ranges of a program: every variable's, per function. |
| 153 | +pub(crate) struct Ranges { |
| 154 | + vars: Vec<Vec<Range>>, |
| 155 | +} |
| 156 | + |
| 157 | +impl Ranges { |
| 158 | + /// The unchecked prelude name for `sym(a, b)`, when the operands are |
| 159 | + /// proven small enough that it cannot overflow (ADR 0046 piece 3). |
| 160 | + pub(crate) fn unchecked(&self, f: FnId, sym: &str, args: &[Atom]) -> Option<&'static str> { |
| 161 | + let (Some(a), Some(b)) = (args.first(), args.get(1)) else { |
| 162 | + return None; |
| 163 | + }; |
| 164 | + let (a, b) = (self.atom(f, a), self.atom(f, b)); |
| 165 | + match sym { |
| 166 | + "tl_int_add" if a.add_safe(b) => Some("tl_int_add_unchecked"), |
| 167 | + "tl_int_sub" if a.add_safe(b) => Some("tl_int_sub_unchecked"), |
| 168 | + "tl_int_mul" if a.mul_safe(b) => Some("tl_int_mul_unchecked"), |
| 169 | + _ => None, |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + /// The range analysis that proves nothing (the `LOUISE_NO_FAST_INTS` |
| 174 | + /// build). |
| 175 | + pub(crate) fn empty() -> Ranges { |
| 176 | + Ranges { vars: Vec::new() } |
| 177 | + } |
| 178 | + |
| 179 | + fn atom(&self, f: FnId, a: &Atom) -> Range { |
| 180 | + match a { |
| 181 | + Atom::Lit(Lit::Int(n)) => Range::of(*n), |
| 182 | + Atom::Var(v) => self |
| 183 | + .vars |
| 184 | + .get(f as usize) |
| 185 | + .and_then(|vars| vars.get(*v as usize)) |
| 186 | + .copied() |
| 187 | + .unwrap_or(Range::Big), |
| 188 | + _ => Range::Big, |
| 189 | + } |
| 190 | + } |
| 191 | +} |
| 192 | + |
| 193 | +/// Compute the program's ranges: parameters from every direct call site |
| 194 | +/// (a fixpoint over the call graph), then each function's locals with |
| 195 | +/// those seeds. Entries and closure-called functions have unknown |
| 196 | +/// callers; so does anything only ever called with unknown values. |
| 197 | +pub(crate) fn analyse(program: &Program, entries: &[FnId], reachable: &BTreeSet<FnId>) -> Ranges { |
| 198 | + let mut params: Vec<Vec<Range>> = program |
| 199 | + .fns |
| 200 | + .iter() |
| 201 | + .map(|f| vec![Range::Bottom; f.params.len()]) |
| 202 | + .collect(); |
| 203 | + // Entries, closure values and the constant dictionaries' methods: |
| 204 | + // their callers are not direct `CallFn` sites. |
| 205 | + let mut unknown: BTreeSet<FnId> = entries.iter().copied().collect(); |
| 206 | + for &f in reachable { |
| 207 | + visit_closures(&program.fns[f as usize].body, &mut |g| { |
| 208 | + unknown.insert(g); |
| 209 | + }); |
| 210 | + } |
| 211 | + for &f in &unknown { |
| 212 | + params[f as usize].fill(Range::Big); |
| 213 | + } |
| 214 | + // Iterate the call sites to a fixpoint, widening the bounds that keep |
| 215 | + // growing (a loop's counter would otherwise iterate once per |
| 216 | + // element). The result is a post-fixpoint by construction: an |
| 217 | + // iteration changed nothing only when every call site's contribution |
| 218 | + // is already covered. |
| 219 | + let mut grew: HashMap<(FnId, usize), u8> = HashMap::new(); |
| 220 | + loop { |
| 221 | + let mut changed = false; |
| 222 | + for &f in reachable { |
| 223 | + let mut local = Local::new(&program.fns[f as usize], ¶ms, f); |
| 224 | + local.walk(&program.fns[f as usize].body); |
| 225 | + for (g, site) in local.sites { |
| 226 | + for (i, r) in site.into_iter().enumerate() { |
| 227 | + let Some(slot) = params[g as usize].get_mut(i) else { |
| 228 | + continue; |
| 229 | + }; |
| 230 | + let next = slot.join(r); |
| 231 | + if std::env::var_os("RANGE_DEBUG").is_some() { |
| 232 | + eprintln!("site: {f} -> {g}[{i}]: {r:?} (was {:?})", *slot); |
| 233 | + } |
| 234 | + if next != *slot { |
| 235 | + *slot = widen(*slot, next, grew.entry((g, i)).or_default()); |
| 236 | + changed = true; |
| 237 | + } |
| 238 | + } |
| 239 | + } |
| 240 | + } |
| 241 | + if !changed { |
| 242 | + break; |
| 243 | + } |
| 244 | + } |
| 245 | + // The locals, with the parameters' final ranges. |
| 246 | + let vars = (0..program.fns.len() as FnId) |
| 247 | + .map(|f| { |
| 248 | + let decl = &program.fns[f as usize]; |
| 249 | + if reachable.contains(&f) { |
| 250 | + let mut local = Local::new(decl, ¶ms, f); |
| 251 | + local.walk(&decl.body); |
| 252 | + local.env |
| 253 | + } else { |
| 254 | + vec![Range::Big; decl.n_vars as usize] |
| 255 | + } |
| 256 | + }) |
| 257 | + .collect(); |
| 258 | + Ranges { vars } |
| 259 | +} |
| 260 | + |
| 261 | +/// Snap a growing bound to the next widening threshold, or `Big` past |
| 262 | +/// the last one — never narrower than the incoming value, so the |
| 263 | +/// fixpoint's growth is monotone and the loop terminates. |
| 264 | +/// `count` counts this parameter's growing iterations. |
| 265 | +fn widen(old: Range, new: Range, count: &mut u8) -> Range { |
| 266 | + let (Range::Small(lo, hi), Range::Small(olo, ohi)) = (new, old) else { |
| 267 | + return new; // Bottom's first observation, or Big: not growth. |
| 268 | + }; |
| 269 | + *count = count.saturating_add(1); |
| 270 | + if *count < 3 { |
| 271 | + return Range::Small(lo, hi); |
| 272 | + } |
| 273 | + let snap_hi = |hi: i64| { |
| 274 | + WIDEN_TO |
| 275 | + .iter() |
| 276 | + .find(|&&t| hi <= t) |
| 277 | + .copied() |
| 278 | + .unwrap_or(if hi <= ADD_SAFE { ADD_SAFE } else { i64::MAX }) |
| 279 | + }; |
| 280 | + let snap_lo = |lo: i64| { |
| 281 | + WIDEN_TO |
| 282 | + .iter() |
| 283 | + .find(|&&t| lo >= -t) |
| 284 | + .copied() |
| 285 | + .map_or(if lo >= -ADD_SAFE { -ADD_SAFE } else { i64::MIN }, |t| -t) |
| 286 | + }; |
| 287 | + let (lo, hi) = ( |
| 288 | + if lo < olo { snap_lo(lo) } else { lo }, |
| 289 | + if hi > ohi { snap_hi(hi) } else { hi }, |
| 290 | + ); |
| 291 | + // Past the last threshold: `Big` (which nothing leaves). |
| 292 | + if lo == i64::MIN || lo < -ADD_SAFE || hi == i64::MAX || hi > ADD_SAFE { |
| 293 | + return Range::Big; |
| 294 | + } |
| 295 | + Range::Small(lo, hi) |
| 296 | +} |
| 297 | + |
| 298 | +/// Call `f` on every function made into a closure in `e`. |
| 299 | +fn visit_closures(e: &Expr, f: &mut impl FnMut(FnId)) { |
| 300 | + match e { |
| 301 | + Expr::Let(_, value, rest, _) => { |
| 302 | + match &**value { |
| 303 | + Value::Closure(g, _) => f(*g), |
| 304 | + Value::Block(inner) => visit_closures(inner, f), |
| 305 | + _ => {} |
| 306 | + } |
| 307 | + visit_closures(rest, f); |
| 308 | + } |
| 309 | + Expr::LetN(_, value, rest, _) => { |
| 310 | + if let Value::Closure(g, _) = &**value { |
| 311 | + f(*g); |
| 312 | + } |
| 313 | + visit_closures(rest, f); |
| 314 | + } |
| 315 | + Expr::Switch { cases, default, .. } => { |
| 316 | + for (_, b) in cases { |
| 317 | + visit_closures(b, f); |
| 318 | + } |
| 319 | + if let Some(d) = default { |
| 320 | + visit_closures(d, f); |
| 321 | + } |
| 322 | + } |
| 323 | + Expr::SwitchLit { cases, default, .. } => { |
| 324 | + for (_, b) in cases { |
| 325 | + visit_closures(b, f); |
| 326 | + } |
| 327 | + visit_closures(default, f); |
| 328 | + } |
| 329 | + Expr::Dup(_, rest) | Expr::Drop(_, rest) | Expr::Release { rest, .. } => { |
| 330 | + visit_closures(rest, f) |
| 331 | + } |
| 332 | + Expr::Return(_) | Expr::Exit(_) | Expr::ReturnN(_) | Expr::Panic(_) => {} |
| 333 | + } |
| 334 | +} |
| 335 | + |
| 336 | +/// The forward walk of one function: every variable's range at its |
| 337 | +/// binding, and every direct call site's argument ranges. |
| 338 | +struct Local { |
| 339 | + /// The enclosing function. |
| 340 | + f: FnId, |
| 341 | + env: Vec<Range>, |
| 342 | + /// The call sites: callee, then its arguments' ranges. |
| 343 | + sites: Vec<(FnId, Vec<Range>)>, |
| 344 | + /// `let c = tl_int_compare(x, y)` (operands may be literals). |
| 345 | + compares: HashMap<VarId, (Atom, Atom)>, |
| 346 | + /// `let b = TagIs(t)(c)`. |
| 347 | + tag_is: HashMap<VarId, (u32, VarId)>, |
| 348 | +} |
| 349 | + |
| 350 | +impl Local { |
| 351 | + fn new(decl: &FnDecl, params: &[Vec<Range>], f: FnId) -> Local { |
| 352 | + let mut env = vec![Range::Big; decl.n_vars as usize]; |
| 353 | + for (i, p) in decl.params.iter().enumerate() { |
| 354 | + if let Some(&r) = params[f as usize].get(i) { |
| 355 | + env[*p as usize] = r; |
| 356 | + } |
| 357 | + } |
| 358 | + Local { |
| 359 | + f, |
| 360 | + env, |
| 361 | + sites: Vec::new(), |
| 362 | + compares: HashMap::new(), |
| 363 | + tag_is: HashMap::new(), |
| 364 | + } |
| 365 | + } |
| 366 | + |
| 367 | + /// A fresh walk state for a `switch` arm: the environment cloned (a |
| 368 | + /// refinement is the arm's own), the guard tables shared. |
| 369 | + fn fork(&self) -> Local { |
| 370 | + Local { |
| 371 | + f: self.f, |
| 372 | + env: self.env.clone(), |
| 373 | + sites: Vec::new(), |
| 374 | + compares: self.compares.clone(), |
| 375 | + tag_is: self.tag_is.clone(), |
| 376 | + } |
| 377 | + } |
| 378 | + |
| 379 | + fn absorb(&mut self, arm: Local) { |
| 380 | + self.sites.extend(arm.sites); |
| 381 | + } |
| 382 | + |
| 383 | + fn atom(&self, a: &Atom) -> Range { |
| 384 | + match a { |
| 385 | + Atom::Lit(Lit::Int(n)) => Range::of(*n), |
| 386 | + Atom::Var(v) => self.env.get(*v as usize).copied().unwrap_or(Range::Big), |
| 387 | + _ => Range::Big, |
| 388 | + } |
| 389 | + } |
| 390 | + |
| 391 | + /// The range of a bound value. |
| 392 | + fn value(&mut self, value: &Value) -> Range { |
| 393 | + match value { |
| 394 | + Value::Atom(a) => self.atom(a), |
| 395 | + Value::CallExtern(sym, args) => { |
| 396 | + let a = args.first().map(|a| self.atom(a)).unwrap_or(Range::Big); |
| 397 | + let b = args.get(1).map(|b| self.atom(b)).unwrap_or(Range::Big); |
| 398 | + match sym.as_str() { |
| 399 | + "tl_int_add" => a.add(b), |
| 400 | + "tl_int_sub" => a.sub(b), |
| 401 | + "tl_int_mul" => a.mul(b), |
| 402 | + "tl_int_div" | "tl_int_rem" => a.shrink(), |
| 403 | + "tl_int_eq" => Range::Small(0, 1), |
| 404 | + "tl_int_compare" => Range::Small(0, 2), |
| 405 | + _ => Range::Big, |
| 406 | + } |
| 407 | + } |
| 408 | + Value::CallFn(g, args) => { |
| 409 | + self.sites |
| 410 | + .push((*g, args.iter().map(|a| self.atom(a)).collect())); |
| 411 | + Range::Big // a call's result is unknown (v1) |
| 412 | + } |
| 413 | + // `TagIs` and `Not` produce Bools (small ints 0 and 1). |
| 414 | + Value::Prim(Prim::TagIs(_), _) | Value::Prim(Prim::Not, _) => Range::Small(0, 1), |
| 415 | + // A block's value is its end's; its lets are block-local, but |
| 416 | + // their ranges stay recorded (out-of-scope code reads none). |
| 417 | + Value::Block(inner) => { |
| 418 | + let saved = self.env.clone(); |
| 419 | + let r = self.walk(inner); |
| 420 | + self.env = saved; |
| 421 | + r |
| 422 | + } |
| 423 | + _ => Range::Big, |
| 424 | + } |
| 425 | + } |
| 426 | + |
| 427 | + /// Walk a chain, returning the value it produces (its `Return`'s, |
| 428 | + /// the arms' joined at a switch). |
| 429 | + fn walk(&mut self, e: &Expr) -> Range { |
| 430 | + let mut e = e; |
| 431 | + loop { |
| 432 | + match e { |
| 433 | + Expr::Let(v, value, rest, _) => { |
| 434 | + let r = self.value(value); |
| 435 | + // Guard chains: `let c = compare(x, y)`, then |
| 436 | + // `let b = TagIs(t)(c)`, then `switch b`. |
| 437 | + match &**value { |
| 438 | + Value::CallExtern(sym, args) if sym == "tl_int_compare" && args.len() == 2 => { |
| 439 | + self.compares.insert(*v, (args[0].clone(), args[1].clone())); |
| 440 | + } |
| 441 | + Value::Prim(Prim::TagIs(t), args) => { |
| 442 | + if let Some(Atom::Var(c)) = args.first() { |
| 443 | + self.tag_is.insert(*v, (*t, *c)); |
| 444 | + } |
| 445 | + } |
| 446 | + _ => {} |
| 447 | + } |
| 448 | + self.env[*v as usize] = r; |
| 449 | + e = rest; |
| 450 | + } |
| 451 | + Expr::Switch { |
| 452 | + on, cases, default, .. |
| 453 | + } => { |
| 454 | + // The arm tagged 1 is the condition holding; the |
| 455 | + // default, after tag 1 was listed, its not holding. |
| 456 | + let true_arm = cases.iter().any(|(t, _)| *t == 1); |
| 457 | + let mut out = Range::Bottom; |
| 458 | + for (t, b) in cases { |
| 459 | + let mut arm = self.fork(); |
| 460 | + arm.refine(on, *t == 1); |
| 461 | + let r = arm.walk(b); |
| 462 | + out = out.join(r); |
| 463 | + self.absorb(arm); |
| 464 | + } |
| 465 | + if let Some(d) = default { |
| 466 | + let mut arm = self.fork(); |
| 467 | + arm.refine(on, !true_arm); |
| 468 | + let r = arm.walk(d); |
| 469 | + out = out.join(r); |
| 470 | + self.absorb(arm); |
| 471 | + } |
| 472 | + return out; |
| 473 | + } |
| 474 | + Expr::SwitchLit { cases, default, .. } => { |
| 475 | + let mut out = Range::Bottom; |
| 476 | + for (_, b) in cases { |
| 477 | + let mut arm = self.fork(); |
| 478 | + let r = arm.walk(b); |
| 479 | + out = out.join(r); |
| 480 | + self.absorb(arm); |
| 481 | + } |
| 482 | + let mut arm = self.fork(); |
| 483 | + let r = arm.walk(default); |
| 484 | + out = out.join(r); |
| 485 | + self.absorb(arm); |
| 486 | + return out; |
| 487 | + } |
| 488 | + Expr::LetN(vars, value, rest, _) => { |
| 489 | + self.value(value); |
| 490 | + for v in vars { |
| 491 | + self.env[*v as usize] = Range::Big; |
| 492 | + } |
| 493 | + e = rest; |
| 494 | + } |
| 495 | + Expr::Dup(_, rest) | Expr::Drop(_, rest) | Expr::Release { rest, .. } => e = rest, |
| 496 | + Expr::Return(a) => return self.atom(a), |
| 497 | + // An exit carries the function's value but produces none |
| 498 | + // here; a panic produces none. |
| 499 | + Expr::Exit(_) | Expr::ReturnN(_) | Expr::Panic(_) => return Range::Bottom, |
| 500 | + } |
| 501 | + } |
| 502 | + } |
| 503 | + |
| 504 | + /// Refine the environment for a `switch` arm: `on` is |
| 505 | + /// `TagIs(t)(compare(x, y))`; `matched` is whether the arm is the |
| 506 | + /// one where the condition holds. A literal side refines the other. |
| 507 | + fn refine(&mut self, on: &Atom, matched: bool) { |
| 508 | + let Atom::Var(b) = on else { return }; |
| 509 | + let Some(&(t, c)) = self.tag_is.get(b) else { |
| 510 | + return; |
| 511 | + }; |
| 512 | + let Some((x, y)) = self.compares.get(&c).cloned() else { |
| 513 | + return; |
| 514 | + }; |
| 515 | + let (Range::Small(xlo, xhi), Range::Small(ylo, yhi)) = |
| 516 | + (self.atom(&x), self.atom(&y)) |
| 517 | + else { |
| 518 | + return; |
| 519 | + }; |
| 520 | + // tl_int_compare's results: 0 is Lt, 1 is Eq, 2 is Gt. |
| 521 | + let cond = match (t, matched) { |
| 522 | + (2, true) => Cmp::Gt, |
| 523 | + (2, false) => Cmp::Le, |
| 524 | + (0, true) => Cmp::Lt, |
| 525 | + (0, false) => Cmp::Ge, |
| 526 | + (1, true) => Cmp::Eq, |
| 527 | + _ => return, // `!=` refines nothing on an interval |
| 528 | + }; |
| 529 | + let (nx, ny) = cond.refine(xlo, xhi, ylo, yhi); |
| 530 | + if let Atom::Var(xv) = x { |
| 531 | + self.env[xv as usize] = self.env[xv as usize].meet(nx.0, nx.1); |
| 532 | + } |
| 533 | + if let Atom::Var(yv) = y { |
| 534 | + self.env[yv as usize] = self.env[yv as usize].meet(ny.0, ny.1); |
| 535 | + } |
| 536 | + } |
| 537 | +} |
| 538 | + |
| 539 | +/// A comparison's condition on `x` against `y`. |
| 540 | +enum Cmp { |
| 541 | + Gt, |
| 542 | + Le, |
| 543 | + Lt, |
| 544 | + Ge, |
| 545 | + Eq, |
| 546 | +} |
| 547 | + |
| 548 | +impl Cmp { |
| 549 | + /// The intervals of x and y in an arm where the condition holds. |
| 550 | + fn refine(self, xlo: i64, xhi: i64, ylo: i64, yhi: i64) -> ((i64, i64), (i64, i64)) { |
| 551 | + match self { |
| 552 | + // x > y: x is at least y's lo + 1; y at most x's hi - 1. |
| 553 | + Cmp::Gt => ( |
| 554 | + (xlo.max(ylo.saturating_add(1)), xhi), |
| 555 | + (ylo, yhi.min(xhi.saturating_sub(1))), |
| 556 | + ), |
| 557 | + Cmp::Le => ((xlo, xhi.min(yhi)), (ylo.max(xlo), yhi)), |
| 558 | + Cmp::Lt => ( |
| 559 | + (xlo, xhi.min(yhi.saturating_sub(1))), |
| 560 | + (ylo.max(xlo.saturating_add(1)), yhi), |
| 561 | + ), |
| 562 | + Cmp::Ge => ((xlo.max(ylo), xhi), (ylo, yhi.min(xhi))), |
| 563 | + Cmp::Eq => ((xlo.max(ylo), xhi.min(yhi)), (xlo.max(ylo), xhi.min(yhi))), |
| 564 | + } |
| 565 | + } |
| 566 | +} |
| 567 | + |
| 568 | +#[cfg(test)] |
| 569 | +mod tests { |
| 570 | + use super::*; |
| 571 | + |
| 572 | + fn r(lo: i64, hi: i64) -> Range { |
| 573 | + Range::Small(lo, hi) |
| 574 | + } |
| 575 | + |
| 576 | + #[test] |
| 577 | + fn literals_and_their_edges() { |
| 578 | + assert_eq!(Range::of(41), r(41, 41)); |
| 579 | + assert_eq!(Range::of(SMALL_MAX), r(SMALL_MAX, SMALL_MAX)); |
| 580 | + assert_eq!(Range::of(-SMALL_MAX), r(-SMALL_MAX, -SMALL_MAX)); |
| 581 | + assert_eq!(Range::of(SMALL_MAX + 1), Range::Big); |
| 582 | + assert_eq!(Range::of(i64::MIN), Range::Big); |
| 583 | + } |
| 584 | + |
| 585 | + #[test] |
| 586 | + fn join_is_a_union() { |
| 587 | + assert_eq!(Range::Bottom.join(r(1, 2)), r(1, 2)); |
| 588 | + assert_eq!(r(1, 2).join(r(5, 7)), r(1, 7)); |
| 589 | + assert_eq!(r(1, 2).join(Range::Big), Range::Big); |
| 590 | + } |
| 591 | + |
| 592 | + #[test] |
| 593 | + fn arithmetic_saturates_at_the_small_range() { |
| 594 | + assert_eq!(r(1, 2).add(r(3, 4)), r(4, 6)); |
| 595 | + assert_eq!(r(1, 2).sub(r(3, 4)), r(-3, -1)); |
| 596 | + assert_eq!(r(2, 3).mul(r(4, 5)), r(8, 15)); |
| 597 | + assert_eq!(r(-3, -2).mul(r(4, 5)), r(-15, -8)); |
| 598 | + assert_eq!(r(0, SMALL_MAX).add(r(1, 1)), Range::Big); |
| 599 | + assert_eq!(r(0, SMALL_MAX).mul(r(2, 2)), Range::Big); |
| 600 | + } |
| 601 | + |
| 602 | + #[test] |
| 603 | + fn safety_margins() { |
| 604 | + assert!(r(0, ADD_SAFE).add_safe(r(-ADD_SAFE, 17))); |
| 605 | + assert!(!r(0, ADD_SAFE + 1).add_safe(r(0, 0))); |
| 606 | + assert!(!Range::Big.add_safe(r(0, 0))); |
| 607 | + assert!(r(-MUL_SAFE, MUL_SAFE).mul_safe(r(0, MUL_SAFE))); |
| 608 | + assert!(!r(0, MUL_SAFE + 1).mul_safe(r(1, 1))); |
| 609 | + } |
| 610 | + |
| 611 | + #[test] |
| 612 | + fn guards_refine_arms() { |
| 613 | + // x > y in the arm: x is at least y's lo + 1. |
| 614 | + assert_eq!(Cmp::Gt.refine(0, 10, 5, 20), ((6, 10), (5, 9))); |
| 615 | + // and where it does not: x ≤ y. |
| 616 | + assert_eq!(Cmp::Le.refine(0, 10, 5, 20), ((0, 10), (5, 20))); |
| 617 | + assert_eq!(Cmp::Eq.refine(0, 10, 5, 20), ((5, 10), (5, 10))); |
| 618 | + } |
| 619 | + |
| 620 | + #[test] |
| 621 | + fn widening_snaps_a_growing_bound() { |
| 622 | + let mut count = 2; // seen growing twice already |
| 623 | + assert_eq!(widen(r(0, 100), r(0, 130), &mut count), r(0, 1 << 8)); |
| 624 | + let mut count = 2; |
| 625 | + assert_eq!(widen(r(0, 300), r(0, 400), &mut count), r(0, 1 << 16)); |
| 626 | + let mut count = 2; |
| 627 | + // Past the last threshold is the add-safe margin, then Big. |
| 628 | + assert_eq!( |
| 629 | + widen(r(0, 1 << 20), r(0, 1 << 25), &mut count), |
| 630 | + r(0, 1 << 31) |
| 631 | + ); |
| 632 | + let mut count = 2; |
| 633 | + assert_eq!( |
| 634 | + widen(r(0, 1 << 40), r(0, 1 << 50), &mut count), |
| 635 | + r(0, ADD_SAFE) |
| 636 | + ); |
| 637 | + let mut count = 2; |
| 638 | + // Past the margin: Big, and it never leaves (the fixpoint |
| 639 | + // terminates). |
| 640 | + assert_eq!(widen(r(0, 1 << 61), r(0, 1 << 62), &mut count), Range::Big); |
| 641 | + let mut count = 2; |
| 642 | + assert_eq!(widen(r(0, ADD_SAFE), Range::Big, &mut count), Range::Big); |
| 643 | + } |
| 644 | + |
| 645 | + #[test] |
| 646 | + fn division_shrinks() { |
| 647 | + assert_eq!(r(-10, 26).shrink(), r(-26, 26)); |
| 648 | + assert_eq!(Range::Big.shrink(), Range::Big); |
| 649 | + } |
| 650 | +} |